CronTaskController.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2022 #
  5. # @Time : 2022/4/1 11:27
  6. # @Author : ming
  7. # @Email : zhangdongming@asj6.wecom.work
  8. # @File : CronTaskController.py
  9. # @Software: PyCharm
  10. import datetime
  11. import io
  12. import json
  13. import threading
  14. import time
  15. import zipfile
  16. import paypalrestsdk
  17. import requests
  18. import csv
  19. from django.db import connection, connections, transaction
  20. from django.db.models import Q, Sum, Count
  21. from django.views import View
  22. from Ansjer.config import USED_SERIAL_REDIS_LIST, UNUSED_SERIAL_REDIS_LIST, CONFIG_INFO, CONFIG_US, \
  23. RESET_REGION_ID_SERIAL_REDIS_LIST, LOGGER, PAYPAL_CRD, CONFIG_EUR, DETECT_PUSH_DOMAINS
  24. from Model.models import Device_User, Device_Info, UidSetModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
  25. VodHlsModel, ExperienceContextModel, AiService, VodHlsSummary, VideoPlaybackTimeModel, DeviceUserSummary, \
  26. CountryModel, DeviceTypeModel, OrdersSummary, DeviceInfoSummary, CompanySerialModel, \
  27. CloudLogModel, UidCloudStorageCount, UserExModel, DeviceDomainRegionModel, VodHlsTag, VodHlsTagType, IcloudService, \
  28. Store_Meal, Lang, VodBucketModel, UnicomComboOrderInfo, UnicomDeviceInfo, AbnormalOrder, DailyReconciliation, \
  29. CustomizedPush, UIDCompanySerialModel, UIDModel, LogModel
  30. from Object.RedisObject import RedisObject
  31. from Object.ResponseObject import ResponseObject
  32. from Object.utils import LocalDateTimeUtil
  33. from Object.utils.PayPalUtil import PayPalService
  34. from Service.CommonService import CommonService
  35. from Service.VodHlsService import SplitVodHlsObject
  36. from Object.UnicomObject import UnicomObjeect
  37. from Object.WechatPayObject import WechatPayObject
  38. from Object.AliPayObject import AliPayObject
  39. from dateutil.relativedelta import relativedelta
  40. class CronDelDataView(View):
  41. def get(self, request, *args, **kwargs):
  42. request.encoding = 'utf-8'
  43. operation = kwargs.get('operation')
  44. return self.validation(request.GET, request, operation)
  45. def post(self, request, *args, **kwargs):
  46. request.encoding = 'utf-8'
  47. operation = kwargs.get('operation')
  48. return self.validation(request.POST, request, operation)
  49. def validation(self, request_dict, request, operation):
  50. response = ResponseObject()
  51. if operation == 'delAccessLog': # 定时删除访问接口数据
  52. return self.delAccessLog(response)
  53. elif operation == 'delPushInfo': # 定时删除推送数据
  54. return self.delPushInfo(response)
  55. elif operation == 'delPushInfoV2': # 定时删除推送数据V2
  56. return self.delPushInfoV2(response)
  57. elif operation == 'delVodHls': # 定时删除云存播放列表
  58. return self.delVodHls(response)
  59. elif operation == 'delCloudLog': # 定时删除云存接口数据
  60. return self.delCloudLog(response)
  61. elif operation == 'delTesterDevice': # 定时删除测试账号下的设备数据
  62. return self.delTesterDevice(response)
  63. elif operation == 'delAppLog': # 定时删除app日志
  64. return self.delAppLog(response)
  65. elif operation == 'UpdateConfiguration': # 定时更新配置
  66. return self.UpdateConfiguration(response)
  67. elif operation == 'cloud-log':
  68. return self.uid_cloud_storage_upload_count(response)
  69. elif operation == 'delDeviceLog': # 定时删除设备日志
  70. return self.del_device_log(response)
  71. elif operation == 'delCampaignsLogs':
  72. return self.del_campaigns_log(response)
  73. else:
  74. return response.json(404)
  75. @staticmethod
  76. def UpdateConfiguration(response):
  77. """
  78. 定时更新配置
  79. @param response: 响应对象
  80. @return:
  81. """
  82. try:
  83. ucode_list = ['823C01552AA',
  84. '823C01550AA',
  85. '823C01550XA',
  86. '823C01850XA',
  87. '730201350AA',
  88. '730201350AA',
  89. '730201450AA',
  90. '730201450MA',
  91. '72V201252AA',
  92. '72V201253AA',
  93. '72V201353AA',
  94. '72V201354AA',
  95. '72V201355AA',
  96. '72V201254AA',
  97. 'V82301850AA',
  98. 'V82301850XA',
  99. '72V201257AA', '72V201256AA']
  100. UidSetModel.objects.filter(ucode__in=ucode_list, is_human=0).update(is_human=1)
  101. ucode_list = ['72V201257AA', '72V201254AA'] # 4G规格码
  102. UidSetModel.objects.filter(ucode__in=ucode_list, mobile_4g=0).update(mobile_4g=1)
  103. # 根据设备规格码定时更新默认算法类型类型
  104. ucode_list = ['823C01552AA', '823C01550AA', '823C01550XA', 'C18201550KA',
  105. '823C01550TA', '823C01550VA', '823C01850XA', 'C18201850KA',
  106. '823C01850TA', '823C01850VA', 'C22501850VA']
  107. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=47)
  108. ucode_list = ['730201350AA', '730201450AA', '730201450MA', '730201450NA']
  109. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=7)
  110. ucode_list = ['V82301850AA', 'V82301850XA']
  111. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=2031)
  112. # 根据设备规格码更新默认个性化语音值
  113. ucode_list = ['823C01552AA', '823C01550XA', 'C18201550KA', '823C01550TA',
  114. '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', '823C01850VA',
  115. '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA',
  116. '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA', 'C22501850VA',
  117. 'V82301850AA', 'V82301850XA', '72V201257AA', '72V201256AA']
  118. UidSetModel.objects.filter(ucode__in=ucode_list, is_custom_voice=0).update(is_custom_voice=1)
  119. # 根据设备规格码更新is_ai
  120. ucode_list = ['823C01552AA', '823C01550XA', 'C18201550KA', '823C01550TA',
  121. '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', '823C01850VA',
  122. '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA',
  123. '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA', 'C22501850VA',
  124. 'V82301850AA', 'V82301850XA', '72V201257AA', '72V201256AA', '730201350AA']
  125. UidSetModel.objects.filter(ucode__in=ucode_list, is_ai=2).update(is_ai=1)
  126. return response.json(0)
  127. except Exception as e:
  128. LOGGER.info('UpdateConfiguration异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  129. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  130. @staticmethod
  131. def delAppLog(response):
  132. """
  133. 定时删除app日志
  134. @param response: 响应对象
  135. @return:
  136. """
  137. nowTime = int(time.time())
  138. try:
  139. cursor = connection.cursor()
  140. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  141. sql = 'DELETE FROM `app_log` WHERE add_time<{}'.format(month_ago_time)
  142. cursor.execute(sql)
  143. cursor.close()
  144. return response.json(0)
  145. except Exception as e:
  146. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  147. @staticmethod
  148. def uid_cloud_storage_upload_count(response):
  149. try:
  150. now_time = int(time.time())
  151. local_time = LocalDateTimeUtil.get_before_days_timestamp(now_time)
  152. format_str = '%Y-%m-%d'
  153. date_str = LocalDateTimeUtil.time_stamp_to_time(local_time, format_str)
  154. start_time, end_time = LocalDateTimeUtil.get_start_and_end_time(date_str, format_str)
  155. cs_uid_qs = UID_Bucket.objects.filter(addTime__gte=int(1669824000)).values('uid')
  156. if not cs_uid_qs.exists():
  157. return response.json(0)
  158. for item in cs_uid_qs:
  159. uid = item['uid']
  160. cloud_log_qs = CloudLogModel.objects.filter(uid=uid, operation=r'cloudstorage/storeplaylist',
  161. time__gte=start_time, time__lte=end_time)
  162. cloud_log_qs = cloud_log_qs.values('uid')[0:1]
  163. if not cloud_log_qs.exists():
  164. continue
  165. count_data = {'uid': uid, 'count': cloud_log_qs.count(), 'created_time': end_time,
  166. 'updated_time': end_time}
  167. UidCloudStorageCount.objects.create(**count_data)
  168. return response.json(0)
  169. except Exception as e:
  170. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  171. return response.json(500)
  172. @staticmethod
  173. def delAccessLog(response):
  174. try:
  175. cursor = connection.cursor()
  176. # 删除7天前的数据
  177. last_week = LocalDateTimeUtil.get_last_week()
  178. sql = 'DELETE FROM access_log WHERE time < %s limit %s'
  179. cursor.execute(sql, [last_week, 10000])
  180. # 关闭游标
  181. cursor.close()
  182. connection.close()
  183. return response.json(0)
  184. except Exception as e:
  185. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  186. @classmethod
  187. def delPushInfo(cls, response):
  188. now_time = int(time.time())
  189. try:
  190. # 当前时间转日期
  191. local_date_now = str(datetime.datetime.fromtimestamp(int(now_time)).date())
  192. # 根据日期获取周几
  193. week_val = LocalDateTimeUtil.date_to_week(local_date_now)
  194. # 根据当前时间获取7天前时间戳
  195. expiration_time = LocalDateTimeUtil.get_before_days_timestamp(now_time, 7)
  196. # 异步删除推送消息
  197. kwargs = {
  198. 'week_val': week_val,
  199. 'expiration_time': expiration_time
  200. }
  201. del_push_info_thread = threading.Thread(
  202. target=cls.del_push_info_data,
  203. kwargs=kwargs)
  204. del_push_info_thread.start()
  205. return response.json(0)
  206. except Exception as e:
  207. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  208. @staticmethod
  209. def del_push_info_data(**kwargs):
  210. cursor = connections['mysql02'].cursor()
  211. # 获取删除星期列表
  212. week_val = kwargs['week_val']
  213. del_week_val_list = [i for i in range(1, 8)]
  214. # 移除当天和前后两天
  215. del_week_val_list.remove(week_val)
  216. if week_val == 1:
  217. pre_week_val = 7
  218. else:
  219. pre_week_val = week_val - 1
  220. del_week_val_list.remove(pre_week_val)
  221. if week_val == 7:
  222. nex_week_val = 1
  223. else:
  224. nex_week_val = week_val + 1
  225. del_week_val_list.remove(nex_week_val)
  226. expiration_time = kwargs['expiration_time']
  227. # 每次删除条数
  228. size = 5000
  229. # 删除7天前的数据
  230. sql = "DELETE FROM equipment_info WHERE addTime<= %s LIMIT %s "
  231. cursor.execute(sql, [expiration_time, size])
  232. for week_val in del_week_val_list:
  233. if week_val == 1:
  234. sql = "DELETE FROM equipment_info_monday WHERE add_time<= %s LIMIT %s "
  235. if week_val == 2:
  236. sql = "DELETE FROM equipment_info_tuesday WHERE add_time<= %s LIMIT %s "
  237. if week_val == 3:
  238. sql = "DELETE FROM equipment_info_wednesday WHERE add_time<= %s LIMIT %s "
  239. if week_val == 4:
  240. sql = "DELETE FROM equipment_info_thursday WHERE add_time<= %s LIMIT %s "
  241. if week_val == 5:
  242. sql = "DELETE FROM equipment_info_friday WHERE add_time<= %s LIMIT %s "
  243. if week_val == 6:
  244. sql = "DELETE FROM equipment_info_saturday WHERE add_time<= %s LIMIT %s "
  245. if week_val == 7:
  246. sql = "DELETE FROM equipment_info_sunday WHERE add_time<= %s LIMIT %s "
  247. cursor.execute(sql, [expiration_time, size])
  248. # 关闭游标
  249. cursor.close()
  250. @classmethod
  251. def delPushInfoV2(cls, response):
  252. try:
  253. del_push_info_thread = threading.Thread(
  254. target=cls.del_push_info_data_v2)
  255. del_push_info_thread.start()
  256. return response.json(0)
  257. except Exception as e:
  258. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  259. @staticmethod
  260. def del_push_info_data_v2():
  261. cursor = connections['mysql02'].cursor()
  262. # 获取7天前时间戳
  263. now_time = int(time.time())
  264. expiration_time = LocalDateTimeUtil.get_before_days_timestamp(now_time, 7)
  265. # 每次删除条数
  266. size = 5000
  267. for i in range(1, 21):
  268. sql = "DELETE FROM equipment_info_{} WHERE add_time< %s LIMIT %s ".format(i)
  269. cursor.execute(sql, [expiration_time, size])
  270. # 关闭游标
  271. cursor.close()
  272. @staticmethod
  273. def delVodHls(response):
  274. nowTime = int(time.time())
  275. try:
  276. CronDelDataView.del_vod_hls_tag()
  277. cursor = connection.cursor()
  278. month_ago_time = nowTime - 3 * 30 * 24 * 60 * 60 # 删除3个月前的数据
  279. sql = 'DELETE FROM `vod_hls` WHERE endTime<{} LIMIT 50000'.format(month_ago_time)
  280. cursor.execute(sql)
  281. cursor.close()
  282. # 删除vod_hls分表数据
  283. split_vod_hls_obj = SplitVodHlsObject()
  284. split_vod_hls_obj.del_vod_hls_data(end_time__lt=month_ago_time)
  285. return response.json(0)
  286. except Exception as e:
  287. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  288. @staticmethod
  289. def del_vod_hls_tag():
  290. """
  291. 删除AI标签记录
  292. """
  293. e_time = LocalDateTimeUtil.get_before_days_timestamp(int(time.time()), 30)
  294. VodHlsTagType.objects.filter(created_time__lt=e_time).delete()
  295. VodHlsTag.objects.filter(created_time__lt=e_time).delete()
  296. @staticmethod
  297. def delCloudLog(response):
  298. nowTime = int(time.time())
  299. cursor = connection.cursor()
  300. try:
  301. # 删除3个月前的数据
  302. sql = "DELETE FROM `cloud_log` WHERE time<={} LIMIT 50000".format(
  303. nowTime - 3 * 30 * 24 * 60 * 60)
  304. cursor.execute(sql)
  305. # 关闭游标
  306. cursor.close()
  307. return response.json(0)
  308. except Exception as e:
  309. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  310. @staticmethod
  311. def delTesterDevice(response):
  312. try:
  313. userID_list = [
  314. 'tech01@ansjer.com',
  315. 'tech02@ansjer.com',
  316. 'tech03@ansjer.com',
  317. 'tech04@ansjer.com',
  318. 'tech05@ansjer.com',
  319. 'tech06@ansjer.com',
  320. 'tech07@ansjer.com',
  321. 'tech08@ansjer.com',
  322. 'tech09@ansjer.com',
  323. 'tech10@ansjer.com',
  324. 'fix01@ansjer.com',
  325. 'fix02@ansjer.com',
  326. 'fix03@ansjer.com',
  327. 'fix04@ansjer.com',
  328. 'fix05@ansjer.com']
  329. device_user = Device_User.objects.filter(username__in=userID_list)
  330. device_info_qs = Device_Info.objects.filter(
  331. userID__in=device_user).values('UID')
  332. uid_list = []
  333. for device_info in device_info_qs:
  334. uid_list.append(device_info['UID'])
  335. with transaction.atomic():
  336. # 删除设备云存相关数据
  337. UidSetModel.objects.filter(uid__in=uid_list).delete()
  338. UID_Bucket.objects.filter(uid__in=uid_list).delete()
  339. Unused_Uid_Meal.objects.filter(uid__in=uid_list).delete()
  340. # Order_Model.objects.filter(UID__in=uid_list).delete()
  341. StsCrdModel.objects.filter(uid__in=uid_list).delete()
  342. VodHlsModel.objects.filter(uid__in=uid_list).delete()
  343. # 删除vod_hls分表数据
  344. split_vod_hls_obj = SplitVodHlsObject()
  345. split_vod_hls_obj.del_vod_hls_data(uid__in=uid_list)
  346. ExperienceContextModel.objects.filter(uid__in=uid_list).delete()
  347. Device_Info.objects.filter(userID__in=device_user).delete()
  348. return response.json(0)
  349. except Exception as e:
  350. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  351. @staticmethod
  352. def del_device_log(response):
  353. """
  354. 定时删除设备日志
  355. @param response: 响应对象
  356. @return:
  357. """
  358. nowTime = int(time.time())
  359. try:
  360. cursor = connection.cursor()
  361. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  362. sql = 'DELETE FROM `device_log` WHERE unix_timestamp(add_time)<{}'.format(month_ago_time)
  363. cursor.execute(sql)
  364. cursor.close()
  365. return response.json(0)
  366. except Exception as e:
  367. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  368. @staticmethod
  369. def del_campaigns_log(response):
  370. """
  371. 定时删除广告日志
  372. @param response: 响应对象
  373. @return:
  374. """
  375. nowTime = int(time.time())
  376. try:
  377. cursor = connection.cursor()
  378. month_ago_time = nowTime - 90 * 24 * 60 * 60 # 保留近90天的数据
  379. sql = f'DELETE FROM `open_screen_campaign` WHERE update_time<{month_ago_time}'
  380. cursor.execute(sql)
  381. cursor.close()
  382. return response.json(0)
  383. except Exception as e:
  384. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  385. class CronUpdateDataView(View):
  386. def get(self, request, *args, **kwargs):
  387. request.encoding = 'utf-8'
  388. operation = kwargs.get('operation')
  389. return self.validation(request.GET, request, operation)
  390. def post(self, request, *args, **kwargs):
  391. request.encoding = 'utf-8'
  392. operation = kwargs.get('operation')
  393. return self.validation(request.POST, request, operation)
  394. def validation(self, request_dict, request, operation):
  395. response = ResponseObject()
  396. if operation == 'updateUnusedUidBucket': # 定时更新过期云存关联的未使用套餐状态
  397. return self.updateUnusedUidBucket(response)
  398. elif operation == 'updateUnusedAiService': # 定时更新过期ai关联的未使用套餐状态
  399. return self.updateUnusedAiService(response)
  400. elif operation == 'updateIcloudService': # 定时更新过期云盘套餐使用状态
  401. return self.updateIcloudService(response)
  402. elif operation == 'reqUpdateSerialStatus': # 定时请求更新序列号状态
  403. return self.reqUpdateSerialStatus(response)
  404. elif operation == 'updateSerialStatus': # 更新序列号状态
  405. return self.updateSerialStatus(request_dict, response)
  406. elif operation == 'reset-region-id': # 重置地区id
  407. return self.reset_region_id(request_dict, response)
  408. elif operation == 'updateVodMeal': # 定时修改体验套餐有效期为1个月
  409. return self.update_vod_meal(request_dict, response)
  410. elif operation == 'checkCustomizedPush': # 定时检查定制化推送,重新执行没有推送成功的请求
  411. return self.check_customized_push(response)
  412. else:
  413. return response.json(404)
  414. @staticmethod
  415. def updateUnusedUidBucket(response):
  416. """
  417. 监控云存套餐过期修改状态
  418. @param response:
  419. @return:
  420. """
  421. # 定时更新已过期套餐修改状态为2
  422. now_time = int(time.time())
  423. expired_uid_bucket = UID_Bucket.objects.filter(endTime__lte=now_time)
  424. expired_uid_bucket = expired_uid_bucket.filter(~Q(use_status=2)).values('id')
  425. if expired_uid_bucket.exists():
  426. expired_uid_bucket.update(use_status=2)
  427. # 监控有未使用套餐则自动生效
  428. expired_uid_buckets = UID_Bucket.objects.filter(endTime__lte=now_time, has_unused=1).values("id", "uid")[0:1000]
  429. for expired_uid_bucket in expired_uid_buckets:
  430. unuseds = Unused_Uid_Meal.objects.filter(
  431. uid=expired_uid_bucket['uid']).values(
  432. "id",
  433. "uid",
  434. "channel",
  435. "addTime",
  436. "expire",
  437. "is_ai",
  438. "bucket_id",
  439. "order_id").order_by('addTime')
  440. if not unuseds.exists():
  441. continue
  442. unused = unuseds[0]
  443. try:
  444. with transaction.atomic():
  445. count_unused = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).count()
  446. has_unused = 1 if count_unused > 1 else 0
  447. end_time = CommonService.calcMonthLater(unused['expire'])
  448. UID_Bucket.objects.filter(
  449. uid=expired_uid_bucket['uid']).update(
  450. channel=unused['channel'],
  451. endTime=end_time,
  452. bucket_id=unused['bucket_id'],
  453. updateTime=now_time,
  454. use_status=1,
  455. has_unused=has_unused,
  456. orderId=unused['order_id'])
  457. if unused['is_ai']:
  458. ai_service = AiService.objects.filter(uid=expired_uid_bucket['uid'], channel=unused['channel'])
  459. if ai_service.exists():
  460. ai_service.update(updTime=now_time, use_status=1, orders_id=unused['order_id'],
  461. endTime=end_time)
  462. else:
  463. AiService.objects.create(uid=expired_uid_bucket['uid'], channel=unused['channel'],
  464. detect_status=1, addTime=now_time, orders_id=unused['order_id'],
  465. updTime=now_time, endTime=end_time, use_status=1)
  466. Unused_Uid_Meal.objects.filter(id=unused['id']).delete()
  467. StsCrdModel.objects.filter(uid=expired_uid_bucket['uid']).delete() # 删除sts记录
  468. except Exception as e:
  469. print(repr(e))
  470. continue
  471. return response.json(0)
  472. @staticmethod
  473. def updateUnusedAiService(response):
  474. now_time = int(time.time())
  475. ai_service_qs = AiService.objects.filter(
  476. endTime__lte=now_time,
  477. use_status=1).values(
  478. 'id',
  479. 'uid')[
  480. 0:200]
  481. for ai_service in ai_service_qs:
  482. try:
  483. with transaction.atomic():
  484. AiService.objects.filter(
  485. id=ai_service['id']).update(
  486. use_status=2) # 更新过期ai订单状态
  487. # 如果存在未使用套餐,更新为使用
  488. unused_ai_service = AiService.objects.filter(
  489. uid=ai_service['uid'],
  490. use_status=0).order_by('addTime')[
  491. :1].values(
  492. 'id',
  493. 'endTime')
  494. if unused_ai_service.exists():
  495. # 未使用套餐的endTime在购买的时候保存为有效时间
  496. effective_day = unused_ai_service[0]['endTime']
  497. endTime = now_time + effective_day
  498. AiService.objects.filter(
  499. id=unused_ai_service[0]['id']).update(
  500. use_status=1, endTime=endTime, updTime=now_time)
  501. except Exception:
  502. continue
  503. return response.json(0)
  504. @staticmethod
  505. def updateIcloudService(response):
  506. """
  507. 监控云盘套餐过期修改状态
  508. @param response:
  509. @return:
  510. """
  511. # 定时更新已过期套餐修改状态为2
  512. now_time = int(time.time())
  513. try:
  514. IcloudService.objects.filter(Q(end_time__lte=now_time), ~Q(end_time=0),
  515. ~Q(use_status=1)).update(use_status=1)
  516. return response.json(0)
  517. except Exception as e:
  518. return response.json(500)
  519. @classmethod
  520. def reqUpdateSerialStatus(cls, response):
  521. redis_obj = RedisObject()
  522. # 更新已使用序列号其他服务器的状态
  523. used_serial_redis_list = redis_obj.lrange(USED_SERIAL_REDIS_LIST, 0, -1) # 读取redis已使用序列号
  524. if used_serial_redis_list:
  525. LOGGER.info('---请求更新已使用序列号列表---used_serial_redis_list:{}'.format(used_serial_redis_list))
  526. used_serial_redis_list = [str(i, 'utf-8') for i in used_serial_redis_list]
  527. cls.do_request_function(used_serial_redis_list, 3)
  528. # 更新未使用序列号其他服务器的状态
  529. unused_serial_redis_list = redis_obj.lrange(UNUSED_SERIAL_REDIS_LIST, 0, -1) # 读取redis未使用序列号
  530. if unused_serial_redis_list:
  531. LOGGER.info('---请求更新未使用序列号列表---unused_serial_redis_list:{}'.format(unused_serial_redis_list))
  532. unused_serial_redis_list = [str(i, 'utf-8') for i in unused_serial_redis_list]
  533. cls.do_request_function(unused_serial_redis_list, 1)
  534. # 重置地区id
  535. reset_region_id_serial_redis_list = redis_obj.lrange(RESET_REGION_ID_SERIAL_REDIS_LIST, 0, -1) # 读取redis未使用序列号
  536. if reset_region_id_serial_redis_list:
  537. LOGGER.info('---请求重置地区id的序列号列表---:{}'.format(reset_region_id_serial_redis_list))
  538. reset_region_id_serial_redis_list = [str(i, 'utf-8') for i in reset_region_id_serial_redis_list]
  539. cls.do_request_reset_region_id(reset_region_id_serial_redis_list)
  540. return response.json(0)
  541. @staticmethod
  542. def do_request_function(serial_redis_list, status):
  543. """
  544. 请求更新序列号状态
  545. @param serial_redis_list: 序列号redis列表
  546. @param status: 状态, 1: 未使用, 3: 已占用
  547. """
  548. data = {
  549. 'serial_redis_list': str(serial_redis_list),
  550. 'status': status
  551. }
  552. # 确认域名列表
  553. orders_domain_name_list = CommonService.get_orders_domain_name_list()
  554. redis_obj = RedisObject()
  555. LOGGER.info('---请求更新序列号线程---data:{},orders_domain_name_list:{}'.format(data, orders_domain_name_list))
  556. try:
  557. requests_failed_flag = False # 请求失败标志位
  558. for domain_name in orders_domain_name_list:
  559. url = '{}cron/update/updateSerialStatus'.format(domain_name)
  560. response = requests.post(url=url, data=data, timeout=5)
  561. LOGGER.info('---请求更新序列号响应时间---:{}'.format(response.elapsed.total_seconds()))
  562. result = response.json()
  563. if result['result_code'] != 0: # 请求失败标志位置位
  564. requests_failed_flag = True
  565. break
  566. # 状态为未使用,重置美洲服的地区id
  567. if status == 1: # 美洲服直接更新
  568. if CONFIG_INFO == CONFIG_US:
  569. DeviceDomainRegionModel.objects.filter(~Q(region_id=0), serial_number__in=serial_redis_list). \
  570. update(region_id=0)
  571. else: # 其他服请求到美洲服更新
  572. req_url = 'https://www.dvema.com/cron/update/reset-region-id'
  573. req_data = {
  574. 'serial_redis_list': str(serial_redis_list)
  575. }
  576. response = requests.post(url=req_url, data=req_data, timeout=5)
  577. LOGGER.info('---请求重置地区id响应时间---:{}'.format(response.elapsed.total_seconds()))
  578. result = response.json()
  579. if result['result_code'] != 0: # 请求失败标志位置位
  580. requests_failed_flag = True
  581. break
  582. if not requests_failed_flag: # 请求成功删除redis序列号
  583. if status == 1:
  584. for i in serial_redis_list:
  585. redis_obj.lrem(UNUSED_SERIAL_REDIS_LIST, 0, i)
  586. elif status == 3:
  587. for i in serial_redis_list:
  588. redis_obj.lrem(USED_SERIAL_REDIS_LIST, 0, i)
  589. except Exception as e:
  590. LOGGER.info('---更新序列号状态异常---:{}'.format(repr(e)))
  591. @staticmethod
  592. def do_request_reset_region_id(reset_region_id_serial_redis_list):
  593. """
  594. 请求重置地区id
  595. @param reset_region_id_serial_redis_list: 序列号redis列表
  596. """
  597. redis_obj = RedisObject()
  598. requests_failed_flag = False # 请求失败标志位
  599. data = {
  600. 'serial_redis_list': str(reset_region_id_serial_redis_list),
  601. }
  602. url = 'https://www.dvema.com/cron/update/reset-region-id'
  603. try:
  604. response = requests.post(url=url, data=data, timeout=5)
  605. result = response.json()
  606. if result['result_code'] != 0: # 请求失败标志位置位
  607. requests_failed_flag = True
  608. if not requests_failed_flag: # 请求成功删除redis序列号
  609. for serial in reset_region_id_serial_redis_list:
  610. redis_obj.lrem(RESET_REGION_ID_SERIAL_REDIS_LIST, 0, serial)
  611. except Exception as e:
  612. LOGGER.info('---请求重置地区id异常---:{}'.format(repr(e)))
  613. @staticmethod
  614. def updateSerialStatus(request_dict, response):
  615. """
  616. 更新序列号状态
  617. @param request_dict: 请求参数
  618. @request_dict serial_redis_list: 序列号redis列表
  619. @request_dict status: 状态, 1: 未使用, 3: 已占用
  620. @param response: 响应对象
  621. """
  622. serial_redis_list = request_dict.get('serial_redis_list', None)
  623. status = request_dict.get('status', None)
  624. LOGGER.info('---更新序列号状态参数---serial_redis_list:{},status:{}'.format(serial_redis_list, status))
  625. if not all([serial_redis_list, status]):
  626. return response.json(444)
  627. now_time = int(time.time())
  628. try:
  629. serial_redis_list = eval(serial_redis_list)
  630. CompanySerialModel.objects.filter(serial_number__in=serial_redis_list).update(status=int(status),
  631. update_time=now_time)
  632. uid_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number__in=serial_redis_list)
  633. if uid_serial_qs:
  634. uid_list = list(uid_serial_qs.values_list('uid__uid', flat=True))
  635. serial_list = list(uid_serial_qs.values_list('company_serial__serial_number', flat=True))
  636. UIDModel.objects.filter(uid__in=uid_list).update(status=3, mac='', update_time=now_time)
  637. uid_serial_qs.delete()
  638. # 记录操作日志
  639. content = json.loads(json.dumps(request_dict))
  640. log = {
  641. 'ip': '127.0.0.1',
  642. 'user_id': 1,
  643. 'status': 200,
  644. 'time': now_time,
  645. 'content': json.dumps(content),
  646. 'url': 'cron/update/updateSerialStatus',
  647. 'operation': '序列号{}解绑uid: {}'.format(serial_list, uid_list),
  648. }
  649. LogModel.objects.create(**log)
  650. return response.json(0)
  651. except Exception as e:
  652. LOGGER.info('---更新序列号状态异常---:{}'.format(repr(e)))
  653. return response.json(500)
  654. @staticmethod
  655. def reset_region_id(request_dict, response):
  656. """
  657. 重置地区id
  658. @param request_dict: 请求参数
  659. @request_dict serial_redis_list: 序列号redis列表
  660. @param response: 响应对象
  661. """
  662. serial_redis_list = request_dict.get('serial_redis_list', None)
  663. LOGGER.info('---重置地区id参数---serial_redis_list:{}'.format(serial_redis_list))
  664. if not serial_redis_list:
  665. return response.json(444)
  666. try:
  667. serial_redis_list = eval(serial_redis_list)
  668. DeviceDomainRegionModel.objects.filter(serial_number__in=serial_redis_list).update(region_id=0)
  669. return response.json(0)
  670. except Exception as e:
  671. LOGGER.info('---重置地区id异常---:{}'.format(repr(e)))
  672. return response.json(500)
  673. @staticmethod
  674. def update_vod_meal(request_dict, response):
  675. """
  676. 定时修改体验套餐有效期为1个月
  677. @param request_dict: 请求参数
  678. @param response: 响应对象
  679. """
  680. try:
  681. Store_Meal.objects.filter(is_show=0, expire=12, pixel_level=0).update(price='39.99',
  682. virtual_price='56.6',
  683. sort=1)
  684. Store_Meal.objects.filter(is_show=0, cycle_config_id=1, pixel_level=0).update(price='3.65',
  685. virtual_price='5.66',
  686. sort=2)
  687. Store_Meal.objects.filter(id=12).update(price='3.99', virtual_price='5.66', sort=3)
  688. Store_Meal.objects.filter(id__in=(16, 17, 18)).update(is_show=0)
  689. return response.json(0)
  690. except Exception as e:
  691. LOGGER.info('---修改云存套餐内容异常---:{}'.format(repr(e)))
  692. return response.json(500)
  693. @staticmethod
  694. def check_customized_push(response):
  695. try:
  696. now_time = int(time.time())
  697. # 查询推送时间小于当前时间且推送状态为待推送的数据
  698. customized_push_qs = CustomizedPush.objects.filter(push_timestamp__lt=now_time, push_satus=0).values('id')
  699. if customized_push_qs.exists():
  700. for customized_push in customized_push_qs:
  701. customized_push_id = customized_push['id']
  702. data = {'customized_push_id': customized_push_id}
  703. url = DETECT_PUSH_DOMAINS + 'customized_push/start'
  704. req = requests.post(url=url, data=data, timeout=8)
  705. return response.json(0)
  706. except Exception as e:
  707. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  708. class CronCollectDataView(View):
  709. def get(self, request, *args, **kwargs):
  710. request.encoding = 'utf-8'
  711. operation = kwargs.get('operation')
  712. return self.validation(request.GET, request, operation)
  713. def post(self, request, *args, **kwargs):
  714. request.encoding = 'utf-8'
  715. operation = kwargs.get('operation')
  716. return self.validation(request.POST, request, operation)
  717. def validation(self, request_dict, request, operation):
  718. response = ResponseObject()
  719. if operation == 'collectPlayBack': # 定时保存云存视频回放
  720. return self.collect_play_back(response)
  721. elif operation == 'collectDeviceUser': # 定时保存用户数据
  722. return self.collect_device_user(response)
  723. elif operation == 'collectOrder': # 定时保存订单数据
  724. return self.collect_order(response)
  725. elif operation == 'collectIcloudOrder': # 定时保存云盘订单数据
  726. return self.collect_icloud_order(response)
  727. elif operation == 'collectDeviceInfo': # 定时保存设备数据
  728. return self.collect_device_info(response)
  729. elif operation == 'collectFlowInfo': # 定时保存设备数据
  730. return self.collect_flow_info(response)
  731. else:
  732. return response.json(404)
  733. @staticmethod
  734. def collect_play_back(response):
  735. try:
  736. now_time = int(time.time())
  737. today = datetime.datetime.today()
  738. start_time = datetime.datetime(today.year, today.month, today.day)
  739. end_time = start_time + datetime.timedelta(days=1)
  740. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  741. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  742. this_month_str = datetime.datetime(today.year, today.month, 1)
  743. this_month_stamp = CommonService.str_to_timestamp(this_month_str.strftime('%Y-%m-%d %H:%M:%S'))
  744. video_play_back_time_qs = VideoPlaybackTimeModel.objects.filter(startTime__gte=start_time,
  745. startTime__lt=end_time,
  746. playMode='cloud').values('uid').annotate(
  747. play_duration=Sum('duration'), play_frequency=Count('uid'))
  748. with transaction.atomic():
  749. for item in video_play_back_time_qs:
  750. vod_hls_summary_qs = VodHlsSummary.objects.filter(uid=item['uid'], time=this_month_stamp)
  751. if vod_hls_summary_qs.exists():
  752. vod_hls_summary = vod_hls_summary_qs.first()
  753. vod_hls_summary.play_duration += item['play_duration']
  754. vod_hls_summary.play_frequency += 1
  755. vod_hls_summary.updated_time = now_time
  756. vod_hls_summary.save()
  757. else:
  758. VodHlsSummary.objects.create(uid=item['uid'], time=this_month_stamp, created_time=now_time,
  759. play_duration=item['play_duration'], play_frequency=1,
  760. updated_time=now_time)
  761. return response.json(0)
  762. except Exception as e:
  763. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  764. @staticmethod
  765. def collect_device_user(response):
  766. try:
  767. created_time = int(time.time())
  768. today = datetime.datetime.today()
  769. start_time = datetime.datetime(today.year, today.month, today.day)
  770. end_time = start_time + datetime.timedelta(days=1)
  771. increase_user_qs = Device_User.objects.filter(data_joined__year=today.year, data_joined__month=today.month,
  772. data_joined__day=today.day).values('region_country')
  773. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  774. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  775. active_user_qs = UserExModel.objects.filter(updTime__gte=start_time, updTime__lt=end_time).values(
  776. 'userID__region_country')
  777. country_qs = CountryModel.objects.all().values('id', 'region__name', 'country_name')
  778. country_dict = {}
  779. continent_dict = {}
  780. for item in country_qs:
  781. country_dict[item['id']] = item['country_name']
  782. continent_dict[item['country_name']] = item['region__name']
  783. with transaction.atomic():
  784. if increase_user_qs.exists():
  785. increase_user_count = increase_user_qs.count()
  786. increase_user_country_list = increase_user_qs.values('region_country').annotate(
  787. count=Count('region_country')).order_by('count')
  788. increase_user_country_dict = {}
  789. increase_user_continent_dict = {}
  790. for item in increase_user_country_list:
  791. country_name = country_dict.get(item['region_country'], '未知国家')
  792. continent_name = continent_dict.get(country_name, '未知大洲')
  793. increase_user_country_dict[country_name] = item['count']
  794. if continent_name not in increase_user_continent_dict:
  795. increase_user_continent_dict[continent_name] = 0
  796. increase_user_continent_dict[continent_name] += item['count']
  797. DeviceUserSummary.objects.create(time=start_time, count=increase_user_count,
  798. country=increase_user_country_dict, created_time=created_time,
  799. continent=increase_user_continent_dict)
  800. if active_user_qs.exists():
  801. active_user_count = active_user_qs.count()
  802. active_user_country_list = active_user_qs.values('userID__region_country').annotate(
  803. count=Count('userID__region_country')).order_by('count')
  804. active_user_country_dict = {}
  805. active_user_continent_dict = {}
  806. for item in active_user_country_list:
  807. country_name = country_dict.get(item['userID__region_country'], '未知国家')
  808. continent_name = continent_dict.get(country_name, '未知大洲')
  809. active_user_country_dict[country_name] = item['count']
  810. if continent_name not in active_user_continent_dict:
  811. active_user_continent_dict[continent_name] = 0
  812. active_user_continent_dict[continent_name] += item['count']
  813. DeviceUserSummary.objects.create(time=start_time, query_type=1, count=active_user_count,
  814. country=active_user_country_dict, created_time=created_time,
  815. continent=active_user_continent_dict)
  816. return response.json(0)
  817. except Exception as e:
  818. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  819. @staticmethod
  820. def collect_order(response):
  821. try:
  822. created_time = int(time.time())
  823. today = datetime.datetime.today()
  824. start_time = datetime.datetime(today.year, today.month, today.day)
  825. end_time = start_time + datetime.timedelta(days=1)
  826. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  827. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  828. order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time,
  829. status=1).values('UID', 'order_type',
  830. 'store_meal_name', 'price',
  831. 'addTime', 'currency').order_by(
  832. 'addTime')
  833. uid_list = []
  834. all_order_qs = Order_Model.objects.filter(addTime__lt=start_time, status=1).values('UID')
  835. for item in all_order_qs:
  836. if item['UID'] not in uid_list:
  837. uid_list.append(item['UID'])
  838. # 国家表数据
  839. country_qs = CountryModel.objects.values('id', 'country_name')
  840. country_dict = {}
  841. for item in country_qs:
  842. country_dict[item['id']] = item['country_name']
  843. # 设备类型数据
  844. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  845. device_type_dict = {}
  846. for item in device_type_qs:
  847. device_type_dict[item['type']] = item['name']
  848. with transaction.atomic():
  849. for item in order_qs:
  850. is_pay = 0
  851. price = float(item['price'])
  852. currency = item['currency']
  853. uid_set_qs = UidSetModel.objects.filter(uid=item['UID']).values('tb_country')
  854. country_id = uid_set_qs[0]['tb_country'] if uid_set_qs.exists() else 0
  855. country_name = country_dict.get(country_id, '未知国家')
  856. order_type = item['order_type']
  857. if order_type == '4' or order_type == 4:
  858. continue
  859. device_info_qs = Device_Info.objects.filter(UID=item['UID']).values('Type')
  860. device_type_id = device_info_qs[0]['Type'] if device_info_qs.exists() else 0
  861. device_type_name = device_type_dict.get(device_type_id, '未知设备')
  862. store_meal_name = item['store_meal_name']
  863. add_time_stamp = item['addTime']
  864. add_time_str = datetime.datetime.fromtimestamp(int(add_time_stamp))
  865. add_time_str = datetime.datetime(add_time_str.year, add_time_str.month, add_time_str.day)
  866. add_time_stamp = CommonService.str_to_timestamp(add_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  867. if price == 0:
  868. is_pay = 1
  869. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=1,
  870. service_type=order_type)
  871. else:
  872. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=0,
  873. service_type=order_type)
  874. if item['UID'] not in uid_list:
  875. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=2,
  876. service_type=order_type)
  877. query_type = 2
  878. else:
  879. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=3,
  880. service_type=order_type)
  881. query_type = 3
  882. if pay_order_summary_qs.exists():
  883. pay_order_summary = pay_order_summary_qs.first()
  884. pay_order_summary.count += 1
  885. temp_total = eval(pay_order_summary.total)
  886. if currency not in temp_total:
  887. temp_total[currency] = price
  888. else:
  889. temp_total[currency] = round(temp_total[currency] + price, 2)
  890. pay_order_summary.total = temp_total
  891. country_temp_dict = eval(pay_order_summary.country)
  892. if country_name in country_temp_dict:
  893. country_temp_dict[country_name]['数量'] += 1
  894. if currency not in country_temp_dict[country_name]:
  895. country_temp_dict[country_name][currency] = price
  896. else:
  897. country_temp_dict[country_name][currency] = round(
  898. country_temp_dict[country_name][currency] + price, 2)
  899. else:
  900. country_temp_dict[country_name] = {'数量': 1, currency: price}
  901. pay_order_summary.country = country_temp_dict
  902. device_type_temp_dict = eval(pay_order_summary.device_type)
  903. if device_type_name in device_type_temp_dict:
  904. device_type_temp_dict[device_type_name]['数量'] += 1
  905. if currency not in device_type_temp_dict[device_type_name]:
  906. device_type_temp_dict[device_type_name][currency] = price
  907. else:
  908. device_type_temp_dict[device_type_name][currency] = round(
  909. device_type_temp_dict[device_type_name][currency] + price, 2)
  910. else:
  911. device_type_temp_dict[device_type_name] = {'数量': 1, currency: price}
  912. pay_order_summary.device_type = device_type_temp_dict
  913. store_meal_temp_dict = eval(pay_order_summary.store_meal)
  914. if store_meal_name in store_meal_temp_dict:
  915. store_meal_temp_dict[store_meal_name]['数量'] += 1
  916. if currency not in store_meal_temp_dict[store_meal_name]:
  917. store_meal_temp_dict[store_meal_name][currency] = price
  918. else:
  919. store_meal_temp_dict[store_meal_name][currency] = round(
  920. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  921. else:
  922. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  923. pay_order_summary.store_meal = store_meal_temp_dict
  924. pay_order_summary.save()
  925. else:
  926. final_total = {currency: price}
  927. country_temp_dict = {
  928. country_name: {
  929. '数量': 1,
  930. currency: price
  931. }
  932. }
  933. device_type_temp_dict = {
  934. device_type_name: {
  935. '数量': 1,
  936. currency: price
  937. }
  938. }
  939. store_meal_temp_dict = {
  940. store_meal_name: {
  941. '数量': 1,
  942. currency: price
  943. }
  944. }
  945. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=query_type,
  946. service_type=order_type, total=final_total,
  947. country=country_temp_dict, created_time=created_time,
  948. device_type=device_type_temp_dict,
  949. store_meal=store_meal_temp_dict)
  950. if order_summary_qs.exists():
  951. order_summary = order_summary_qs.first()
  952. order_summary.count += 1
  953. temp_total = eval(order_summary.total)
  954. if currency not in temp_total:
  955. temp_total[currency] = price
  956. else:
  957. temp_total[currency] = round(temp_total[currency] + price, 2)
  958. order_summary.total = temp_total
  959. country_temp_dict = eval(order_summary.country)
  960. if country_name in country_temp_dict:
  961. if is_pay == 0:
  962. country_temp_dict[country_name]['数量'] += 1
  963. if currency not in country_temp_dict[country_name]:
  964. country_temp_dict[country_name][currency] = price
  965. else:
  966. country_temp_dict[country_name][currency] = round(
  967. country_temp_dict[country_name][currency] + price, 2)
  968. else:
  969. country_temp_dict[country_name] += 1
  970. else:
  971. if is_pay == 0:
  972. country_temp_dict[country_name] = {'数量': 1, currency: price}
  973. else:
  974. country_temp_dict[country_name] = 1
  975. order_summary.country = country_temp_dict
  976. device_type_temp_dict = eval(order_summary.device_type)
  977. if device_type_name in device_type_temp_dict:
  978. if is_pay == 0:
  979. device_type_temp_dict[device_type_name]['数量'] += 1
  980. if currency not in device_type_temp_dict[device_type_name]:
  981. device_type_temp_dict[device_type_name][currency] = price
  982. else:
  983. device_type_temp_dict[device_type_name][currency] = round(
  984. device_type_temp_dict[device_type_name][currency] + price, 2)
  985. else:
  986. device_type_temp_dict[device_type_name] += 1
  987. else:
  988. if is_pay == 0:
  989. device_type_temp_dict[device_type_name] = {'数量': 1, currency: price}
  990. else:
  991. device_type_temp_dict[device_type_name] = 1
  992. order_summary.device_type = device_type_temp_dict
  993. store_meal_temp_dict = eval(order_summary.store_meal)
  994. if store_meal_name in store_meal_temp_dict:
  995. if is_pay == 0:
  996. store_meal_temp_dict[store_meal_name]['数量'] += 1
  997. if currency not in store_meal_temp_dict[store_meal_name]:
  998. store_meal_temp_dict[store_meal_name][currency] = price
  999. else:
  1000. store_meal_temp_dict[store_meal_name][currency] = round(
  1001. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1002. else:
  1003. store_meal_temp_dict[store_meal_name] += 1
  1004. else:
  1005. if is_pay == 0:
  1006. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1007. else:
  1008. store_meal_temp_dict[store_meal_name] = 1
  1009. order_summary.store_meal = store_meal_temp_dict
  1010. order_summary.save()
  1011. else:
  1012. final_total = {currency: price}
  1013. if is_pay == 0:
  1014. country_temp_dict = {
  1015. country_name: {
  1016. '数量': 1,
  1017. currency: price
  1018. }
  1019. }
  1020. device_type_temp_dict = {
  1021. device_type_name: {
  1022. '数量': 1,
  1023. currency: price
  1024. }
  1025. }
  1026. store_meal_temp_dict = {
  1027. store_meal_name: {
  1028. '数量': 1,
  1029. currency: price
  1030. }
  1031. }
  1032. else:
  1033. device_type_temp_dict = {
  1034. device_type_name: 1
  1035. }
  1036. store_meal_temp_dict = {
  1037. store_meal_name: 1
  1038. }
  1039. country_temp_dict = {
  1040. country_name: 1
  1041. }
  1042. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=is_pay,
  1043. service_type=order_type, total=final_total,
  1044. country=country_temp_dict, created_time=created_time,
  1045. device_type=device_type_temp_dict, store_meal=store_meal_temp_dict)
  1046. return response.json(0)
  1047. except Exception as e:
  1048. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1049. @staticmethod
  1050. def collect_icloud_order(response):
  1051. try:
  1052. order_type = 4
  1053. created_time = int(time.time())
  1054. today = datetime.datetime.today()
  1055. start_time = datetime.datetime(today.year, today.month, today.day)
  1056. end_time = start_time + datetime.timedelta(days=1)
  1057. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1058. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1059. order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time, order_type=order_type,
  1060. status=1).values('userID',
  1061. 'store_meal_name', 'price',
  1062. 'addTime', 'currency').order_by(
  1063. 'addTime')
  1064. user_list = []
  1065. all_order_qs = Order_Model.objects.filter(addTime__lt=start_time, status=1, order_type=order_type).values(
  1066. 'userID')
  1067. for item in all_order_qs:
  1068. if item['userID'] not in user_list:
  1069. user_list.append(item['userID'])
  1070. # 国家表数据
  1071. country_qs = CountryModel.objects.values('id', 'country_name')
  1072. country_dict = {}
  1073. for item in country_qs:
  1074. country_dict[item['id']] = item['country_name']
  1075. with transaction.atomic():
  1076. for item in order_qs:
  1077. price = float(item['price'])
  1078. currency = item['currency']
  1079. user_qs = Device_User.objects.filter(userID=item['userID']).values('region_country')
  1080. country_id = user_qs[0]['region_country'] if user_qs.exists() else 0
  1081. country_name = country_dict.get(country_id, '未知国家')
  1082. store_meal_name = item['store_meal_name']
  1083. add_time_stamp = item['addTime']
  1084. add_time_str = datetime.datetime.fromtimestamp(int(add_time_stamp))
  1085. add_time_str = datetime.datetime(add_time_str.year, add_time_str.month, add_time_str.day)
  1086. add_time_stamp = CommonService.str_to_timestamp(add_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  1087. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=0,
  1088. service_type=order_type)
  1089. if item['userID'] not in user_list:
  1090. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=2,
  1091. service_type=order_type)
  1092. query_type = 2
  1093. else:
  1094. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=3,
  1095. service_type=order_type)
  1096. query_type = 3
  1097. if pay_order_summary_qs.exists():
  1098. pay_order_summary = pay_order_summary_qs.first()
  1099. pay_order_summary.count += 1
  1100. temp_total = eval(pay_order_summary.total)
  1101. if currency not in temp_total:
  1102. temp_total[currency] = price
  1103. else:
  1104. temp_total[currency] = round(temp_total[currency] + price, 2)
  1105. pay_order_summary.total = temp_total
  1106. country_temp_dict = eval(pay_order_summary.country)
  1107. if country_name in country_temp_dict:
  1108. country_temp_dict[country_name]['数量'] += 1
  1109. if currency not in country_temp_dict[country_name]:
  1110. country_temp_dict[country_name][currency] = price
  1111. else:
  1112. country_temp_dict[country_name][currency] = round(
  1113. country_temp_dict[country_name][currency] + price, 2)
  1114. else:
  1115. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1116. pay_order_summary.country = country_temp_dict
  1117. store_meal_temp_dict = eval(pay_order_summary.store_meal)
  1118. if store_meal_name in store_meal_temp_dict:
  1119. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1120. if currency not in store_meal_temp_dict[store_meal_name]:
  1121. store_meal_temp_dict[store_meal_name][currency] = price
  1122. else:
  1123. store_meal_temp_dict[store_meal_name][currency] = round(
  1124. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1125. else:
  1126. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1127. pay_order_summary.store_meal = store_meal_temp_dict
  1128. pay_order_summary.save()
  1129. else:
  1130. final_total = {currency: price}
  1131. country_temp_dict = {
  1132. country_name: {
  1133. '数量': 1,
  1134. currency: price
  1135. }
  1136. }
  1137. store_meal_temp_dict = {
  1138. store_meal_name: {
  1139. '数量': 1,
  1140. currency: price
  1141. }
  1142. }
  1143. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=query_type,
  1144. service_type=order_type, total=final_total,
  1145. country=country_temp_dict, created_time=created_time,
  1146. device_type={},
  1147. store_meal=store_meal_temp_dict)
  1148. if order_summary_qs.exists():
  1149. order_summary = order_summary_qs.first()
  1150. order_summary.count += 1
  1151. temp_total = eval(order_summary.total)
  1152. if currency not in temp_total:
  1153. temp_total[currency] = price
  1154. else:
  1155. temp_total[currency] = round(temp_total[currency] + price, 2)
  1156. order_summary.total = temp_total
  1157. country_temp_dict = eval(order_summary.country)
  1158. if country_name in country_temp_dict:
  1159. country_temp_dict[country_name]['数量'] += 1
  1160. if currency not in country_temp_dict[country_name]:
  1161. country_temp_dict[country_name][currency] = price
  1162. else:
  1163. country_temp_dict[country_name][currency] = round(
  1164. country_temp_dict[country_name][currency] + price, 2)
  1165. else:
  1166. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1167. order_summary.country = country_temp_dict
  1168. store_meal_temp_dict = eval(order_summary.store_meal)
  1169. if store_meal_name in store_meal_temp_dict:
  1170. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1171. if currency not in store_meal_temp_dict[store_meal_name]:
  1172. store_meal_temp_dict[store_meal_name][currency] = price
  1173. else:
  1174. store_meal_temp_dict[store_meal_name][currency] = round(
  1175. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1176. else:
  1177. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1178. order_summary.store_meal = store_meal_temp_dict
  1179. order_summary.save()
  1180. else:
  1181. final_total = {currency: price}
  1182. country_temp_dict = {
  1183. country_name: {
  1184. '数量': 1,
  1185. currency: price
  1186. }
  1187. }
  1188. store_meal_temp_dict = {
  1189. store_meal_name: {
  1190. '数量': 1,
  1191. currency: price
  1192. }
  1193. }
  1194. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=0,
  1195. service_type=order_type, total=final_total,
  1196. country=country_temp_dict, created_time=created_time,
  1197. device_type={}, store_meal=store_meal_temp_dict)
  1198. return response.json(0)
  1199. except Exception as e:
  1200. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1201. @staticmethod
  1202. def collect_device_info(response):
  1203. try:
  1204. created_time = int(time.time())
  1205. today = datetime.datetime.today()
  1206. start_time = datetime.datetime(today.year, today.month, today.day)
  1207. end_time = start_time + datetime.timedelta(days=1)
  1208. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1209. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1210. increase_device_qs = UidSetModel.objects.filter(addTime__gte=start_time, addTime__lt=end_time).values(
  1211. 'tb_country',
  1212. 'uid',
  1213. 'device_type',
  1214. 'cloud_vod',
  1215. 'is_ai',
  1216. 'mobile_4g',
  1217. 'addTime')
  1218. video_play_back_time_qs = VideoPlaybackTimeModel.objects.filter(startTime__gte=start_time,
  1219. startTime__lt=end_time).values('uid')
  1220. active_device_qs = UidSetModel.objects.filter(uid__in=video_play_back_time_qs).values('tb_country',
  1221. 'addTime',
  1222. 'device_type',
  1223. 'cloud_vod',
  1224. 'is_ai',
  1225. 'mobile_4g',
  1226. 'uid')
  1227. increase_device_count = increase_device_qs.count()
  1228. active_device_count = active_device_qs.count()
  1229. # 国家表数据
  1230. country_qs = CountryModel.objects.values('id', 'country_name', 'region__name')
  1231. country_dict = {}
  1232. continent_dict = {}
  1233. for item in country_qs:
  1234. country_dict[item['id']] = item['country_name']
  1235. continent_dict[item['country_name']] = item['region__name']
  1236. # 设备类型数据
  1237. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  1238. device_type_dict = {}
  1239. for item in device_type_qs:
  1240. device_type_dict[item['type']] = item['name']
  1241. with transaction.atomic():
  1242. if increase_device_qs.exists():
  1243. # 国家大洲设备数据
  1244. increase_device_country_list = increase_device_qs.values('tb_country').annotate(
  1245. count=Count('tb_country')).order_by('count')
  1246. increase_device_country_dict = {}
  1247. increase_device_continent_dict = {}
  1248. for item in increase_device_country_list:
  1249. country_name = country_dict.get(item['tb_country'], '未知国家')
  1250. continent_name = continent_dict.get(country_name, '未知大洲')
  1251. increase_device_country_dict[country_name] = item['count']
  1252. if continent_name not in increase_device_continent_dict:
  1253. increase_device_continent_dict[continent_name] = 0
  1254. increase_device_continent_dict[continent_name] += item['count']
  1255. # 设备类型数据
  1256. increase_device_type_list = increase_device_qs.values('device_type').annotate(
  1257. count=Count('device_type')).order_by('count')
  1258. increase_device_type_dict = {}
  1259. for item in increase_device_type_list:
  1260. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1261. increase_device_type_dict[type_name] = item['count']
  1262. # 云存设备类型数据
  1263. increase_device_vod_list = increase_device_qs.filter(~Q(cloud_vod=2)).values(
  1264. 'device_type').annotate(
  1265. count=Count('device_type')).order_by('count')
  1266. increase_device_vod_dict = {}
  1267. for item in increase_device_vod_list:
  1268. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1269. increase_device_vod_dict[type_name] = item['count']
  1270. # AI设备类型数据
  1271. increase_device_ai_list = increase_device_qs.filter(~Q(is_ai=2)).values('device_type').annotate(
  1272. count=Count('device_type')).order_by('count')
  1273. increase_device_ai_dict = {}
  1274. for item in increase_device_ai_list:
  1275. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1276. increase_device_ai_dict[type_name] = item['count']
  1277. # 联通设备类型数据
  1278. increase_device_unicom_list = increase_device_qs.filter(~Q(mobile_4g=2)).values(
  1279. 'device_type').annotate(
  1280. count=Count('device_type')).order_by('count')
  1281. increase_device_unicom_dict = {}
  1282. for item in increase_device_unicom_list:
  1283. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1284. increase_device_unicom_dict[type_name] = item['count']
  1285. DeviceInfoSummary.objects.create(time=start_time, count=increase_device_count,
  1286. query_type=0, created_time=created_time,
  1287. country=increase_device_country_dict,
  1288. continent=increase_device_continent_dict,
  1289. vod_service=increase_device_vod_dict,
  1290. ai_service=increase_device_ai_dict,
  1291. unicom_service=increase_device_unicom_dict,
  1292. device_type=increase_device_type_dict)
  1293. if active_device_qs.exists():
  1294. # 国家大洲设备数据
  1295. active_device_country_list = active_device_qs.values('tb_country').annotate(
  1296. count=Count('tb_country')).order_by('count')
  1297. active_device_country_dict = {}
  1298. active_device_continent_dict = {}
  1299. for item in active_device_country_list:
  1300. country_name = country_dict.get(item['tb_country'], '未知国家')
  1301. continent_name = continent_dict.get(country_name, '未知大洲')
  1302. active_device_country_dict[country_name] = item['count']
  1303. if continent_name not in active_device_continent_dict:
  1304. active_device_continent_dict[continent_name] = 0
  1305. active_device_continent_dict[continent_name] += item['count']
  1306. # 设备类型数据
  1307. active_device_type_list = active_device_qs.values('device_type').annotate(
  1308. count=Count('device_type')).order_by('count')
  1309. active_device_type_dict = {}
  1310. for item in active_device_type_list:
  1311. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1312. active_device_type_dict[type_name] = item['count']
  1313. # 云存设备类型数据
  1314. active_device_vod_list = active_device_qs.filter(~Q(cloud_vod=2)).values('device_type').annotate(
  1315. count=Count('device_type')).order_by('count')
  1316. active_device_vod_dict = {}
  1317. for item in active_device_vod_list:
  1318. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1319. active_device_vod_dict[type_name] = item['count']
  1320. # AI设备类型数据
  1321. active_device_ai_list = active_device_qs.filter(~Q(is_ai=2)).values('device_type').annotate(
  1322. count=Count('device_type')).order_by('count')
  1323. active_device_ai_dict = {}
  1324. for item in active_device_ai_list:
  1325. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1326. active_device_ai_dict[type_name] = item['count']
  1327. # 联通设备类型数据
  1328. active_device_unicom_list = active_device_qs.filter(~Q(mobile_4g=2)).values('device_type').annotate(
  1329. count=Count('device_type')).order_by('count')
  1330. active_device_unicom_dict = {}
  1331. for item in active_device_unicom_list:
  1332. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1333. active_device_unicom_dict[type_name] = item['count']
  1334. DeviceInfoSummary.objects.create(time=start_time, count=active_device_count,
  1335. query_type=1, created_time=created_time,
  1336. country=active_device_country_dict,
  1337. continent=active_device_continent_dict,
  1338. vod_service=active_device_vod_dict,
  1339. ai_service=active_device_ai_dict,
  1340. unicom_service=active_device_unicom_dict,
  1341. device_type=active_device_type_dict)
  1342. return response.json(0)
  1343. except Exception as e:
  1344. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1345. @staticmethod
  1346. def collect_flow_info(response):
  1347. try:
  1348. unicom_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('iccid').distinct().order_by('iccid')
  1349. asy = threading.Thread(target=CronCollectDataView.thread_collect_flow, args=(unicom_qs,))
  1350. asy.start()
  1351. return response.json(0)
  1352. except Exception as e:
  1353. return response.json(500, repr(e))
  1354. @staticmethod
  1355. def thread_collect_flow(qs):
  1356. try:
  1357. unicom_api = UnicomObjeect()
  1358. redis_obj = RedisObject()
  1359. for item in qs:
  1360. res = unicom_api.query_device_usage_history(**item)
  1361. if res.status_code == 200:
  1362. res_json = res.json()
  1363. if res_json['code'] == 0:
  1364. redis_dict = {}
  1365. for data in res_json['data']['deviceUsageHistory']:
  1366. year = data.get('year', None)
  1367. month = data.get('month', None)
  1368. flow = data.get('flowTotalUsage', None)
  1369. if not all([year, month, flow]):
  1370. continue
  1371. file = str(year) + '-' + str(month)
  1372. redis_dict[file] = flow
  1373. key = 'monthly_flow_' + item['iccid']
  1374. if redis_dict:
  1375. redis_obj.set_hash_data(key, redis_dict)
  1376. except Exception as e:
  1377. LOGGER.info('统计联通流量失败,时间为:{}'.format(int(time.time())))
  1378. class CronComparedDataView(View):
  1379. def get(self, request, *args, **kwargs):
  1380. request.encoding = 'utf-8'
  1381. operation = kwargs.get('operation')
  1382. return self.validation(request.GET, request, operation)
  1383. def post(self, request, *args, **kwargs):
  1384. request.encoding = 'utf-8'
  1385. operation = kwargs.get('operation')
  1386. return self.validation(request.POST, request, operation)
  1387. def validation(self, request_dict, request, operation):
  1388. response = ResponseObject()
  1389. if operation == 'PaypalOrder': # 定时对比paypal订单
  1390. return self.compared_paypal_order(request_dict, response)
  1391. elif operation == 'WechatOrder': # 定时对比微信订单
  1392. return self.compared_wechat_order(response)
  1393. elif operation == 'AlipayOrder': # 定时对比阿里订单
  1394. return self.compared_alipay_order(response)
  1395. elif operation == 'AnsjerOrder': # 定时对比后台订单
  1396. return self.compared_ansjer_order(request_dict, response)
  1397. else:
  1398. return response.json(404)
  1399. @staticmethod
  1400. def compared_paypal_order(request_dict, response):
  1401. time_stamp = request_dict.get('time', None)
  1402. if time_stamp:
  1403. end_date = datetime.datetime.fromtimestamp(int(time_stamp))
  1404. start_date = end_date - datetime.timedelta(days=1)
  1405. else:
  1406. today = datetime.datetime.today()
  1407. start_date = today - datetime.timedelta(days=2)
  1408. end_date = start_date + datetime.timedelta(days=1)
  1409. try:
  1410. data = (
  1411. ('start_date', '{}-{}-{}T08:00:00-0800'.format(start_date.year, start_date.month, start_date.day)),
  1412. ('end_date', '{}-{}-{}T08:00:00-0800'.format(end_date.year, end_date.month, end_date.day)),
  1413. ('fields', 'all'),
  1414. ('page_size', '500'),
  1415. ('page', '1'),
  1416. ('transaction_status', 'S')
  1417. )
  1418. order_list = PayPalService(PAYPAL_CRD['client_id'], PAYPAL_CRD['client_secret']).get_transactions(data)
  1419. thread = threading.Thread(target=CronComparedDataView.thread_compared_paypal_order,
  1420. args=(order_list['transaction_details'], end_date), daemon=True)
  1421. thread.start()
  1422. return response.json(0)
  1423. except Exception as e:
  1424. LOGGER.info('CronComparedDataView.compared_paypal_order, errLine:{}, errMsg:{}'.format(
  1425. e.__traceback__.tb_lineno, repr(e)))
  1426. return response.json(500)
  1427. @staticmethod
  1428. def thread_compared_paypal_order(order_list, start_time):
  1429. now_time = int(time.time())
  1430. timestamp = int(start_time.timestamp())
  1431. count = len(order_list)
  1432. total = 0
  1433. more_order_list = []
  1434. for item in order_list:
  1435. total += float(item['transaction_info']['transaction_amount']['value'])
  1436. trade_no = item['transaction_info']['transaction_id']
  1437. if item['transaction_info']['transaction_event_code'] in ['T1106', 'T1107']: # 付款退款
  1438. trade_no = item['transaction_info']['paypal_reference_id']
  1439. transaction_subject = item['transaction_info'].get('transaction_subject', '')
  1440. agreement_id = item['transaction_info'].get('paypal_reference_id', '')
  1441. refund_order = False
  1442. if item['transaction_info']['transaction_event_code'] in ['T1106', 'T1107', 'T1201', 'T0114']:
  1443. agreement_id = ''
  1444. if item['transaction_info']['transaction_event_code'] in ['T0114']:
  1445. transaction_subject = '争议费'
  1446. else:
  1447. refund_order = True
  1448. transaction_subject = '退款费'
  1449. more_order_list.append(trade_no)
  1450. pay_time = int(datetime.datetime.strptime(item['transaction_info']['transaction_updated_date'],
  1451. "%Y-%m-%dT%H:%M:%S%z").timestamp())
  1452. order_qs = Order_Model.objects.filter(trade_no=trade_no, payType=1)
  1453. if not order_qs.exists():
  1454. order_dict = {
  1455. 'trade_no': trade_no,
  1456. 'agreement_id': agreement_id,
  1457. 'pay_time': pay_time,
  1458. 'username': item['payer_info'].get('email_address', ''),
  1459. 'price': item['transaction_info']['transaction_amount']['value'],
  1460. 'pay_type': 1,
  1461. 'upd_time': now_time,
  1462. 'status': 0,
  1463. 'meal_name': transaction_subject
  1464. }
  1465. if agreement_id:
  1466. order_dict['pay_type'] = 0
  1467. order_dict['meal_name'] = 'paypal_cycle'
  1468. order_dict['order_id'] = transaction_subject
  1469. params = {'trade_no': trade_no, 'pay_time': pay_time, 'refund_order': refund_order}
  1470. response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
  1471. if response.status_code != 200:
  1472. # 如果响应失败,记录在数据库
  1473. AbnormalOrder.objects.create(**order_dict)
  1474. continue
  1475. result = response.json()
  1476. if result['result_code'] != 0 or not result['result']['is_exist']:
  1477. # 如果响应结果为空,记录在数据库
  1478. AbnormalOrder.objects.create(**order_dict)
  1479. else:
  1480. if not refund_order:
  1481. order_qs.update(payTime=pay_time)
  1482. total = round(total, 2)
  1483. daily_reconciliation = DailyReconciliation.objects.filter(time=timestamp)
  1484. if daily_reconciliation.exists():
  1485. if daily_reconciliation.first().order_ids:
  1486. more_order_list = daily_reconciliation.first().order_ids.split(',') + more_order_list
  1487. order_ids = ','.join(more_order_list)
  1488. daily_reconciliation.update(paypal_num=count, paypal_total=total, upd_time=now_time, order_ids=order_ids)
  1489. else:
  1490. order_ids = ','.join(more_order_list)
  1491. DailyReconciliation.objects.create(paypal_num=count, paypal_total=total, time=timestamp,
  1492. order_ids=order_ids, creat_time=now_time, upd_time=now_time)
  1493. @staticmethod
  1494. def compared_wechat_order(response):
  1495. today = datetime.datetime.today()
  1496. start_date = today - datetime.timedelta(days=1)
  1497. start_date = start_date.strftime("%Y%m%d")
  1498. try:
  1499. order_list = WechatPayObject().download_bill(start_date)
  1500. thread = threading.Thread(target=CronComparedDataView.thread_compared_wechat_order,
  1501. args=(order_list,), daemon=True)
  1502. thread.start()
  1503. return response.json(0)
  1504. except Exception as e:
  1505. LOGGER.info('CronComparedDataView.compared_wechat_order, errLine:{}, errMsg:{}'.format(
  1506. e.__traceback__.tb_lineno, repr(e)))
  1507. return response.json(500)
  1508. @staticmethod
  1509. def thread_compared_wechat_order(order_list):
  1510. now_time = int(time.time())
  1511. for order in order_list:
  1512. if order['交易类型'] != '`APP':
  1513. continue
  1514. order_id = order['商户订单号'].replace('`', '')
  1515. order_qs = Order_Model.objects.filter(orderID=order_id)
  1516. if not order_qs.exists():
  1517. order_dict = {
  1518. 'trade_no': order['微信订单号'].replace('`', ''),
  1519. 'order_id': order_id,
  1520. 'pay_type': 3,
  1521. 'price': order['订单金额'].replace('`', ''),
  1522. 'pay_time': int(datetime.datetime.strptime(order['\ufeff交易时间'], "`%Y-%m-%d %H:%M:%S").timestamp()),
  1523. 'upd_time': now_time,
  1524. 'meal_name': order['商品名称'].replace('`', ''),
  1525. }
  1526. AbnormalOrder.objects.create(**order_dict)
  1527. @staticmethod
  1528. def compared_alipay_order(response):
  1529. today = datetime.datetime.today()
  1530. start_date = today - datetime.timedelta(days=1)
  1531. start_date = start_date.strftime("%Y-%m-%d")
  1532. try:
  1533. ali_pay_obj = AliPayObject()
  1534. alipay = ali_pay_obj.conf()
  1535. result = alipay.server_api(
  1536. api_name='alipay.data.dataservice.bill.downloadurl.query',
  1537. biz_content={'bill_type': 'trade',
  1538. 'bill_date': start_date,
  1539. }
  1540. )
  1541. res = requests.get(result['bill_download_url'])
  1542. zip_file = res.content
  1543. zip_data = io.BytesIO(zip_file)
  1544. data = []
  1545. with zipfile.ZipFile(zip_data, 'r') as zip_ref:
  1546. for file in zip_ref.namelist():
  1547. if '汇总' not in file.encode('cp437').decode('gbk'):
  1548. with zip_ref.open(file) as f:
  1549. reader = csv.reader(io.TextIOWrapper(f, 'gbk'))
  1550. for row in reader:
  1551. data.append(row)
  1552. key_list = data[4]
  1553. orders = data[5:-4]
  1554. order_list = []
  1555. for item in orders:
  1556. order_list.append(dict(zip(key_list, item)))
  1557. thread = threading.Thread(target=CronComparedDataView.thread_compared_alipay_order,
  1558. args=(order_list,), daemon=True)
  1559. thread.start()
  1560. return response.json(0)
  1561. except Exception as e:
  1562. LOGGER.info('CronComparedDataView.compared_alipay_order, errLine:{}, errMsg:{}'.format(
  1563. e.__traceback__.tb_lineno, repr(e)))
  1564. return response.json(500)
  1565. @staticmethod
  1566. def thread_compared_alipay_order(order_list):
  1567. now_time = int(time.time())
  1568. for order in order_list:
  1569. order_id = order['商户订单号'].replace('\t', '')
  1570. if len(order_id) != 20:
  1571. continue
  1572. order_qs = Order_Model.objects.filter(orderID=order_id)
  1573. if not order_qs.exists():
  1574. order_dict = {
  1575. 'trade_no': order['支付宝交易号'].replace('\t', ''),
  1576. 'order_id': order_id,
  1577. 'pay_type': 2,
  1578. 'price': order['订单金额(元)'].replace('\t', ''),
  1579. 'pay_time': int(datetime.datetime.strptime(order['完成时间'], "%Y-%m-%d %H:%M:%S").timestamp()),
  1580. 'upd_time': now_time,
  1581. 'meal_name': order['商品名称'].replace('\t', ''),
  1582. 'username': order['对方账户'].replace('\t', ''),
  1583. }
  1584. AbnormalOrder.objects.create(**order_dict)
  1585. @staticmethod
  1586. def compared_ansjer_order(request_dict, response):
  1587. start_date_stamp = request_dict.get('time', None)
  1588. if start_date_stamp:
  1589. start_date = datetime.datetime.fromtimestamp(int(start_date_stamp))
  1590. end_date = start_date + datetime.timedelta(days=1)
  1591. end_date_stamp = int(end_date.timestamp())
  1592. else:
  1593. today = datetime.datetime.today()
  1594. start_date = today - datetime.timedelta(days=1)
  1595. start_date = datetime.datetime(start_date.year, start_date.month, start_date.day)
  1596. end_date = datetime.datetime(today.year, today.month, today.day)
  1597. start_date_stamp = int(start_date.timestamp())
  1598. end_date_stamp = int(end_date.timestamp())
  1599. try:
  1600. order_qs = Order_Model.objects.filter(status__in=[1, 5, 6], payType=1, payTime__gte=start_date_stamp,
  1601. payTime__lt=end_date_stamp).values('orderID', 'trade_no', 'price')
  1602. if CONFIG_INFO == CONFIG_EUR:
  1603. return response.json(0, list(order_qs))
  1604. thread = threading.Thread(target=CronComparedDataView.thread_compared_ansjer_order,
  1605. args=(list(order_qs), start_date), daemon=True)
  1606. thread.start()
  1607. return response.json(0)
  1608. except Exception as e:
  1609. LOGGER.info('CronComparedDataView.compared_ansjer_order, errLine:{}, errMsg:{}'.format(
  1610. e.__traceback__.tb_lineno, repr(e)))
  1611. return response.json(500)
  1612. @staticmethod
  1613. def thread_compared_ansjer_order(order_list, start_time):
  1614. while True:
  1615. response = requests.get('https://www.zositeche.com/cron/compared/AnsjerOrder',
  1616. params={'time': int(start_time.timestamp())})
  1617. if response.status_code == 200:
  1618. result = response.json()
  1619. if result['result_code'] == 0:
  1620. eur_order_list = result['result']
  1621. break
  1622. begin_date = start_time - datetime.timedelta(days=15)
  1623. end_date = start_time + datetime.timedelta(days=15)
  1624. start_timestamp = int(start_time.timestamp())
  1625. now_time = int(time.time())
  1626. more_order_list = []
  1627. total = 0
  1628. all_order_list = order_list + eur_order_list
  1629. count = len(all_order_list)
  1630. paypal_api = paypalrestsdk.Api(PAYPAL_CRD)
  1631. for index, order in enumerate(all_order_list):
  1632. total += float(order['price'])
  1633. if not order['trade_no']:
  1634. more_order_list.append(order['orderID'])
  1635. continue
  1636. if all_order_list.index(order) != index:
  1637. more_order_list.append(order['orderID'])
  1638. continue
  1639. paypal_url = 'v1/reporting/transactions?start_date={}-{}-{}T00:00:00-0000&end_date={}-{}-{}T00:00:00-0000&transaction_id={}&fields=all&page_size=100&page=1'.format(
  1640. begin_date.year, begin_date.month, begin_date.day, end_date.year, end_date.month, end_date.day,
  1641. order['trade_no'])
  1642. paypal_order_list = paypal_api.get(paypal_url)
  1643. if not paypal_order_list['transaction_details']:
  1644. more_order_list.append(order['orderID'])
  1645. total = round(total, 2)
  1646. daily_reconciliation = DailyReconciliation.objects.filter(time=start_timestamp)
  1647. if daily_reconciliation.exists():
  1648. if daily_reconciliation.first().order_ids:
  1649. more_order_list = daily_reconciliation.first().order_ids.split(',') + more_order_list
  1650. order_ids = ','.join(more_order_list)
  1651. daily_reconciliation.update(ansjer_total=total, ansjer_num=count, order_ids=order_ids, upd_time=now_time)
  1652. else:
  1653. order_ids = ','.join(more_order_list)
  1654. DailyReconciliation.objects.create(order_ids=order_ids, ansjer_total=total, ansjer_num=count,
  1655. time=start_timestamp, creat_time=now_time, upd_time=now_time)