CronTaskController.py 89 KB

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