ServeManagementController.py 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import calendar
  4. import datetime
  5. import hashlib
  6. import time
  7. import uuid
  8. import paypalrestsdk
  9. import requests
  10. import xlrd
  11. import xlwt
  12. from django.db import transaction, connection
  13. from django.db.models import F, Sum, Count, Q
  14. from django.http import HttpResponse, StreamingHttpResponse
  15. from django.utils.encoding import escape_uri_path
  16. from django.views.generic.base import View
  17. from Ansjer.config import PAYPAL_CRD
  18. from Controller.Cron.CronTaskController import CronUpdateDataView
  19. from Controller.UnicomCombo.UnicomComboTaskController import UnicomComboTaskView
  20. from Model.models import VodBucketModel, CDKcontextModel, Store_Meal, Order_Model, \
  21. UID_Bucket, ExperienceContextModel, Lang, CloudLogModel, UidSetModel, Unused_Uid_Meal, \
  22. Device_Info, DeviceTypeModel, UnicomComboOrderInfo, AiService, CountryModel, CouponLang, CouponConfigModel, \
  23. CouponCombo, CouponModel, Device_User, AbnormalOrder
  24. from Object.ResponseObject import ResponseObject
  25. from Object.TokenObject import TokenObject
  26. from Object.UnicomObject import UnicomObjeect
  27. from Service.CommonService import CommonService
  28. class serveManagement(View):
  29. def get(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. return self.validation(request.GET, request, operation)
  33. def post(self, request, *args, **kwargs):
  34. request.encoding = 'utf-8'
  35. operation = kwargs.get('operation')
  36. return self.validation(request.POST, request, operation)
  37. def validation(self, request_dict, request, operation):
  38. language = request_dict.get('language', 'en')
  39. response = ResponseObject(language, 'pc')
  40. if operation == 'exportCloudUserList': # 导出云存用户信息
  41. return self.exportCloudUserList(request_dict, response)
  42. elif operation == 'getCloudDataList':
  43. return self.getCloudDataList(request_dict, response)
  44. elif operation == 'vodOrderReconcile':
  45. return self.vodOrderReconcile(request, request_dict, response)
  46. elif operation == 'cloudDataExport': # 导出流失预警
  47. return self.cloudDataExport(request, response)
  48. else:
  49. tko = TokenObject(
  50. request.META.get('HTTP_AUTHORIZATION'),
  51. returntpye='pc')
  52. if tko.code != 0:
  53. return response.json(tko.code)
  54. response.lang = tko.lang
  55. userID = tko.userID
  56. if operation == 'getVodBucketList':
  57. return self.getVodBucketList(userID, request_dict, response)
  58. elif operation == 'addOrEditVodBucket':
  59. return self.addOrEditVodBucket(userID, request_dict, response)
  60. elif operation == 'deleteVodBucket':
  61. return self.deleteVodBucket(userID, request_dict, response)
  62. elif operation == 'getStoreMealList':
  63. return self.getStoreMealList(userID, request_dict, response)
  64. elif operation == 'addOrEditStoreMeal':
  65. return self.addOrEditStoreMeal(userID, request_dict, response)
  66. elif operation == 'deleteStoreMeal':
  67. return self.deleteStoreMeal(userID, request_dict, response)
  68. elif operation == 'getStoreMealLanguage':
  69. return self.getStoreMealLanguage(
  70. userID, request_dict, response)
  71. elif operation == 'addOrEditStoreMealLanguage':
  72. return self.addOrEditStoreMealLanguage(
  73. userID, request_dict, response)
  74. elif operation == 'deleteStoreMealLanguage':
  75. return self.deleteStoreMealLanguage(
  76. userID, request_dict, response)
  77. # CDK
  78. elif operation == 'getCdkList':
  79. return self.getCdkList(userID, request_dict, response)
  80. elif operation == 'createCdk':
  81. return self.createCdk(request_dict, response)
  82. elif operation == 'getVodStoreMeal':
  83. return self.getVodStoreMeal(response)
  84. elif operation == 'editExpress':
  85. return self.editExpress(request_dict, response)
  86. elif operation == 'deleteCdk':
  87. return self.deleteCdk(request_dict, response)
  88. elif operation == 'downloadCDK':
  89. return self.downloadCDK(request_dict, response)
  90. # 优惠券
  91. elif operation == 'getCouponList': # 查询优惠券
  92. return self.getCouponList(request_dict, response)
  93. elif operation == 'getCouponId': # 查询优惠券id
  94. return self.getCouponId(response)
  95. elif operation == 'addOrEditCoupon': # 添加/编辑优惠券
  96. return self.addOrEditCoupon(request_dict, response)
  97. elif operation == 'deleteCoupon': # 删除优惠券
  98. return self.deleteCoupon(request_dict, response)
  99. # 优惠券语言
  100. elif operation == 'getCouponLangList': # 查询优惠券语言
  101. return self.getCouponLangList(request_dict, response)
  102. elif operation == 'addOrEditCouponLang': # 添加/编辑优惠券语言
  103. return self.addOrEditCouponLang(request_dict, response)
  104. elif operation == 'deleteCouponLang': # 删除优惠券语言
  105. return self.deleteCouponLang(request_dict, response)
  106. # 优惠券使用
  107. elif operation == 'getCouponUsingList': # 查询优惠券使用
  108. return self.getCouponUsingList(request_dict, response)
  109. elif operation == 'editCouponUsing': # 编辑优惠券使用
  110. return self.editCouponUsing(request_dict, response)
  111. elif operation == 'deleteCouponUsing': # 删除优惠券使用
  112. return self.deleteCouponUsing(request_dict, response)
  113. elif operation == 'getDeviceOrderList':
  114. return self.getDeviceOrderList(request_dict, response)
  115. elif operation == 'getAbnormalOrderList':
  116. return self.getAbnormalOrderList(request_dict, response)
  117. elif operation == 'updateAbnormalOrder':
  118. return self.updateAbnormalOrder(request_dict, response)
  119. elif operation == 'deleteDeviceOrder':
  120. return self.deleteDeviceOrder(userID, request_dict, response)
  121. elif operation == 'getDevicePackageList': # 云存设备套餐
  122. return self.getDevicePackageList(request_dict, response)
  123. elif operation == 'deleteDevicePackage':
  124. return self.deleteDevicePackage(userID, request_dict, response)
  125. elif operation == 'experiencereset': # 重置设备云存体验
  126. return self.do_experience_reset(request_dict, userID, response)
  127. # 云存用户信息
  128. elif operation == 'getCloudUserList': # 获取云存用户信息
  129. return self.getCloudUserList(request_dict, response)
  130. elif operation == 'paypal-cycle-cancel': # 取消循环扣款
  131. return self.paypal_cycle_cancel(request_dict, response)
  132. elif operation == 'distributeCoupons': # 发放云存优惠券
  133. return self.distributeCoupons(request_dict, response)
  134. # 流失预警
  135. elif operation == 'deviceAttritionAlert':
  136. return self.deviceAttritionAlert(request_dict, response)
  137. elif operation == 'deactivationPackage': # 停用套餐
  138. return self.deactivationPackage(request_dict, response)
  139. else:
  140. return response.json(404)
  141. @staticmethod
  142. def paypal_cycle_cancel(request_dict, response):
  143. """
  144. 取消云存循环扣款
  145. """
  146. order_id = request_dict.get('orderID', None)
  147. if not order_id:
  148. return response.json(444)
  149. order_qs = Order_Model.objects.filter(orderID=order_id)
  150. order_qs = order_qs.filter(~Q(agreement_id='')).values("agreement_id")
  151. if not order_qs.exists():
  152. return response.json(800)
  153. paypalrestsdk.configure(PAYPAL_CRD)
  154. agreement_id = order_qs[0]['agreement_id']
  155. try:
  156. now_time = int(time.time())
  157. billing_agreement = paypalrestsdk.BillingAgreement.find(agreement_id)
  158. if billing_agreement.state != 'Active':
  159. Order_Model.objects.filter(agreement_id=agreement_id).update(agreement_id='', updTime=now_time)
  160. return response.json(0)
  161. cancel_note = {"note": "Canceling the agreement"}
  162. if billing_agreement.cancel(cancel_note):
  163. Order_Model.objects.filter(agreement_id=agreement_id).update(agreement_id='', updTime=now_time)
  164. return response.json(0)
  165. else:
  166. return response.json(10052)
  167. except Exception as e:
  168. print(repr(e))
  169. return response.json(10052)
  170. @staticmethod
  171. def distributeCoupons(request_dict, response):
  172. user_id = request_dict.get('userID', None)
  173. coupon_id = request_dict.get('couponID', None)
  174. valid_time = request_dict.get('validTime', None)
  175. if not all([user_id, coupon_id]):
  176. return response.json(444)
  177. now_time = int(time.time())
  178. try:
  179. CouponModel.objects.create(userID=user_id, coupon_config_id=coupon_id, valid_time=valid_time,
  180. distribute_time=now_time, create_time=now_time, update_time=now_time)
  181. return response.json(0)
  182. except Exception as e:
  183. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  184. def getVodBucketList(self, userID, request_dict, response):
  185. # 查询存储桶数据
  186. print('request_dict: ', request_dict)
  187. isSelect = request_dict.get('isSelect', None)
  188. if isSelect:
  189. # 获取全部数据作为存储桶选项
  190. vod_bucket_qs = VodBucketModel.objects.all().values('id', 'bucket')
  191. return response.json(
  192. 0, {'list': CommonService.qs_to_list(vod_bucket_qs)})
  193. bucket = request_dict.get('bucket', None)
  194. mold = request_dict.get('mold', None)
  195. is_free = request_dict.get('is_free', None)
  196. pageNo = request_dict.get('pageNo', None)
  197. pageSize = request_dict.get('pageSize', None)
  198. if not all([pageNo, pageSize]):
  199. return response.json(444)
  200. page = int(pageNo)
  201. line = int(pageSize)
  202. try:
  203. if bucket or mold or is_free: # 条件查询
  204. if bucket:
  205. vod_bucket_qs = VodBucketModel.objects.filter(
  206. bucket=bucket)
  207. elif mold:
  208. vod_bucket_qs = VodBucketModel.objects.filter(
  209. mold=int(mold))
  210. elif is_free:
  211. vod_bucket_qs = VodBucketModel.objects.filter(
  212. is_free=int(is_free))
  213. else: # 查询全部
  214. vod_bucket_qs = VodBucketModel.objects.filter().all()
  215. total = len(vod_bucket_qs)
  216. vod_buckets = vod_bucket_qs[(page - 1) * line:page * line]
  217. vod_bucket_list = []
  218. for vod_bucket in vod_buckets:
  219. vod_bucket_list.append({
  220. 'bucketID': vod_bucket.id,
  221. 'bucket': vod_bucket.bucket,
  222. 'content': vod_bucket.content,
  223. 'mold': vod_bucket.mold,
  224. 'area': vod_bucket.area,
  225. 'region': vod_bucket.region,
  226. 'endpoint': vod_bucket.endpoint,
  227. 'is_free': vod_bucket.is_free,
  228. 'storeDay': vod_bucket.storeDay,
  229. 'region_id': vod_bucket.region_id,
  230. 'addTime': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(vod_bucket.addTime)),
  231. 'updTime': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(vod_bucket.updTime)),
  232. })
  233. print('vod_bucket_list: ', vod_bucket_list)
  234. return response.json(
  235. 0, {'list': vod_bucket_list, 'total': total})
  236. except Exception as e:
  237. print(e)
  238. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  239. def addOrEditVodBucket(self, userID, request_dict, response):
  240. # 添加/编辑存储桶
  241. print('request_dict: ', request_dict)
  242. bucketID = request_dict.get('bucketID', None)
  243. bucket = request_dict.get('bucket', '').strip() # 移除字符串头尾的空格
  244. content = request_dict.get('content', '').strip()
  245. mold = int(request_dict.get('mold', 1))
  246. area = request_dict.get('area', '').strip()
  247. region = request_dict.get('region', '').strip()
  248. endpoint = request_dict.get('endpoint', '').strip()
  249. is_free = int(request_dict.get('is_free', 0))
  250. storeDay = int(request_dict.get('storeDay', 0))
  251. region_id = int(request_dict.get('region_id', 1))
  252. isEdit = request_dict.get('isEdit', None)
  253. if not all([bucket, content, area, region, endpoint]):
  254. return response.json(444)
  255. try:
  256. now_time = int(time.time())
  257. vod_bucket_data = {
  258. 'bucket': bucket,
  259. 'content': content,
  260. 'mold': mold,
  261. 'area': area,
  262. 'region': region,
  263. 'endpoint': endpoint,
  264. 'is_free': is_free,
  265. 'storeDay': storeDay,
  266. 'region_id': region_id,
  267. }
  268. if isEdit:
  269. if not bucketID:
  270. return response.json(444)
  271. vod_bucket_data['updTime'] = now_time
  272. VodBucketModel.objects.filter(
  273. id=bucketID).update(
  274. **vod_bucket_data)
  275. else:
  276. vod_bucket_data['addTime'] = now_time
  277. VodBucketModel.objects.create(**vod_bucket_data)
  278. return response.json(0)
  279. except Exception as e:
  280. print(e)
  281. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  282. def deleteVodBucket(self, userID, request_dict, response):
  283. # 删除存储桶
  284. print('request_dict: ', request_dict)
  285. bucketID = request_dict.get('bucketID', None)
  286. if not bucketID:
  287. return response.json(444)
  288. try:
  289. VodBucketModel.objects.filter(id=bucketID).delete()
  290. return response.json(0)
  291. except Exception as e:
  292. print(e)
  293. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  294. def getStoreMealList(self, userID, request_dict, response):
  295. # 获取云存套餐信息数据
  296. print('request_dict: ', request_dict)
  297. isSelect = request_dict.get('isSelect', None)
  298. if isSelect:
  299. # 获取套餐ID作为选项
  300. store_meal_qs = Store_Meal.objects.all().values('id', 'bucket__bucket')
  301. return response.json(
  302. 0, {'list': CommonService.qs_to_list(store_meal_qs)})
  303. bucket = request_dict.get('bucket', None)
  304. pageNo = request_dict.get('pageNo', None)
  305. pageSize = request_dict.get('pageSize', None)
  306. if not all([pageNo, pageSize]):
  307. return response.json(444)
  308. page = int(pageNo)
  309. line = int(pageSize)
  310. try:
  311. if bucket: # 条件查询
  312. bucket_id = VodBucketModel.objects.filter(
  313. bucket=bucket).values('id')[0]['id']
  314. store_meal_qs = Store_Meal.objects.filter(
  315. bucket_id=bucket_id)
  316. else: # 查询全部
  317. store_meal_qs = Store_Meal.objects.filter()
  318. store_meal_val = store_meal_qs.values(
  319. 'id',
  320. 'bucket__bucket',
  321. 'day',
  322. 'expire',
  323. 'commodity_type',
  324. 'commodity_code',
  325. 'is_discounts',
  326. 'discount_price',
  327. 'virtual_price',
  328. 'price',
  329. 'currency',
  330. 'symbol',
  331. 'is_show',
  332. 'is_ai',
  333. 'pixel_level',
  334. 'add_time',
  335. 'update_time')
  336. total = len(store_meal_val)
  337. store_meals = store_meal_val[(page - 1) * line:page * line]
  338. store_meal_list = []
  339. for store_meal in store_meals:
  340. # 获取支付方式列表
  341. pay_type_list = [
  342. pay_type['id'] for pay_type in Store_Meal.objects.get(
  343. id=store_meal['id']).pay_type.values('id')]
  344. # 组织响应数据
  345. store_meal_list.append({
  346. 'storeMealID': store_meal['id'],
  347. 'bucket': store_meal['bucket__bucket'],
  348. 'day': store_meal['day'],
  349. 'expire': store_meal['expire'],
  350. 'commodity_type': store_meal['commodity_type'],
  351. 'pay_type': pay_type_list,
  352. 'commodity_code': store_meal['commodity_code'],
  353. 'is_discounts': store_meal['is_discounts'],
  354. 'discount_price': store_meal['discount_price'],
  355. 'virtual_price': store_meal['virtual_price'],
  356. 'price': store_meal['price'],
  357. 'currency': store_meal['currency'],
  358. 'symbol': store_meal['symbol'],
  359. 'is_show': store_meal['is_show'],
  360. 'is_ai': store_meal['is_ai'],
  361. 'pixel_level': store_meal['pixel_level'],
  362. 'addTime': store_meal['add_time'].strftime("%Y-%m-%d %H:%M:%S"),
  363. 'updTime': store_meal['update_time'].strftime("%Y-%m-%d %H:%M:%S"),
  364. })
  365. print('store_meal_list: ', store_meal_list)
  366. return response.json(
  367. 0, {'list': store_meal_list, 'total': total})
  368. except Exception as e:
  369. print(e)
  370. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  371. def addOrEditStoreMeal(self, userID, request_dict, response):
  372. # 添加/编辑套餐
  373. print('request_dict: ', request_dict)
  374. storeMealID = request_dict.get('storeMealID', None)
  375. bucket = request_dict.get('bucket', '')
  376. day = int(request_dict.get('day', 0))
  377. expire = int(request_dict.get('expire', 0))
  378. commodity_type = int(request_dict.get('commodity_type', 0))
  379. pay_type = request_dict.get(
  380. 'pay_type', '')[
  381. 1:-1].split(',') # '[1,2]' -> ['1','2']
  382. commodity_code = request_dict.get('commodity_code', '')
  383. is_discounts = int(request_dict.get('is_discounts', 0))
  384. discount_price = request_dict.get('discount_price', '')
  385. virtual_price = request_dict.get('virtual_price', '')
  386. price = request_dict.get('price', '')
  387. currency = request_dict.get('currency', '')
  388. symbol = request_dict.get('symbol', '')
  389. is_show = int(request_dict.get('is_show', 0))
  390. is_ai = int(request_dict.get('is_ai', 0))
  391. pixel_level = int(request_dict.get('pixel_level', 0))
  392. isEdit = request_dict.get('isEdit', None)
  393. if not all([bucket, pay_type, price, currency, symbol]):
  394. return response.json(444)
  395. try:
  396. bucket_id = VodBucketModel.objects.filter(
  397. bucket=bucket).values('id')[0]['id']
  398. store_meal_data = {
  399. 'bucket_id': bucket_id,
  400. 'day': day,
  401. 'expire': expire,
  402. 'commodity_type': commodity_type,
  403. 'commodity_code': commodity_code,
  404. 'is_discounts': is_discounts,
  405. 'discount_price': discount_price,
  406. 'virtual_price': virtual_price,
  407. 'price': price,
  408. 'currency': currency,
  409. 'symbol': symbol,
  410. 'is_show': is_show,
  411. 'is_ai': is_ai,
  412. 'pixel_level': pixel_level,
  413. }
  414. if isEdit:
  415. if not storeMealID:
  416. return response.json(444)
  417. Store_Meal.objects.filter(
  418. id=storeMealID).update(
  419. **store_meal_data)
  420. Store_Meal.objects.get(id=storeMealID).pay_type.set(pay_type)
  421. else:
  422. Store_Meal.objects.create(
  423. **store_meal_data).pay_type.set(pay_type)
  424. return response.json(0)
  425. except Exception as e:
  426. print(e)
  427. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  428. def deleteStoreMeal(self, userID, request_dict, response):
  429. # 删除套餐信息
  430. print('request_dict: ', request_dict)
  431. storeMealID = request_dict.get('storeMealID', None)
  432. if not storeMealID:
  433. return response.json(444)
  434. try:
  435. Store_Meal.objects.filter(id=storeMealID).delete()
  436. return response.json(0)
  437. except Exception as e:
  438. print(e)
  439. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  440. def getStoreMealLanguage(self, userID, request_dict, response):
  441. # 获取套餐语言
  442. print('request_dict: ', request_dict)
  443. storeMealID = request_dict.get('storeMealID', None)
  444. pageNo = request_dict.get('pageNo', None)
  445. pageSize = request_dict.get('pageSize', None)
  446. if not all([pageNo, pageSize]):
  447. return response.json(444)
  448. page = int(pageNo)
  449. line = int(pageSize)
  450. try:
  451. if storeMealID: # 条件查询
  452. store_meal_lang_qs = Store_Meal.objects.filter(id=storeMealID)
  453. else: # 查询全部
  454. store_meal_lang_qs = Store_Meal.objects.filter(
  455. lang__isnull=False)
  456. store_meal_lang_val = store_meal_lang_qs.values(
  457. 'id',
  458. 'lang__id',
  459. 'lang__lang',
  460. 'lang__title',
  461. 'lang__content',
  462. 'lang__discount_content',
  463. )
  464. total = len(store_meal_lang_val)
  465. store_meal_langs = store_meal_lang_val[(
  466. page - 1) * line:page * line]
  467. store_meal_lang_list = []
  468. for store_meal_lang in store_meal_langs:
  469. store_meal_lang_list.append({
  470. 'storeMealID': store_meal_lang['id'],
  471. 'langID': store_meal_lang['lang__id'],
  472. 'lang': store_meal_lang['lang__lang'],
  473. 'title': store_meal_lang['lang__title'],
  474. 'content': store_meal_lang['lang__content'],
  475. 'discountContent': store_meal_lang['lang__discount_content'],
  476. })
  477. print('store_meal_lang_list: ', store_meal_lang_list)
  478. return response.json(
  479. 0, {'list': store_meal_lang_list, 'total': total})
  480. except Exception as e:
  481. print(e)
  482. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  483. def addOrEditStoreMealLanguage(self, userID, request_dict, response):
  484. # 添加/编辑套餐语言
  485. print('request_dict: ', request_dict)
  486. storeMealID = request_dict.get('storeMealID', None)
  487. lang = request_dict.get('lang', None)
  488. title = request_dict.get('title', None)
  489. content = request_dict.get('content', None)
  490. discount_content = request_dict.get('discount_content', '')
  491. isEdit = request_dict.get('isEdit', None)
  492. if not all([storeMealID, lang, title, content]):
  493. return response.json(444)
  494. try:
  495. # 查询套餐是否存在
  496. store_meal_qs = Store_Meal.objects.get(id=storeMealID)
  497. if not store_meal_qs:
  498. return response.json(173)
  499. if isEdit: # 编辑
  500. langID = request_dict.get('langID', None)
  501. if not langID:
  502. return response.json(444)
  503. Lang.objects.filter(
  504. id=langID).update(
  505. lang=lang,
  506. title=title,
  507. content=content,
  508. discount_content=discount_content)
  509. else: # 添加
  510. lang_obj = Lang.objects.filter(
  511. lang=lang,
  512. title=title,
  513. content=content,
  514. discount_content=discount_content)
  515. if not lang_obj.exists():
  516. # 数据不存在,lang表创建数据
  517. Lang.objects.create(
  518. lang=lang,
  519. title=title,
  520. content=content,
  521. discount_content=discount_content)
  522. lang_obj = Lang.objects.filter(
  523. lang=lang,
  524. title=title,
  525. content=content,
  526. discount_content=discount_content)
  527. store_meal_qs.lang.add(*lang_obj) # store_meal表添加语言数据
  528. return response.json(0)
  529. except Exception as e:
  530. print(e)
  531. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  532. def deleteStoreMealLanguage(self, userID, request_dict, response):
  533. # 删除套餐语言
  534. storeMealID = request_dict.get('storeMealID', None)
  535. langID = request_dict.get('langID', None)
  536. if not all([storeMealID, langID]):
  537. return response.json(444)
  538. try:
  539. storeMeal_qs = Store_Meal.objects.get(id=storeMealID)
  540. if not storeMeal_qs:
  541. return response.json(173)
  542. lang_qs = Lang.objects.filter(id=langID)
  543. storeMeal_qs.lang.remove(*lang_qs)
  544. return response.json(0)
  545. except Exception as e:
  546. print(e)
  547. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  548. def getCdkList(self, userID, request_dict, response):
  549. # 获取激活码列表
  550. pageNo = request_dict.get('pageNo', None)
  551. pageSize = request_dict.get('pageSize', None)
  552. cdk = request_dict.get('cdk', None)
  553. order = request_dict.get('order', None)
  554. is_activate = request_dict.get('is_activate', None)
  555. mold = request_dict.get('mold', None)
  556. lang = request_dict.get('lang', 'cn')
  557. if not all([pageNo, pageSize]):
  558. return response.json(444)
  559. page = int(pageNo)
  560. line = int(pageSize)
  561. try:
  562. if cdk:
  563. searchVal = cdk.strip()
  564. if order:
  565. searchVal = order.strip()
  566. if is_activate:
  567. searchVal = is_activate.strip()
  568. cdk_qs = CDKcontextModel.objects.filter().all()
  569. if cdk:
  570. cdk_qs = cdk_qs.filter(cdk__contains=searchVal)
  571. if order:
  572. cdk_qs = cdk_qs.filter(order__contains=searchVal)
  573. if is_activate:
  574. cdk_qs = cdk_qs.filter(is_activate=searchVal)
  575. if mold:
  576. cdk_qs = cdk_qs.filter(rank__bucket__mold=mold)
  577. cdk_qs = cdk_qs.filter(rank__lang__lang=lang)
  578. cdk_qs = cdk_qs.annotate(rank__title=F('rank__lang__title'))
  579. cdk_qs = cdk_qs.values(
  580. 'id',
  581. 'cdk',
  582. 'create_time',
  583. 'valid_time',
  584. 'is_activate',
  585. 'is_down',
  586. 'rank__id',
  587. 'rank__title',
  588. 'order',
  589. 'create_time',
  590. 'rank__bucket__mold')
  591. cdk_qs = cdk_qs.order_by('-create_time') # 根据CDK创建时间降序排序
  592. count = cdk_qs.count()
  593. cdk_qs = cdk_qs[(page - 1) * line:page * line]
  594. return response.json(
  595. 0, {'list': list(cdk_qs), 'total': count})
  596. except Exception as e:
  597. print(e)
  598. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  599. def editExpress(self, request_dict, response):
  600. order_id = request_dict.get('orderID', None)
  601. express_id = request_dict.get('express_id', None)
  602. if not all([order_id, express_id]):
  603. return response.json(444, {'error param': 'orderID or express_id'})
  604. try:
  605. CDKcontextModel.objects.filter(order=order_id).update(express_id=express_id)
  606. return response.json(0)
  607. except Exception as e:
  608. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  609. def getVodStoreMeal(self, response):
  610. try:
  611. store_meal = Store_Meal.objects.filter(Q(is_show=0), ~Q(commodity_code='paypal_cycle'),
  612. Q(lang__lang='cn')).values('id', 'lang__title', 'lang__content',
  613. 'pixel_level')
  614. if not store_meal.exists():
  615. return response.json(0, [])
  616. store_meal_list = []
  617. for item in store_meal:
  618. pixel_content = '4k像素' if item['pixel_level'] == 1 else '4k像素以下'
  619. store_meal_list.append({'id': item['id'], 'title': item['lang__title'] + '--' + item[
  620. 'lang__content'] + '(' + pixel_content + ')'})
  621. return response.json(0, store_meal_list)
  622. except Exception as e:
  623. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  624. def createCdk(self, request_dict, response):
  625. cdk_num = request_dict.get("cdknum", None)
  626. mold = request_dict.get('mold', None)
  627. order = request_dict.get('order', None)
  628. rank = request_dict.get('rank', None)
  629. if not all([cdk_num, rank]):
  630. return response.json(444, {'error param': 'cdknum or rank'})
  631. store_meal = Store_Meal.objects.filter(id=rank)
  632. # sm_qs = Store_Meal.objects.filter(
  633. # pay_type__payment='cdk_pay', bucket__mold=mold, is_show=0)
  634. if not store_meal.exists():
  635. return response.json(173)
  636. cdk_list = []
  637. for i in range(int(cdk_num)):
  638. now_time = int(time.time())
  639. cdk = hashlib.md5((str(uuid.uuid1()) +
  640. str(now_time)).encode('utf-8')).hexdigest()
  641. cdk_model = CDKcontextModel(
  642. cdk=cdk,
  643. create_time=now_time,
  644. valid_time=0,
  645. is_activate=0,
  646. is_down=0,
  647. rank_id=rank,
  648. order=order,
  649. )
  650. cdk_list.append(cdk_model)
  651. try:
  652. CDKcontextModel.objects.bulk_create(cdk_list)
  653. except Exception as e:
  654. return response.json(404, repr(e))
  655. else:
  656. return response.json(0)
  657. def deleteCdk(self, request_dict, response):
  658. cdk_id = request_dict.get("id", None)
  659. try:
  660. CDKcontextModel.objects.get(id=cdk_id).delete()
  661. return response.json(0)
  662. except Exception as e:
  663. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  664. def downloadCDK(self, request_dict, response):
  665. region = request_dict.get('region', None)
  666. content = ''
  667. if region == 'cn':
  668. # 下载国内未使用激活码
  669. content += '激活码(国内)\n'
  670. cdk_inactivate_qs = CDKcontextModel.objects.filter(is_down=0, is_activate=0, rank__bucket__mold=0,
  671. rank__is_show=0).values('cdk')
  672. else:
  673. # 下载国外未使用激活码
  674. content += '激活码(国外)\n'
  675. cdk_inactivate_qs = CDKcontextModel.objects.filter(is_down=0, is_activate=0, rank__bucket__mold=1,
  676. rank__is_show=0).values('cdk')
  677. for cdk_inactivate in cdk_inactivate_qs:
  678. content += cdk_inactivate['cdk'] + '\n'
  679. # print(content)
  680. cdk_inactivate_qs.update(is_down=1)
  681. response = StreamingHttpResponse(content)
  682. response['Content-Type'] = 'application/octet-stream'
  683. response['Content-Disposition'] = 'attachment;filename="CDK.txt"'
  684. return response
  685. @staticmethod
  686. def getCouponList(request_dict, response):
  687. combo_id = request_dict.get('comboID', None)
  688. pageNo = request_dict.get('pageNo', None)
  689. pageSize = request_dict.get('pageSize', None)
  690. if not all([pageNo, pageSize]):
  691. return response.json(444)
  692. page = int(pageNo)
  693. line = int(pageSize)
  694. try:
  695. if combo_id: # 根据套餐id查询
  696. coupon_id_list = CouponCombo.objects.filter(combo_id=combo_id).values_list('coupon_id', flat=True)
  697. coupon_qs = CouponConfigModel.objects.filter(id__in=coupon_id_list).values(
  698. 'id', 'type', 'use_range', 'coupon_discount')
  699. else:
  700. coupon_qs = CouponConfigModel.objects.filter().values(
  701. 'id', 'type', 'use_range', 'coupon_discount')
  702. count = coupon_qs.count()
  703. coupon_list = list(coupon_qs[(page - 1) * line:page * line])
  704. for coupon in coupon_list:
  705. coupon['combo_id'] = 'NA'
  706. coupon_combo_qs = CouponCombo.objects.filter(coupon_id=coupon['id']).values('combo_id')
  707. if coupon_combo_qs.exists():
  708. coupon['combo_id'] = coupon_combo_qs[0]['combo_id']
  709. return response.json(0, {'list': coupon_list, 'total': count})
  710. except Exception as e:
  711. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  712. @staticmethod
  713. def getCouponId(response):
  714. coupon_qs = CouponConfigModel.objects.all().values('id')
  715. return response.json(0, {'list': list(coupon_qs)})
  716. @staticmethod
  717. def addOrEditCoupon(request_dict, response):
  718. coupon_id = request_dict.get('couponID', None)
  719. combo_id = request_dict.get('comboID', None)
  720. coupon_type = int(request_dict.get('type', 0))
  721. use_range = request_dict.get('useRange', '')
  722. coupon_discount = request_dict.get('couponDiscount', '')
  723. is_edit = request_dict.get('isEdit', None)
  724. if not all([coupon_type, use_range, coupon_discount]):
  725. return response.json(444)
  726. try:
  727. now_time = int(time.time())
  728. coupon_data = {
  729. 'type': coupon_type,
  730. 'use_range': use_range,
  731. 'coupon_discount': coupon_discount
  732. }
  733. if is_edit:
  734. if not coupon_id:
  735. return response.json(444)
  736. CouponConfigModel.objects.filter(id=coupon_id).update(**coupon_data)
  737. CouponCombo.objects.filter(coupon_id=coupon_id).update(combo_id=combo_id, update_time=now_time)
  738. else:
  739. coupon = CouponConfigModel.objects.create(**coupon_data)
  740. coupon_id = coupon.id
  741. # 关联套餐
  742. CouponCombo.objects.create(coupon_id=coupon_id, combo_id=combo_id,
  743. create_time=now_time, update_time=now_time)
  744. return response.json(0)
  745. except Exception as e:
  746. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  747. @staticmethod
  748. def deleteCoupon(request_dict, response):
  749. coupon_id = request_dict.get('couponID', None)
  750. if not coupon_id:
  751. return response.json(444)
  752. try:
  753. CouponConfigModel.objects.filter(id=coupon_id).delete()
  754. return response.json(0)
  755. except Exception as e:
  756. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  757. @staticmethod
  758. def getCouponLangList(request_dict, response):
  759. coupon_id = request_dict.get('couponID', None)
  760. page = request_dict.get('pageNo', None)
  761. line = request_dict.get('pageSize', None)
  762. if not all([page, line]):
  763. return response.json(444)
  764. page = int(page)
  765. line = int(line)
  766. try:
  767. if coupon_id: # 条件查询
  768. coupon_qs = CouponConfigModel.objects.filter(id=coupon_id)
  769. else: # 查询语言id非空数据
  770. coupon_qs = CouponConfigModel.objects.filter(~Q(lang__id=None))
  771. coupon_lang_qs = coupon_qs.values(
  772. 'id',
  773. 'lang__id',
  774. 'lang__lang',
  775. 'lang__instruction',
  776. 'lang__quota',
  777. 'lang__unit',
  778. 'lang__remark'
  779. )
  780. total = len(coupon_lang_qs)
  781. coupon_lang_qs = coupon_lang_qs[(page - 1) * line:page * line]
  782. coupon_lang_list = []
  783. for coupon_lang in coupon_lang_qs:
  784. coupon_lang_list.append({
  785. 'couponID': coupon_lang['id'],
  786. 'langID': coupon_lang['lang__id'],
  787. 'lang': coupon_lang['lang__lang'],
  788. 'instruction': coupon_lang['lang__instruction'],
  789. 'quota': coupon_lang['lang__quota'],
  790. 'unit': coupon_lang['lang__unit'],
  791. 'remark': coupon_lang['lang__remark']
  792. })
  793. return response.json(0, {'list': coupon_lang_list, 'total': total})
  794. except Exception as e:
  795. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  796. @staticmethod
  797. def addOrEditCouponLang(request_dict, response):
  798. coupon_id = request_dict.get('couponID', None)
  799. lang = request_dict.get('lang', None)
  800. instruction = request_dict.get('instruction', '')
  801. quota = request_dict.get('quota', '')
  802. unit = request_dict.get('unit', '')
  803. unit = request_dict.get('unit', '')
  804. remark = request_dict.get('remark', None)
  805. is_edit = request_dict.get('isEdit', None)
  806. if not all([coupon_id, lang]):
  807. return response.json(444)
  808. try:
  809. # 查询优惠券是否存在
  810. coupon_qs = CouponConfigModel.objects.get(id=coupon_id)
  811. if not coupon_qs:
  812. return response.json(173)
  813. if is_edit: # 编辑
  814. lang_id = request_dict.get('langID', None)
  815. if not lang_id:
  816. return response.json(444)
  817. CouponLang.objects.filter(
  818. id=lang_id).update(
  819. lang=lang,
  820. instruction=instruction,
  821. quota=quota,
  822. unit=unit,
  823. remark=remark
  824. )
  825. else: # 添加
  826. lang_obj = CouponLang.objects.filter(
  827. lang=lang,
  828. instruction=instruction,
  829. quota=quota,
  830. unit=unit,
  831. remark=remark
  832. )
  833. if not lang_obj.exists():
  834. # 数据不存在,lang表创建数据
  835. CouponLang.objects.create(
  836. lang=lang,
  837. instruction=instruction,
  838. quota=quota,
  839. unit=unit,
  840. remark=remark
  841. )
  842. lang_obj = CouponLang.objects.filter(
  843. lang=lang,
  844. instruction=instruction,
  845. quota=quota,
  846. unit=unit,
  847. remark=remark
  848. )
  849. coupon_qs.lang.add(*lang_obj) # coupon_config表添加语言数据
  850. return response.json(0)
  851. except Exception as e:
  852. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  853. @staticmethod
  854. def deleteCouponLang(request_dict, response):
  855. coupon_id = request_dict.get('couponID', None)
  856. lang_id = request_dict.get('langID', None)
  857. if not all([coupon_id, lang_id]):
  858. return response.json(444)
  859. try:
  860. coupon_qs = CouponConfigModel.objects.get(id=coupon_id)
  861. if not coupon_qs:
  862. return response.json(173)
  863. lang_qs = CouponLang.objects.filter(id=lang_id)
  864. coupon_qs.lang.remove(*lang_qs)
  865. return response.json(0)
  866. except Exception as e:
  867. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  868. @staticmethod
  869. def getCouponUsingList(request_dict, response):
  870. username = request_dict.get('username', None)
  871. phone = request_dict.get('phone', None)
  872. user_email = request_dict.get('userEmail', None)
  873. use_status = request_dict.get('useStatus', None)
  874. page_no = request_dict.get('pageNo', None)
  875. page_size = request_dict.get('pageSize', None)
  876. if not all([page_no, page_size]):
  877. return response.json(444)
  878. page = int(page_no)
  879. line = int(page_size)
  880. try:
  881. coupon_qs = CouponModel.objects.all()
  882. if use_status:
  883. coupon_qs = coupon_qs.filter(use_status=use_status)
  884. if not coupon_qs.exists():
  885. return response.json(0, [])
  886. device_user_qs = Device_User.objects.filter().values(
  887. 'userID', 'username', 'phone', 'userEmail')
  888. if username:
  889. device_user_qs = device_user_qs.filter(username=username)
  890. if not device_user_qs.exists():
  891. return response.json(0, [])
  892. user_id = device_user_qs.first()['userID']
  893. coupon_qs = coupon_qs.filter(userID=user_id)
  894. if phone:
  895. device_user_qs = device_user_qs.filter(phone__contains=phone)
  896. if not device_user_qs.exists():
  897. return response.json(0, [])
  898. user_id = device_user_qs.first()['userID']
  899. coupon_qs = coupon_qs.filter(userID=user_id)
  900. if user_email:
  901. device_user_qs = device_user_qs.filter(userEmail__contains=user_email)
  902. if not device_user_qs.exists():
  903. return response.json(0, [])
  904. user_id = device_user_qs.first()['userID']
  905. coupon_qs = coupon_qs.filter(userID=user_id)
  906. coupon_qs = coupon_qs.values(
  907. 'id', 'use_status', 'distribute_time', 'valid_time', 'update_time', 'create_time', 'userID',
  908. 'coupon_config__id', 'userID')
  909. count = coupon_qs.count()
  910. coupons = coupon_qs[(page - 1) * line:page * line]
  911. coupon_list = []
  912. for coupon in coupons:
  913. device_user_qs = Device_User.objects.filter(userID=coupon['userID']).values('username', 'phone',
  914. 'userEmail')
  915. username = device_user_qs[0]['username'] if device_user_qs.exists() else ''
  916. phone = device_user_qs[0]['phone'] if device_user_qs.exists() else ''
  917. user_email = device_user_qs[0]['userEmail'] if device_user_qs.exists() else ''
  918. coupon_list.append({
  919. 'id': coupon['id'],
  920. 'useStatus': coupon['use_status'],
  921. 'distributeTime': coupon['distribute_time'],
  922. 'validTime': coupon['valid_time'],
  923. 'updateTime': coupon['update_time'],
  924. 'createTime': coupon['create_time'],
  925. 'couponID': coupon['coupon_config__id'],
  926. 'username': username,
  927. 'phone': phone,
  928. 'userEmail': user_email,
  929. })
  930. return response.json(0, {'list': coupon_list, 'total': count})
  931. except Exception as e:
  932. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  933. @staticmethod
  934. def editCouponUsing(request_dict, response):
  935. id = request_dict.get('id', None)
  936. use_status = request_dict.get('useStatus', 0)
  937. valid_time = request_dict.get('validTime', None)
  938. if not all([id, use_status, valid_time]):
  939. return response.json(444)
  940. try:
  941. now_time = int(time.time())
  942. CouponModel.objects.filter(id=id).update(use_status=use_status, valid_time=valid_time, update_time=now_time)
  943. return response.json(0)
  944. except Exception as e:
  945. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  946. @staticmethod
  947. def deleteCouponUsing(request_dict, response):
  948. id = request_dict.get('id', None)
  949. if not id:
  950. return response.json(444)
  951. try:
  952. CouponModel.objects.filter(id=id).delete()
  953. return response.json(0)
  954. except Exception as e:
  955. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  956. def getDeviceOrderList(self, request_dict, response):
  957. print('request_dict: ', request_dict)
  958. pageNo = request_dict.get('pageNo', None)
  959. pageSize = request_dict.get('pageSize', None)
  960. uid = request_dict.get('uid', None)
  961. channel = request_dict.get('channel', None)
  962. orderID = request_dict.get('orderID', None)
  963. userID__username = request_dict.get('userID__username', None)
  964. currency = request_dict.get('currency', None)
  965. payType = request_dict.get('payType', None)
  966. status = request_dict.get('status', None)
  967. timeRange = request_dict.getlist('timeRange[]', None)
  968. orderType = request_dict.get('orderType', None)
  969. serialNumber = request_dict.get('serialNumber', None)
  970. trade_no = request_dict.get('tradeNo', None)
  971. userID__phone = request_dict.get('userID__phone', None)
  972. if not all([pageNo, pageSize]):
  973. return response.json(444)
  974. page = int(pageNo)
  975. line = int(pageSize)
  976. try:
  977. omqs = Order_Model.objects.all()
  978. # 筛选指定设备id的订单
  979. if uid:
  980. omqs = omqs.filter(UID=uid)
  981. if channel:
  982. omqs = omqs.filter(channel=channel)
  983. if orderID:
  984. omqs = omqs.filter(orderID=orderID)
  985. if userID__username:
  986. omqs = omqs.filter(userID__username=userID__username)
  987. if currency:
  988. omqs = omqs.filter(currency=currency)
  989. if payType:
  990. omqs = omqs.filter(payType=payType)
  991. if status:
  992. omqs = omqs.filter(status=status)
  993. if orderType:
  994. omqs = omqs.filter(order_type=int(orderType))
  995. if trade_no:
  996. omqs = omqs.filter(trade_no=trade_no)
  997. if userID__phone:
  998. omqs = omqs.filter(userID__phone=userID__phone)
  999. if serialNumber:
  1000. device_uid = CommonService.query_uid_with_serial(serialNumber)
  1001. omqs = omqs.filter(UID=device_uid)
  1002. if timeRange:
  1003. startTime, endTime = int(
  1004. timeRange[0][:-3]), int(timeRange[1][:-3])
  1005. omqs = omqs.filter(
  1006. addTime__gte=startTime,
  1007. addTime__lte=endTime)
  1008. if not omqs.exists():
  1009. return response.json(0, [])
  1010. order_list = []
  1011. count = omqs.count()
  1012. order_ql = omqs.values("orderID", "UID", "userID__username", "userID__NickName", "channel", "desc", "price",
  1013. "refunded_amount", "currency", "addTime", "updTime", "paypal", "payType",
  1014. "rank__day", "rank__price", "status", "order_type", "paymentID", "trade_no",
  1015. "payTime", "userID__region_country", "userID__phone")
  1016. order_ql = order_ql.order_by('-addTime') # 根据CDK创建时间降序排序
  1017. order_ql = order_ql[(page - 1) * line:page * line]
  1018. for order in order_ql:
  1019. # 查询国家信息
  1020. country = 'N/A'
  1021. country_qs = CountryModel.objects.filter(id=order['userID__region_country']).values('country_name')
  1022. if country_qs.exists():
  1023. country = country_qs[0]['country_name']
  1024. serialNumber = CommonService.query_serial_with_uid(order['UID'])
  1025. data = {
  1026. 'orderID': order['orderID'],
  1027. 'UID': order['UID'],
  1028. 'userID__username': order['userID__username'],
  1029. 'userID__NickName': order['userID__NickName'],
  1030. 'channel': order['channel'],
  1031. 'desc': order['desc'],
  1032. 'price': order['price'],
  1033. 'refunded_amount': order['refunded_amount'],
  1034. 'currency': order['currency'],
  1035. 'addTime': order['addTime'],
  1036. 'updTime': order['updTime'],
  1037. 'paypal': order['paypal'],
  1038. 'payType': order['payType'],
  1039. 'rank__day': order['rank__day'],
  1040. 'rank__price': order['rank__price'],
  1041. 'status': order['status'],
  1042. 'order_type': order['order_type'],
  1043. 'payTime': order['payTime'] if order['payTime'] else 'N/A',
  1044. 'serialNumber': 'N/A' if serialNumber == order['UID'] else serialNumber,
  1045. 'country': country,
  1046. 'userID__phone': order['userID__phone'],
  1047. }
  1048. # 订单显示(或不显示)停用/退款功能
  1049. if order['order_type'] == 0: # 云存
  1050. uid_bucket = UID_Bucket.objects.filter(uid=order['UID']).values('use_status')
  1051. user_status = uid_bucket[0]['use_status'] if uid_bucket.exists() else ''
  1052. if user_status != '':
  1053. data['user_status'] = user_status
  1054. else:
  1055. data['user_status'] = 2
  1056. elif order['order_type'] == 1: # ai
  1057. ai_service_qs = AiService.objects.filter(
  1058. Q(orders_id=order['orderID']) & ~Q(use_status=2))
  1059. if ai_service_qs.exists():
  1060. data['user_status'] = 1
  1061. else:
  1062. data['user_status'] = 2
  1063. elif order['order_type'] == 2: # 联通4G
  1064. unicom_combor_order_qs = UnicomComboOrderInfo.objects.filter(
  1065. Q(order_id=order['orderID']) & ~Q(status=2))
  1066. if unicom_combor_order_qs.exists():
  1067. data['user_status'] = 1
  1068. else:
  1069. data['user_status'] = 2
  1070. # 添加PayPal交易号字段
  1071. data['trade_no'] = 'N/A'
  1072. if data['payType'] == 1:
  1073. data['trade_no'] = order['trade_no'] if order['trade_no'] else 'N/A'
  1074. data['express_id'] = ''
  1075. if data['payType'] == 11:
  1076. cdk_context_qs = CDKcontextModel.objects.filter(order=data['orderID']).values('express_id')
  1077. if cdk_context_qs.exists():
  1078. data['express_id'] = cdk_context_qs[0]['express_id']
  1079. order_list.append(data)
  1080. return response.json(
  1081. 0, {'list': order_list, 'total': count})
  1082. except Exception as e:
  1083. print(e)
  1084. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1085. def getAbnormalOrderList(self, request_dict, response):
  1086. print('request_dict: ', request_dict)
  1087. pageNo = request_dict.get('page_no', None)
  1088. pageSize = request_dict.get('page_size', None)
  1089. order_id = request_dict.get('order_id', None)
  1090. username = request_dict.get('username', None)
  1091. pay_type = request_dict.get('pay_type', None)
  1092. status = request_dict.get('status', None)
  1093. trade_no = request_dict.get('trade_no', None)
  1094. agreement_id = request_dict.get('agreement_id', None)
  1095. start_time = request_dict.get('start_time', None)
  1096. end_time = request_dict.get('end_time', None)
  1097. if not all([pageNo, pageSize]):
  1098. return response.json(444)
  1099. page = int(pageNo)
  1100. line = int(pageSize)
  1101. try:
  1102. order_qs = AbnormalOrder.objects.all()
  1103. # 筛选指定订单
  1104. if order_id:
  1105. order_qs = order_qs.filter(order_id=order_id)
  1106. if username:
  1107. order_qs = order_qs.filter(username=username)
  1108. if pay_type:
  1109. order_qs = order_qs.filter(pay_type=pay_type)
  1110. if status:
  1111. order_qs = order_qs.filter(status=status)
  1112. if trade_no:
  1113. order_qs = order_qs.filter(trade_no=trade_no)
  1114. if agreement_id:
  1115. order_qs = order_qs.filter(agreement_id=agreement_id)
  1116. if start_time and end_time:
  1117. order_qs = order_qs.filter(pay_time__gte=start_time, pay_time__lt=end_time)
  1118. if not order_qs.exists():
  1119. return response.json(0, [])
  1120. count = order_qs.count()
  1121. order_qs = order_qs.values("id", "order_id", "username", "pay_type", "status", "trade_no", "agreement_id",
  1122. "price", "pay_time").order_by('-pay_time')[(page - 1) * line:page * line]
  1123. return response.json(0, {'list': list(order_qs), 'total': count})
  1124. except Exception as e:
  1125. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1126. def updateAbnormalOrder(self, request_dict, response):
  1127. abnormal_order_id = request_dict.get('id', None)
  1128. if not all([abnormal_order_id]):
  1129. return response.json(444)
  1130. abnormal_order = AbnormalOrder.objects.filter(id=abnormal_order_id)
  1131. if not abnormal_order.exists():
  1132. return response.json(173)
  1133. try:
  1134. trade_no = abnormal_order.values('trade_no')[0]['trade_no']
  1135. order_qs = Order_Model.objects.filter(trade_no=trade_no)
  1136. if order_qs.exists():
  1137. abnormal_order.update(status=1)
  1138. return response.json(0)
  1139. params = {'trade_no': trade_no}
  1140. eur_response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
  1141. if eur_response.status_code == 200:
  1142. result = eur_response.json()
  1143. if result['result_code'] == 0 and result['result']['is_exist']:
  1144. abnormal_order.update(status=1)
  1145. return response.json(0)
  1146. except Exception as e:
  1147. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1148. def vodOrderReconcile(self, request, request_dict, response):
  1149. file = request.FILES.get('file', None)
  1150. if not all([file]):
  1151. return response.json(444, {'error param': 'file'})
  1152. try:
  1153. rd_book = xlrd.open_workbook(filename=None, file_contents=file.read())
  1154. rd_sheet = rd_book.sheet_by_index(0)
  1155. date = rd_sheet.cell_value(1, 0)
  1156. month = int(date.split('/')[0])
  1157. year = int(date.split('/')[2])
  1158. last_day = calendar.monthrange(year, month)[1]
  1159. start_time = datetime.datetime(year, month, 1)
  1160. end_time = datetime.datetime(year, month, last_day) + datetime.timedelta(hours=24)
  1161. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1162. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1163. wt_book = xlwt.Workbook(encoding='utf-8')
  1164. wt_sheet = wt_book.add_sheet('对账结果', cell_overwrite_ok=True)
  1165. row_start = 0
  1166. # 第一部分表格填写
  1167. first_header = ['支付类型', '销售总金额', '销售总数量', '退款总额', '退款总数量', '应收金额', '平台手续费', '账务实收', '金额相差']
  1168. for index, content in enumerate(first_header):
  1169. wt_sheet.write(row_start, index, content)
  1170. row_start += 1
  1171. all_order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time,
  1172. status__in=[1, 5, 6])
  1173. trade_no_list = []
  1174. paid_order_qs = all_order_qs.filter(status=1)
  1175. for i in paid_order_qs:
  1176. if i.trade_no not in rd_sheet.col_values(9, 1):
  1177. trade_no_list.append(i.trade_no)
  1178. # 已付款订单
  1179. paid = all_order_qs.filter(payType=1, status=1).aggregate(total=Sum('price'),
  1180. count=Count('UID'))
  1181. paid_total = paid['total'] if paid['total'] else 0
  1182. paid_count = paid['count'] if paid['count'] else 0
  1183. # 全额退款订单
  1184. refund = all_order_qs.filter(payType=1, status__in=[5, 6]).aggregate(total=Sum('refunded_amount'),
  1185. count=Count('UID'))
  1186. refund_total = refund['total'] if refund['total'] else 0
  1187. refund_count = refund['count'] if refund['count'] else 0
  1188. wt_sheet.write(row_start, 0, 'PayPal')
  1189. wt_sheet.write(row_start, 1, paid_total + refund_total)
  1190. wt_sheet.write(row_start, 2, paid_count + refund_count)
  1191. wt_sheet.write(row_start, 3, refund_total)
  1192. wt_sheet.write(row_start, 4, refund_count)
  1193. wt_sheet.write(row_start, 5, paid_total)
  1194. wt_sheet.write(row_start, 8, label=xlwt.Formula('f{row}-h{row}+g{row}'.format(row=row_start + 1)))
  1195. row_start += 1
  1196. # 第二部分表格填写
  1197. row_start += 2
  1198. paypal_money = 0
  1199. fee_money = 0
  1200. for row in range(rd_sheet.nrows):
  1201. if row == 0:
  1202. wt_sheet.write(row_start, 0, '是否匹配账单')
  1203. for col in range(rd_sheet.ncols):
  1204. value = rd_sheet.cell_value(row, col)
  1205. temp_col = col + 1
  1206. wt_sheet.write(row_start, temp_col, str(value))
  1207. row_start += 1
  1208. continue
  1209. if rd_sheet.cell_value(row, 0) == '合计':
  1210. break
  1211. paypal_money += rd_sheet.cell_value(row, 7)
  1212. fee_money += rd_sheet.cell_value(row, 6)
  1213. transaction_id = rd_sheet.cell_value(row, 9)
  1214. order_qs = all_order_qs.filter(trade_no=transaction_id)
  1215. if not order_qs.exists():
  1216. col_value_list = rd_sheet.row_values(row)
  1217. col_value_list.insert(0, '否')
  1218. for index, value in enumerate(col_value_list):
  1219. wt_sheet.write(row_start, index, str(value))
  1220. row_start += 1
  1221. # 第三部分表格填写
  1222. row_start += 1
  1223. third_header = ['是否匹配账单', '交易ID', '订单ID', '设备UID', '用户名', '账号昵称', '通道', '商品描述', '支付方式', '价格', '支付状态',
  1224. '已退金额', '添加时间', '更新时间']
  1225. diff_order_qs = all_order_qs.filter(trade_no__in=trade_no_list).values('trade_no', 'orderID', 'UID',
  1226. 'userID__username',
  1227. 'userID__NickName', 'channel',
  1228. 'desc', 'payType',
  1229. 'price', 'status',
  1230. 'refunded_amount', 'addTime',
  1231. 'updTime')
  1232. for index, content in enumerate(third_header):
  1233. wt_sheet.write(row_start, index, content)
  1234. row_start += 1
  1235. for item in diff_order_qs:
  1236. values_list = item.values()
  1237. for col, content in enumerate(values_list):
  1238. if col == 0:
  1239. wt_sheet.write(row_start, col, '否')
  1240. if col == 7:
  1241. content = 'PayPal'
  1242. if col == 9:
  1243. if content == 1:
  1244. content = '支付成功'
  1245. elif content == 5:
  1246. content = '全额退款'
  1247. elif content == 6:
  1248. content = '部分退款'
  1249. if col in [11, 12]:
  1250. content = CommonService.timestamp_to_str(int(content))
  1251. wt_sheet.write(row_start, col + 1, str(content))
  1252. row_start += 1
  1253. wt_sheet.write(1, 6, fee_money)
  1254. wt_sheet.write(1, 7, paypal_money)
  1255. res = HttpResponse(content_type='application/vnd.ms-excel')
  1256. res['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file.name))
  1257. wt_book.save(res)
  1258. return res
  1259. except Exception as e:
  1260. print(e)
  1261. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1262. def deleteDeviceOrder(self, userID, request_dict, response):
  1263. orderID = request_dict.get('orderID', None)
  1264. if orderID:
  1265. Order_Model.objects.filter(orderID=orderID).delete()
  1266. return response.json(0)
  1267. else:
  1268. return response.json(444)
  1269. def getDevicePackageList(self, request_dict, response):
  1270. pageNo = request_dict.get('pageNo', None)
  1271. pageSize = request_dict.get('pageSize', None)
  1272. uid = request_dict.get('uid', None)
  1273. if not all([pageNo, pageSize]):
  1274. return response.json(444)
  1275. page = int(pageNo)
  1276. line = int(pageSize)
  1277. try:
  1278. ubqs = UID_Bucket.objects.all()
  1279. if uid:
  1280. ubqs = ubqs.filter(uid__contains=uid)
  1281. if not ubqs.exists():
  1282. return response.json(0, [])
  1283. count = ubqs.count()
  1284. ubqs = ubqs.values(
  1285. 'id',
  1286. 'uid',
  1287. 'channel',
  1288. 'status',
  1289. 'endTime',
  1290. 'bucket__bucket',
  1291. 'bucket__storeDay',
  1292. 'bucket__area')
  1293. ubqs = ubqs.order_by('-addTime') # 根据CDK创建时间降序排序
  1294. ubqs = ubqs[(page - 1) * line:page * line]
  1295. return response.json(
  1296. 0, {'list': list(ubqs), 'total': count})
  1297. except Exception as e:
  1298. print(e)
  1299. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1300. def deleteDevicePackage(self, userID, request_dict, response):
  1301. orderID = request_dict.get('orderID', None)
  1302. if orderID:
  1303. Order_Model.objects.filter(orderID=orderID).delete()
  1304. return response.json(0)
  1305. else:
  1306. return response.json(444)
  1307. # 重置设备云存体验
  1308. def do_experience_reset(self, request_dict, userID, response):
  1309. bid = request_dict.get("id", None)
  1310. ubq = UID_Bucket.objects.filter(id=bid)
  1311. if ubq:
  1312. eq = ExperienceContextModel.objects.filter(uid=ubq[0].uid)
  1313. if eq:
  1314. eq.delete()
  1315. Order_Model.objects.filter(uid_bucket_id=bid).delete()
  1316. ubq.delete()
  1317. return response.json(0)
  1318. else:
  1319. return response.json(10007)
  1320. else:
  1321. return response.json(0, '重置云存体验失败')
  1322. @classmethod
  1323. def getCloudUserList(cls, request_dict, response):
  1324. print('request_dict: ', request_dict)
  1325. # UID_Bucket表查询数据
  1326. uid = request_dict.get('uid', None)
  1327. status = request_dict.get('status', None)
  1328. use_status = request_dict.get('use_status', None)
  1329. has_unused = request_dict.get('has_unused', None)
  1330. addTimeRange = request_dict.getlist('addTimeRange[]', None)
  1331. endTimeRange = request_dict.getlist('endTimeRange[]', None)
  1332. # Order_Model表查询数据
  1333. username = request_dict.get('username', None)
  1334. phone = request_dict.get('phone', None)
  1335. userEmail = request_dict.get('userEmail', None)
  1336. payType = request_dict.get('payType', None)
  1337. # uid_set 表查询
  1338. ucode = request_dict.getlist('ucode', None)
  1339. version = request_dict.getlist('version', None)
  1340. # 日志表查询
  1341. logTimeRange = request_dict.getlist('logTimeRange[]', None)
  1342. # 序列号查询
  1343. serialNumber = request_dict.get('serialNumber', None)
  1344. pageNo = request_dict.get('pageNo', None)
  1345. pageSize = request_dict.get('pageSize', None)
  1346. if not all([pageNo, pageSize]):
  1347. return response.json(444)
  1348. page = int(pageNo)
  1349. line = int(pageSize)
  1350. try:
  1351. uid_bucket_qs = UID_Bucket.objects.all()
  1352. if uid:
  1353. uid_bucket_qs = uid_bucket_qs.filter(uid__icontains=uid)
  1354. if status:
  1355. uid_bucket_qs = uid_bucket_qs.filter(status=status)
  1356. if use_status:
  1357. uid_bucket_qs = uid_bucket_qs.filter(use_status=use_status)
  1358. if has_unused:
  1359. uid_bucket_qs = uid_bucket_qs.filter(has_unused=has_unused)
  1360. if serialNumber:
  1361. device_info_qs = Device_Info.objects.filter(serial_number=serialNumber).values('UID')
  1362. uid = device_info_qs[0]['UID'] if device_info_qs.exists() else 'N/A'
  1363. uid_bucket_qs = uid_bucket_qs.filter(uid__icontains=uid)
  1364. if addTimeRange:
  1365. addStartTime, addEndTime = int(
  1366. addTimeRange[0][:-3]), int(addTimeRange[1][:-3])
  1367. uid_bucket_qs = uid_bucket_qs.filter(
  1368. addTime__gte=addStartTime,
  1369. addTime__lte=addEndTime)
  1370. if endTimeRange:
  1371. endStartTime, endEndTime = int(
  1372. endTimeRange[0][:-3]), int(endTimeRange[1][:-3])
  1373. uid_bucket_qs = uid_bucket_qs.filter(
  1374. addTime__gte=endStartTime,
  1375. addTime__lte=endEndTime)
  1376. uid_list = []
  1377. uid_set_dict = {}
  1378. if ucode and ucode != ['']:
  1379. uid_set_qs = UidSetModel.objects.filter(ucode__in=ucode).values('uid', 'ucode', 'version').distinct()
  1380. for uid_set in uid_set_qs:
  1381. uid_list.append(uid_set['uid'])
  1382. uid_set_dict[uid_set['uid']] = {
  1383. 'ucode': uid_set['ucode'],
  1384. 'version': uid_set['version']
  1385. }
  1386. uid_bucket_qs = uid_bucket_qs.filter(uid__in=uid_list)
  1387. else:
  1388. uid_set_qs = UidSetModel.objects.filter().values('uid', 'ucode', 'version').distinct()
  1389. for uid_set in uid_set_qs:
  1390. uid_list.append(uid_set['uid'])
  1391. uid_set_dict[uid_set['uid']] = {
  1392. 'ucode': uid_set['ucode'],
  1393. 'version': uid_set['version']
  1394. }
  1395. if not uid_bucket_qs.exists():
  1396. return response.json(0, [])
  1397. order_qs = Order_Model.objects.filter(uid_bucket_id__in=uid_bucket_qs.values('id'))
  1398. if username or phone or userEmail or payType:
  1399. if username:
  1400. order_qs = order_qs.filter(userID__username=username)
  1401. if phone:
  1402. order_qs = order_qs.filter(userID__phone__contains=phone)
  1403. if userEmail:
  1404. order_qs = order_qs.filter(
  1405. userID__userEmail__contains=userEmail)
  1406. if payType:
  1407. order_qs = order_qs.filter(payType=int(payType))
  1408. # 过滤套餐关联的UID_Bucket数据
  1409. uid_bucket_qs = uid_bucket_qs.filter(
  1410. id__in=order_qs.values_list(
  1411. 'uid_bucket_id', flat=True))
  1412. cg_qs = CloudLogModel.objects.filter(
  1413. operation='cloudstorage/queryvodlist')
  1414. if logTimeRange:
  1415. logStartTime, logEndTime = int(
  1416. logTimeRange[0][:-3]), int(logTimeRange[1][:-3])
  1417. cg_qs = cg_qs.filter(
  1418. time__gte=logStartTime,
  1419. time__lte=logEndTime)
  1420. # 过滤套餐关联的UID_Bucket数据
  1421. uid_bucket_qs = uid_bucket_qs.filter(
  1422. uid__in=cg_qs.values('uid'))
  1423. list_data = []
  1424. count = uid_bucket_qs.count()
  1425. uid_bucket_qs = uid_bucket_qs.order_by('-addTime')[(page - 1) * line:page * line]
  1426. for uid_bucket in uid_bucket_qs:
  1427. for order in order_qs.filter(uid_bucket_id=uid_bucket.id) \
  1428. .values('orderID', 'uid_bucket_id', 'desc', 'userID__userID',
  1429. 'UID', 'price', 'payType', 'userID__username', 'userID__phone',
  1430. 'userID__userEmail', 'userID__data_joined', 'agreement_id'):
  1431. # 套餐到期时间累加未使用套餐
  1432. unused_qs = Unused_Uid_Meal.objects.filter(uid=uid_bucket.uid).values('expire')
  1433. if unused_qs.exists():
  1434. addMonth = 0
  1435. for unused in unused_qs:
  1436. addMonth += unused['expire']
  1437. endTime = CommonService.calcMonthLater(addMonth, uid_bucket.endTime)
  1438. endTime = time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(endTime))
  1439. else:
  1440. endTime = time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(uid_bucket.endTime))
  1441. uid = uid_bucket.uid.upper()
  1442. data = {
  1443. 'id': uid_bucket.id,
  1444. 'orderId': order['orderID'],
  1445. 'uid': uid,
  1446. 'agreementId': order['agreement_id'] if order['agreement_id'] else 'N/A',
  1447. 'channel': uid_bucket.channel,
  1448. 'status': uid_bucket.status,
  1449. 'endTime': endTime,
  1450. 'addTime': time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(uid_bucket.addTime)),
  1451. 'use_status': uid_bucket.use_status,
  1452. 'has_unused': uid_bucket.has_unused,
  1453. 'desc': order['desc'],
  1454. 'payType': order['payType'],
  1455. 'price': order['price'],
  1456. 'username': order['userID__username'],
  1457. 'userID': order['userID__userID'],
  1458. 'phone': order['userID__phone'],
  1459. 'userEmail': order['userID__userEmail'],
  1460. 'data_joined': order['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S"),
  1461. 'playcount': cg_qs.filter(operation='cloudstorage/queryvodlist', uid=order['UID']).count(),
  1462. 'serial_number': 'N/A'
  1463. }
  1464. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number')
  1465. if device_info_qs.exists():
  1466. data['serial_number'] = device_info_qs[0]['serial_number'] if device_info_qs[0][
  1467. 'serial_number'] else 'N/A'
  1468. if uid in uid_set_dict:
  1469. data['ucode'] = uid_set_dict[uid]['ucode']
  1470. data['version'] = uid_set_dict[uid]['version']
  1471. list_data.append(data)
  1472. return response.json(
  1473. 0, {'list': list_data, 'total': count})
  1474. except Exception as e:
  1475. print(e)
  1476. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1477. def exportCloudUserList(self, request_dict, response):
  1478. # UID_Bucket表查询数据
  1479. uid = request_dict.get('uid', None)
  1480. status = request_dict.get('status', None)
  1481. use_status = request_dict.get('use_status', None)
  1482. has_unused = request_dict.get('has_unused', None)
  1483. addTimeRange = request_dict.getlist('addTimeRange[]', None)
  1484. endTimeRange = request_dict.getlist('endTimeRange[]', None)
  1485. # Order_Model表查询数据
  1486. username = request_dict.get('username', None)
  1487. phone = request_dict.get('phone', None)
  1488. userEmail = request_dict.get('userEmail', None)
  1489. payType = request_dict.get('payType', None)
  1490. # uid_set 表查询
  1491. ucode = request_dict.getlist('ucode', None)
  1492. version = request_dict.getlist('version', None)
  1493. # 日志表查询
  1494. logTimeRange = request_dict.getlist('logTimeRange[]', None)
  1495. pageNo = request_dict.get('pageNo', None)
  1496. pageSize = request_dict.get('pageSize', None)
  1497. if not all([pageNo, pageSize]):
  1498. return response.json(444)
  1499. page = int(pageNo)
  1500. line = int(pageSize)
  1501. try:
  1502. uid_bucket_qs = UID_Bucket.objects.all()
  1503. if uid:
  1504. uid_bucket_qs = uid_bucket_qs.filter(uid__contains=uid)
  1505. if status:
  1506. uid_bucket_qs = uid_bucket_qs.filter(status=status)
  1507. if use_status:
  1508. uid_bucket_qs = uid_bucket_qs.filter(use_status=use_status)
  1509. if has_unused:
  1510. uid_bucket_qs = uid_bucket_qs.filter(has_unused=has_unused)
  1511. if addTimeRange:
  1512. addStartTime, addEndTime = int(
  1513. addTimeRange[0][:-3]), int(addTimeRange[1][:-3])
  1514. uid_bucket_qs = uid_bucket_qs.filter(
  1515. addTime__gte=addStartTime,
  1516. addTime__lte=addEndTime)
  1517. if endTimeRange:
  1518. endStartTime, endEndTime = int(
  1519. endTimeRange[0][:-3]), int(endTimeRange[1][:-3])
  1520. uid_bucket_qs = uid_bucket_qs.filter(
  1521. addTime__gte=endStartTime,
  1522. addTime__lte=endEndTime)
  1523. if not uid_bucket_qs.exists():
  1524. return response.json(0, [])
  1525. order_qs = Order_Model.objects.filter(
  1526. uid_bucket_id__in=uid_bucket_qs.values('id'))
  1527. if username or phone or userEmail or payType:
  1528. if username:
  1529. order_qs = order_qs.filter(userID__username=username)
  1530. if phone:
  1531. order_qs = order_qs.filter(userID__phone__contains=phone)
  1532. if userEmail:
  1533. order_qs = order_qs.filter(
  1534. userID__userEmail__contains=userEmail)
  1535. if payType:
  1536. order_qs = order_qs.filter(payType=int(payType))
  1537. # 过滤套餐关联的UID_Bucket数据
  1538. uid_bucket_qs = uid_bucket_qs.filter(
  1539. id__in=order_qs.values_list(
  1540. 'uid_bucket_id', flat=True))
  1541. uidset_qs = UidSetModel.objects.filter(
  1542. uid__in=uid_bucket_qs.values('uid'))
  1543. if ucode or version:
  1544. if ucode:
  1545. uidset_qs = uidset_qs.filter(ucode=ucode)
  1546. if version:
  1547. uidset_qs = uidset_qs.filter(version=version)
  1548. cg_qs = CloudLogModel.objects.filter(
  1549. operation='cloudstorage/queryvodlist')
  1550. if logTimeRange:
  1551. logStartTime, logEndTime = int(
  1552. logTimeRange[0][:-3]), int(logTimeRange[1][:-3])
  1553. cg_qs = cg_qs.filter(
  1554. time__gte=logStartTime,
  1555. time__lte=logEndTime)
  1556. list_data = []
  1557. count = uid_bucket_qs.count()
  1558. uid_bucket_qs = uid_bucket_qs.order_by('-addTime')[(page - 1) * line:page * line]
  1559. for uid_bucket in uid_bucket_qs:
  1560. data = {
  1561. 'id': uid_bucket.id,
  1562. 'uid': uid_bucket.uid,
  1563. 'channel': uid_bucket.channel,
  1564. 'status': uid_bucket.status,
  1565. 'endTime': time.strftime(
  1566. "%Y--%m--%d %H:%M:%S",
  1567. time.localtime(
  1568. uid_bucket.endTime)),
  1569. 'addTime': time.strftime(
  1570. "%Y--%m--%d %H:%M:%S",
  1571. time.localtime(
  1572. uid_bucket.addTime)),
  1573. 'use_status': uid_bucket.use_status,
  1574. 'has_unused': uid_bucket.has_unused}
  1575. for order in order_qs.filter(
  1576. uid_bucket_id=uid_bucket.id).values(
  1577. 'uid_bucket_id',
  1578. 'desc',
  1579. 'userID__userID',
  1580. 'UID',
  1581. 'price',
  1582. 'payType',
  1583. 'userID__username',
  1584. 'userID__phone',
  1585. 'userID__userEmail',
  1586. 'userID__data_joined'):
  1587. data['desc'] = order['desc']
  1588. data['payType'] = order['payType']
  1589. data['price'] = order['price']
  1590. data['username'] = order['userID__username']
  1591. data['phone'] = order['userID__phone']
  1592. data['userEmail'] = order['userID__userEmail']
  1593. data['data_joined'] = order['userID__data_joined'].strftime(
  1594. "%Y-%m-%d %H:%M:%S")
  1595. data['playcount'] = cg_qs.filter(
  1596. operation='cloudstorage/queryvodlist', uid=order['UID']).count()
  1597. for uidset in uidset_qs.filter(
  1598. uid=uid_bucket.uid).values(
  1599. 'ucode',
  1600. 'version'):
  1601. data['ucode'] = uidset['ucode']
  1602. data['version'] = uidset['version']
  1603. list_data.append(data)
  1604. response = HttpResponse(content_type='application/vnd.ms-excel')
  1605. response['Content-Disposition'] = 'attachment; filename=userinfo.xls'
  1606. workbook = xlwt.Workbook(encoding='utf-8')
  1607. sheet1 = workbook.add_sheet('UID')
  1608. headtitle = [
  1609. 'id',
  1610. '用户账号',
  1611. '用户手机号',
  1612. '用户邮箱',
  1613. '注册时间',
  1614. '设备UID',
  1615. '设备通道',
  1616. '云存状态',
  1617. '添加时间',
  1618. '到期时间',
  1619. '使用状态',
  1620. '是否有未使用套餐',
  1621. '套餐描述',
  1622. '支付方式',
  1623. '价格',
  1624. '播放次数',
  1625. '产品编码',
  1626. '版本'
  1627. ]
  1628. headnum = 0
  1629. for title in headtitle:
  1630. sheet1.write(0, headnum, title)
  1631. headnum = headnum + 1
  1632. fields = [
  1633. 'id',
  1634. 'username',
  1635. 'phone',
  1636. 'userEmail',
  1637. 'data_joined',
  1638. 'uid',
  1639. 'channel',
  1640. 'status',
  1641. 'addTime',
  1642. 'endTime',
  1643. 'use_status',
  1644. 'has_unused',
  1645. 'desc',
  1646. 'payType',
  1647. 'price',
  1648. 'playcount',
  1649. 'ucode',
  1650. 'version'
  1651. ]
  1652. num = 1
  1653. for item in list_data:
  1654. fieldnum = 0
  1655. for key in fields:
  1656. val = item[key]
  1657. if key == 'payType':
  1658. if val == 1:
  1659. val = 'PayPal'
  1660. if val == 2:
  1661. val = '支付宝'
  1662. if val == 3:
  1663. val = '微信支付'
  1664. if val == 10:
  1665. val = '免费体验'
  1666. if val == 11:
  1667. val = '激活码'
  1668. sheet1.write(num, fieldnum, val)
  1669. fieldnum = fieldnum + 1
  1670. num = num + 1
  1671. workbook.save(response)
  1672. return response
  1673. except Exception as e:
  1674. print(e)
  1675. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1676. def getCloudDataList(self, request_dict, response):
  1677. year = request_dict.get('year', None)
  1678. Jan = int(time.mktime(time.strptime(year + '-1-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1679. Feb = int(time.mktime(time.strptime(year + '-2-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1680. Mar = int(time.mktime(time.strptime(year + '-3-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1681. Apr = int(time.mktime(time.strptime(year + '-4-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1682. May = int(time.mktime(time.strptime(year + '-5-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1683. Jun = int(time.mktime(time.strptime(year + '-6-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1684. Jul = int(time.mktime(time.strptime(year + '-7-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1685. Aug = int(time.mktime(time.strptime(year + '-8-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1686. Sep = int(time.mktime(time.strptime(year + '-9-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1687. Oct = int(time.mktime(time.strptime(year + '-10-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1688. Nov = int(time.mktime(time.strptime(year + '-11-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1689. Dec = int(time.mktime(time.strptime(year + '-12-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1690. Jan_next = int(time.mktime(time.strptime(str(int(year) + 1) + '-1-1 00:00:00', "%Y-%m-%d %H:%M:%S")))
  1691. list_data = []
  1692. vod_bucket_qs = VodBucketModel.objects.filter()
  1693. if not vod_bucket_qs.exists():
  1694. return response.json(173)
  1695. try:
  1696. for vod_bucket in vod_bucket_qs:
  1697. vod_bucket_id = vod_bucket.id
  1698. store_meal = Store_Meal.objects.filter(bucket_id=vod_bucket_id, lang__lang='cn').values('lang__title',
  1699. 'lang__content')
  1700. if not store_meal.exists():
  1701. continue
  1702. name = store_meal[0]['lang__title'] + '-' + store_meal[0]['lang__content']
  1703. order = Order_Model.objects.filter(rank__bucket_id=vod_bucket_id)
  1704. Jan_count = order.filter(status=1, addTime__range=[Jan, Feb]).count()
  1705. Feb_count = order.filter(status=1, addTime__range=[Feb, Mar]).count()
  1706. Mar_count = order.filter(status=1, addTime__range=[Mar, Apr]).count()
  1707. Apr_count = order.filter(status=1, addTime__range=[Apr, May]).count()
  1708. May_count = order.filter(status=1, addTime__range=[May, Jun]).count()
  1709. Jun_count = order.filter(status=1, addTime__range=[Jun, Jul]).count()
  1710. Jul_count = order.filter(status=1, addTime__range=[Jul, Aug]).count()
  1711. Aug_count = order.filter(status=1, addTime__range=[Aug, Sep]).count()
  1712. Sep_count = order.filter(status=1, addTime__range=[Sep, Oct]).count()
  1713. Oct_count = order.filter(status=1, addTime__range=[Oct, Nov]).count()
  1714. Nov_count = order.filter(status=1, addTime__range=[Nov, Dec]).count()
  1715. Dec_count = order.filter(status=1, addTime__range=[Dec, Jan_next]).count()
  1716. data = [Jan_count, Feb_count, Mar_count, Apr_count, May_count, Jun_count, Jul_count, Aug_count,
  1717. Sep_count,
  1718. Oct_count, Nov_count, Dec_count]
  1719. cloud_data = {
  1720. 'name': name,
  1721. 'type': 'line',
  1722. 'data': data,
  1723. }
  1724. list_data.append(cloud_data)
  1725. return response.json(0, {'list': list_data})
  1726. except Exception as e:
  1727. print(e)
  1728. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1729. @classmethod
  1730. def deviceAttritionAlert(cls, request_dict, response):
  1731. """
  1732. 流失预警界面
  1733. @param request_dict:
  1734. @param response:
  1735. @param userName:用户名
  1736. @param uid:设备uid
  1737. @param grade:预警等级
  1738. """
  1739. userName = request_dict.get('userName', None)
  1740. uid = request_dict.get('uid', None)
  1741. grade = request_dict.get('grade', None)
  1742. pageNo = request_dict.get('pageNo', None)
  1743. pageSize = request_dict.get('pageSize', None)
  1744. if not all({pageNo, pageSize}):
  1745. return response.json(444)
  1746. # 获取云存套餐信息表内的设备uid
  1747. page = int(pageNo)
  1748. line = int(pageSize)
  1749. if userName == '' or uid == '' or grade == '': # 判断是否为空
  1750. if userName == '':
  1751. userName = None
  1752. if uid == '':
  1753. uid = None
  1754. if grade == '':
  1755. grade = None
  1756. para_list = [userName, uid, grade]
  1757. not_upload_list = []
  1758. para_count = para_list.count(None)
  1759. try:
  1760. # 筛选数据
  1761. cursor = connection.cursor()
  1762. sql = "SELECT t1.userID_id, du.username, t1.uid, t1.addTime, t1.use_status, t1.`day`, t1.grade FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, t1.`day`, t1.grade FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, t1.`day`,(CASE WHEN t1.`day` >= '15' AND t1.`day` < '25' THEN '一号预警' WHEN t1.use_status = '1' AND t1.`day` >= '25' THEN '二号预警' WHEN t1.use_status = 2 AND t1.`day` >= '25' THEN '八号预警' ELSE '预警取消' END ) AS grade FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, t1.`day` FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, TIMESTAMPDIFF(DAY,FROM_UNIXTIME(t1.addTime, '%Y-%m-%d' ),DATE_FORMAT( NOW(), '%Y-%m-%d' )) AS 'day' FROM (SELECT di.userID_id, vub.uid, vub.addTime, vub.use_status FROM vod_uid_bucket AS vub, device_info AS di WHERE vub.uid = di.UID AND vub.addTime > '1669824000' GROUP BY di.userID_id) AS t1 WHERE t1.uid NOT IN (SELECT uid FROM uid_cloud_storage_count)) AS t1 WHERE t1.`day`>='15' AND t1.userID_id is NOT NULL) AS t1 ORDER BY t1.userID_id)AS t1 WHERE t1.userID_id NOT IN (SELECT di.userID_id FROM `uid_cloud_storage_count` AS vcsc LEFT JOIN device_info AS di ON vcsc.uid = di.UID WHERE di.userID_id is NOT NULL))AS t1 LEFT JOIN device_user AS du ON t1.userID_id = du.userID order by t1.addTime "
  1763. cursor.execute(sql)
  1764. uid_type_tuple = cursor.fetchall()
  1765. total = len(uid_type_tuple)
  1766. cursor.close() # 执行完,关闭
  1767. connection.close()
  1768. result_list = []
  1769. more_list = [] # 多个参数查询结果
  1770. new_list = [] # 单独一个参数查询结果
  1771. col_names = [desc[0] for desc in cursor.description]
  1772. for uid_type in uid_type_tuple:
  1773. uid_dict = dict(zip(col_names, uid_type))
  1774. result_list.append(uid_dict)
  1775. if para_count != 2 and para_count != 3: # 两个及以上参数进行筛查
  1776. if userName and uid and grade == None:
  1777. for result in result_list:
  1778. if result['username'] == userName and result['uid'] == uid:
  1779. more_list.append(result)
  1780. if userName and grade and uid == None:
  1781. for result in result_list:
  1782. if result['username'] == userName and result['grade'] == grade:
  1783. more_list.append(result)
  1784. if uid and grade and userName == None:
  1785. for result in result_list:
  1786. if result['uid'] == uid and result['grade'] == grade:
  1787. more_list.append(result)
  1788. if userName and uid and grade:
  1789. for result in result_list:
  1790. if result['username'] == userName and result['uid'] == uid and result['grade'] == grade:
  1791. more_list.append(result)
  1792. result_list = more_list
  1793. if para_count == 2: # 一个参数进行筛查
  1794. if userName:
  1795. for result in result_list:
  1796. if result['username'] == userName:
  1797. new_list.append(result)
  1798. if uid:
  1799. for result in result_list:
  1800. if result['uid'] == uid:
  1801. new_list.append(result)
  1802. if grade:
  1803. for result in result_list:
  1804. if result['grade'] == grade:
  1805. new_list.append(result)
  1806. result_list = new_list
  1807. else:
  1808. result_list = result_list
  1809. result_list = result_list[(page - 1) * line:page * line]
  1810. for item in result_list: # 获取账号下的云存设备数量
  1811. userID_id = item['userID_id']
  1812. device_info_qs = Device_Info.objects.filter(userID_id=userID_id).annotate(count=Count('UID')).values(
  1813. 'UID')
  1814. count = device_info_qs.count()
  1815. if count == 1 or count == 0:
  1816. item['device_number'] = count
  1817. else:
  1818. device_number = 0
  1819. for device_info in device_info_qs:
  1820. uid = device_info['UID']
  1821. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ucode', 'device_type')
  1822. ucode = uid_set_qs[0]['ucode'] if uid_set_qs.exists() else ''
  1823. device_type = uid_set_qs[0]['device_type'] if uid_set_qs.exists() else ''
  1824. cloud_vod = CommonService.is_cloud_device(ucode, device_type)
  1825. # 判断设备是否为ipc设备和是否支持云存
  1826. if cloud_vod:
  1827. device_number += 1
  1828. item['device_number'] = device_number
  1829. item['other_device'] = 0
  1830. not_upload_list.append(item)
  1831. return response.json(0, {'result_list': not_upload_list, 'total': total})
  1832. except Exception as e:
  1833. meg = '异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e))
  1834. return response.json(500, meg)
  1835. def deactivationPackage(self, request_dict, response):
  1836. """
  1837. 停用套餐
  1838. @param request_dict:
  1839. @param response:
  1840. """
  1841. status = request_dict.get('status', None)
  1842. if status in [1, 5, 6, 7]: # 付款状态
  1843. return response.json(10059)
  1844. uid = request_dict.get('uid', None)
  1845. orderID = request_dict.get('orderID', None)
  1846. orderType = request_dict.get('orderType', None)
  1847. payType = request_dict.get('payType', None)
  1848. userName = request_dict.get('userName', None)
  1849. # 查询订单
  1850. if not all([orderID, orderType, uid, userName]):
  1851. return response.json(444)
  1852. nowTime = int(time.time())
  1853. try:
  1854. with transaction.atomic():
  1855. # 云存套餐
  1856. if orderType == '0' and payType != '10':
  1857. order_qs = Order_Model.objects.filter(orderID=orderID, userID__username=userName, UID=uid).values(
  1858. 'rank__bucket_id')
  1859. if not order_qs.exists():
  1860. return response.json(14)
  1861. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, use_status=1).values('has_unused')
  1862. has_unused = uid_bucket_qs[0]['has_unused'] if uid_bucket_qs.exists() else ''
  1863. # 判断套餐是否唯一
  1864. if has_unused == 0:
  1865. uid_bucket_qs.update(endTime=nowTime)
  1866. CronUpdateDataView.updateUnusedUidBucket(response)
  1867. return response.json(0)
  1868. # 当设备套餐不唯一时
  1869. # 判断停用套餐是否是为未使用套餐
  1870. unused_uid_Meal_qs = Unused_Uid_Meal.objects.filter(uid=uid,
  1871. bucket_id=order_qs[0]['rank__bucket_id'])
  1872. unused_uid_Meal_number = unused_uid_Meal_qs.count()
  1873. if unused_uid_Meal_number == 1:
  1874. unused_uid_Meal_qs.delete()
  1875. return response.json(0)
  1876. return response.json(10059) # 未使用套餐类型重复
  1877. # AI套餐
  1878. if orderType == '1' and payType != '10':
  1879. return response.json(10059)
  1880. # order_qs = Order_Model.objects.filter(orderID=orderID, userID__username=userName, UID=uid).values(
  1881. # 'ai_rank_id')
  1882. # order_qs = order_qs.objects.filter(UID=uid)
  1883. # ai_service_qs = AiService.objects.filter(uid=uid, use_status=1).values('addTime', 'endTime')
  1884. # ai_service_number = ai_service_qs.count()
  1885. # if ai_service_number <= 1:
  1886. # ai_service_qs.update(endTime=nowTime)
  1887. # return response.json(0)
  1888. # # 当设备套餐不唯一时
  1889. # ai_service_qs = AiService.objects.filter(uid=uid, bucket_id=order_qs[0]['ai_rank_id'])
  1890. # ai_serverice_number = ai_service_qs.count()
  1891. # if ai_serverice_number == 1:
  1892. # ai_service_qs.update(endTime=nowTime)
  1893. # return response.json(0)
  1894. # return response.json(10059) # 未使用套餐类型重复
  1895. # 联通4G套餐
  1896. if orderType == '2' and payType != '10':
  1897. now_time = int(time.time())
  1898. combo_info_qs = UnicomComboOrderInfo.objects.filter(~Q(status=2), order_id=orderID)
  1899. if not combo_info_qs.exists():
  1900. return response.json(10059)
  1901. iccid = combo_info_qs.first().iccid
  1902. combo_info_qs.update(status=2, updated_time=now_time)
  1903. combo_info_qs = UnicomComboOrderInfo.objects.filter(status=1)
  1904. if combo_info_qs:
  1905. return response.json(10059)
  1906. unicom_api = UnicomObjeect()
  1907. usage_flow = unicom_api.get_flow_usage_total(iccid)
  1908. today = datetime.datetime.today()
  1909. year = today.year
  1910. month = today.month
  1911. task_view = UnicomComboTaskView()
  1912. result = task_view.query_unused_combo_and_activate(iccid, year, month, usage_flow)
  1913. if not result:
  1914. # 停用设备
  1915. unicom_api.change_device_to_disable(iccid)
  1916. else:
  1917. unicom_api.change_device_to_activate(iccid)
  1918. return response.json(0)
  1919. return response.json(173)
  1920. except Exception as e:
  1921. print(e)
  1922. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1923. def cloudDataExport(self, request_dict, response):
  1924. """
  1925. 流失预警导出功能
  1926. """
  1927. cursor = connection.cursor()
  1928. sql = "SELECT t1.userID_id, du.username, t1.uid, t1.addTime, t1.use_status, t1.`day`, t1.grade FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, t1.`day`, t1.grade FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, t1.`day`,(CASE WHEN t1.`day` >= '15' AND t1.`day` < '25' THEN '一号预警' WHEN t1.use_status = '1' AND t1.`day` >= '25' THEN '二号预警' WHEN t1.use_status = 2 AND t1.`day` >= '25' THEN '八号预警' ELSE '预警取消' END ) AS grade FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, t1.`day` FROM(SELECT t1.userID_id, t1.uid, t1.addTime, t1.use_status, TIMESTAMPDIFF(DAY,FROM_UNIXTIME(t1.addTime, '%Y-%m-%d' ),DATE_FORMAT( NOW(), '%Y-%m-%d' )) AS 'day' FROM (SELECT di.userID_id, vub.uid, vub.addTime, vub.use_status FROM vod_uid_bucket AS vub, device_info AS di WHERE vub.uid = di.UID AND vub.addTime > '1669824000' GROUP BY di.userID_id) AS t1 WHERE t1.uid NOT IN (SELECT uid FROM uid_cloud_storage_count)) AS t1 WHERE t1.`day`>='15' AND t1.userID_id is NOT NULL) AS t1 ORDER BY t1.userID_id)AS t1 WHERE t1.userID_id NOT IN (SELECT di.userID_id FROM `uid_cloud_storage_count` AS vcsc LEFT JOIN device_info AS di ON vcsc.uid = di.UID WHERE di.userID_id is NOT NULL))AS t1 LEFT JOIN device_user AS du ON t1.userID_id = du.userID order by t1.addTime "
  1929. cursor.execute(sql)
  1930. uid_type_tuple = cursor.fetchall()
  1931. cursor.close() # 执行完,关闭
  1932. connection.close()
  1933. result_list = []
  1934. not_upload_list = []
  1935. try:
  1936. with transaction.atomic():
  1937. col_names = [desc[0] for desc in cursor.description]
  1938. for uid_type in uid_type_tuple:
  1939. uid_dict = dict(zip(col_names, uid_type))
  1940. result_list.append(uid_dict)
  1941. for item in result_list: # 获取账号下的云存设备数量
  1942. device_info_qs = Device_Info.objects.filter(userID_id=item['userID_id']).values('UID')
  1943. count = device_info_qs.count()
  1944. if count == 1 or count == 0:
  1945. item['device_number'] = count
  1946. else:
  1947. device_number = 0
  1948. for device_info in device_info_qs:
  1949. uid_set_qs = UidSetModel.objects.filter(uid=device_info['UID']).values('ucode',
  1950. 'device_type')
  1951. device_type_qs = DeviceTypeModel.objects.filter(type=uid_set_qs[0]['device_type']).values(
  1952. 'model')
  1953. model = device_type_qs[0]['model'] if device_type_qs.exists() else ''
  1954. # 判断设备是否为ipc设备和是否支持云存
  1955. if model == 2:
  1956. if len(uid_set_qs[0]['ucode']) > 4:
  1957. number = uid_set_qs[0]['ucode'][-4]
  1958. else:
  1959. continue
  1960. if number in ['4', '5']:
  1961. device_number += 1
  1962. else:
  1963. continue
  1964. item['device_number'] = device_number
  1965. item['other_device'] = 0
  1966. not_upload_list.append(item)
  1967. # 创建Excel,导出所有流失预警数据
  1968. file_name = "流失预警.xls"
  1969. if not_upload_list:
  1970. ws = xlwt.Workbook(encoding="UTF-8")
  1971. w = ws.add_sheet('流失预警', cell_overwrite_ok=True)
  1972. w.write(0, 0, u'用户名')
  1973. w.write(0, 1, u'用户ID')
  1974. w.write(0, 2, u'设备UID')
  1975. w.write(0, 3, u'设备自云存开通起多少天没有上传数据')
  1976. w.write(0, 4, u'设备数量')
  1977. w.write(0, 5, u'用户有无上传过数据')
  1978. w.write(0, 6, u'是否有有效期内的付费套餐')
  1979. w.write(0, 7, u'预警级别')
  1980. excel_row = 1
  1981. for obj in not_upload_list:
  1982. data_username = obj['username']
  1983. data_userID_id = obj['userID_id']
  1984. data_uid = obj['uid']
  1985. data_day = obj['day']
  1986. data_device_number = obj['device_number']
  1987. if data_device_number == 1:
  1988. data_device_number = 'N/A'
  1989. data_use_status = obj['use_status']
  1990. if data_use_status == 1:
  1991. data_use_status = '有'
  1992. else:
  1993. data_use_status = '无'
  1994. data_other_device = '无'
  1995. data_grade = obj['grade']
  1996. w.write(excel_row, 0, data_username)
  1997. w.write(excel_row, 1, data_userID_id)
  1998. w.write(excel_row, 2, data_uid)
  1999. w.write(excel_row, 3, data_day)
  2000. w.write(excel_row, 4, data_device_number)
  2001. w.write(excel_row, 5, data_other_device)
  2002. w.write(excel_row, 6, data_use_status)
  2003. w.write(excel_row, 7, data_grade)
  2004. excel_row += 1
  2005. # 生成相应格式给前端
  2006. res = HttpResponse(content_type='application/vnd.ms-excel')
  2007. res['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file_name))
  2008. ws.save(res)
  2009. return res
  2010. except Exception as e:
  2011. meg = '异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e))
  2012. return response.json(500, meg)