CronTaskController.py 88 KB

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