CronTaskController.py 107 KB

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