HomeDataController.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UserDataController.py
  4. @Time : 2022/8/16 10:44
  5. @Author : peng
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import datetime
  10. import openpyxl
  11. import requests
  12. from django.db.models import Sum
  13. from django.http import HttpResponse
  14. from django.utils.encoding import escape_uri_path
  15. from django.views.generic.base import View
  16. from Model.models import DeviceUserSummary, OrdersSummary, DeviceInfoSummary
  17. from Service.CommonService import CommonService
  18. # 业务数据
  19. class HomeDataView(View):
  20. def get(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation')
  23. return self.validation(request.GET, request, operation)
  24. def post(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. operation = kwargs.get('operation')
  27. return self.validation(request.POST, request, operation)
  28. def validation(self, request_dict, request, operation):
  29. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  30. if token_code != 0:
  31. return response.json(token_code)
  32. if operation == 'allData': # 查询首页数据
  33. return self.query_all_data(response)
  34. elif operation == 'salesVolume': # 查询销售额数据
  35. return self.query_sales_volume_data(request_dict, response)
  36. elif operation == 'global/allData': # 查询全球首页数据
  37. return self.query_global_all_data(request, request_dict, response)
  38. elif operation == 'global/salesVolume': # 查询全球销售额数据
  39. return self.query_global_sales_volume_data(request, request_dict, response)
  40. elif operation == 'exportData': # 查询全球销售额数据
  41. return self.export_data(request_dict, response)
  42. else:
  43. return response.json(414)
  44. @classmethod
  45. def query_all_data(cls, response):
  46. """
  47. 查询首页数据
  48. @param response:响应对象
  49. @return:
  50. """
  51. end_time = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
  52. start_time = end_time + datetime.timedelta(days=-1)
  53. end_time_stamp = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  54. start_time_stamp = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  55. try:
  56. # 昨日用户增长数据
  57. user_increase_qs = DeviceUserSummary.objects.filter(time__gte=start_time_stamp, time__lt=end_time_stamp,
  58. query_type=0).values('count', 'country')
  59. user_increase_count = user_increase_qs.aggregate(count=Sum('count'))['count']
  60. user_increase_count = user_increase_count if user_increase_count else 0
  61. user_increase_region_dict = {}
  62. user_increase_region_list = []
  63. for item in user_increase_qs:
  64. user_increase_region_temp_dict = eval(item['country'])
  65. for k, v in user_increase_region_temp_dict.items():
  66. if k in user_increase_region_dict:
  67. user_increase_region_dict[k] += v
  68. else:
  69. user_increase_region_dict[k] = v
  70. for k, v in user_increase_region_dict.items():
  71. user_increase_region_list.append({
  72. 'countryName': k,
  73. 'count': v
  74. })
  75. # 所有用户数据
  76. user_all_qs = DeviceUserSummary.objects.filter(time__lte=start_time_stamp, query_type=0).values('count',
  77. 'country')
  78. user_all_region_dict = {}
  79. user_all_region_list = []
  80. for item in user_all_qs:
  81. user_all_region_temp_dict = eval(item['country'])
  82. for k, v in user_all_region_temp_dict.items():
  83. if k in user_all_region_dict:
  84. user_all_region_dict[k] += v
  85. else:
  86. user_all_region_dict[k] = v
  87. for k, v in user_all_region_dict.items():
  88. user_all_region_list.append({
  89. 'countryName': k,
  90. 'count': v
  91. })
  92. user_all_count = user_all_qs.aggregate(count=Sum('count'))['count']
  93. user_all_count = user_all_count if user_all_count else 0
  94. # 活跃用户数据
  95. user_active_count = DeviceUserSummary.objects.filter(time__gte=start_time_stamp, time__lt=end_time_stamp,
  96. query_type=1).aggregate(count=Sum('count'))['count']
  97. user_active_count = round(user_active_count, 2) if user_active_count else 0
  98. # 新增设备数据
  99. device_increase_count = DeviceInfoSummary.objects.filter(time__gte=start_time_stamp,
  100. time__lt=end_time_stamp,
  101. query_type=0).aggregate(count=Sum('count'))
  102. device_increase_count = device_increase_count['count'] if device_increase_count['count'] else 0
  103. # 活跃设备数据
  104. device_active_count = DeviceInfoSummary.objects.filter(time__gte=start_time_stamp,
  105. time__lt=end_time_stamp,
  106. query_type=1).aggregate(count=Sum('count'))['count']
  107. device_active_count = device_active_count if device_active_count else 0
  108. # 所有设备数据
  109. device_all_count = DeviceInfoSummary.objects.filter(time__lte=start_time_stamp,
  110. query_type=0).aggregate(count=Sum('count'))['count']
  111. device_all_count = device_all_count if device_all_count else 0
  112. # 昨日订单销售额
  113. order_qs = OrdersSummary.objects.filter(time__gte=start_time_stamp,
  114. time__lt=end_time_stamp,
  115. query_type=0).values('total')
  116. order_total = order_qs.aggregate(total=Sum('total'))['total']
  117. order_total = round(order_total, 2) if order_total else 0
  118. # 昨日云存订单销售额
  119. vod_order_total = order_qs.filter(service_type=0).aggregate(total=Sum('total'))['total']
  120. vod_order_total = round(vod_order_total, 2) if vod_order_total else 0
  121. # 昨日AI订单销售额
  122. ai_order_total = order_qs.filter(service_type=1).aggregate(total=Sum('total'))['total']
  123. ai_order_total = round(ai_order_total, 2) if ai_order_total else 0
  124. # 昨日联通订单销售额
  125. unicom_order_total = order_qs.filter(service_type=2).aggregate(total=Sum('total'))['total']
  126. unicom_order_total = round(unicom_order_total, 2) if unicom_order_total else 0
  127. # 所有订单销售额
  128. order_all_qs = OrdersSummary.objects.filter(time__lte=start_time_stamp, query_type=0).values('total')
  129. order_all_total = order_all_qs.aggregate(total=Sum('total'))['total']
  130. order_all_total = round(order_all_total, 2) if order_all_total else 0
  131. # 所有云存订单销售额
  132. vod_order_all_total = order_all_qs.filter(service_type=0).aggregate(total=Sum('total'))['total']
  133. vod_order_all_total = round(vod_order_all_total, 2) if vod_order_all_total else 0
  134. # 所有AI订单销售额
  135. ai_order_all_total = order_all_qs.filter(service_type=1).aggregate(total=Sum('total'))['total']
  136. ai_order_all_total = round(ai_order_all_total, 2) if ai_order_all_total else 0
  137. # 所有联通订单销售额
  138. unicom_order_all_total = order_all_qs.filter(service_type=2).aggregate(total=Sum('total'))['total']
  139. unicom_order_all_total = round(unicom_order_all_total, 2) if unicom_order_all_total else 0
  140. res = {
  141. 'userIncreaseCount': user_increase_count,
  142. 'userActiveCount': user_active_count,
  143. 'userAllCount': user_all_count,
  144. 'deviceIncreaseCount': device_increase_count,
  145. 'deviceActiveCount': device_active_count,
  146. 'deviceAllCount': device_all_count,
  147. 'orderTotal': order_total,
  148. 'vodOrderTotal': vod_order_total,
  149. 'aiOrderTotal': ai_order_total,
  150. 'unicomOrderTotal': unicom_order_total,
  151. 'orderAllTotal': order_all_total,
  152. 'vodOrderAllTotal': vod_order_all_total,
  153. 'aiOrderAllTotal': ai_order_all_total,
  154. 'unicomOrderAllTotal': unicom_order_all_total,
  155. 'userIncreaseRegion': user_increase_region_list,
  156. 'userAllRegion': user_all_region_list
  157. }
  158. return response.json(0, res)
  159. except Exception as e:
  160. return response.json(500, repr(e))
  161. @classmethod
  162. def query_sales_volume_data(cls, request_dict, response):
  163. """
  164. 查询销售额数据
  165. @param request_dict:请求参数
  166. @request_dict startTime:开始时间
  167. @request_dict endTime:结束时间
  168. @request_dict timeUnit:时间单位
  169. @param response:响应对象
  170. @return:
  171. """
  172. start_time = request_dict.get('startTime', None)
  173. end_time = request_dict.get('endTime', None)
  174. time_unit = request_dict.get('timeUnit', None)
  175. if not all([start_time, end_time, time_unit]):
  176. return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
  177. try:
  178. order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time, query_type=0).values(
  179. 'total')
  180. start_time = datetime.datetime.fromtimestamp(int(start_time))
  181. end_time = datetime.datetime.fromtimestamp(int(end_time))
  182. time_list = CommonService.cutting_time(start_time, end_time, time_unit)
  183. order_list = []
  184. for item in time_list:
  185. temp_order_qs = order_qs.filter(time__gte=item[0], time__lt=item[1])
  186. cny_total = 0
  187. usd_total = 0
  188. for each in temp_order_qs:
  189. temp_total = eval(each['total'])
  190. cny_total += temp_total.get('CNY', 0)
  191. usd_total += temp_total.get('USD', 0)
  192. res = {
  193. 'rmbTotal': cny_total,
  194. 'usdTotal': usd_total,
  195. 'startTime': item[0],
  196. 'endTime': item[1]
  197. }
  198. order_list.append(res)
  199. return response.json(0, order_list)
  200. except Exception as e:
  201. return response.json(500, repr(e))
  202. @classmethod
  203. def query_global_all_data(cls, request, request_dict, response):
  204. """
  205. 查询全球首页数据
  206. @param request:请求
  207. @param request_dict:请求参数
  208. @param response:响应对象
  209. @return:
  210. """
  211. url_list = CommonService.get_domain_name()
  212. try:
  213. headers = {
  214. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  215. }
  216. user_increase_count = 0
  217. user_active_count = 0
  218. user_all_count = 0
  219. device_increase_count = 0
  220. device_active_count = 0
  221. device_all_count = 0
  222. order_total = 0
  223. vod_order_total = 0
  224. ai_order_total = 0
  225. unicom_order_total = 0
  226. order_all_total = 0
  227. vod_order_all_total = 0
  228. ai_order_all_total = 0
  229. unicom_order_all_total = 0
  230. user_increase_temp_list = []
  231. user_increase_list = []
  232. user_increase_other_dict = {'count': 0, 'countryName': '其他', 'rate': 0}
  233. user_all_temp_list = []
  234. user_all_list = []
  235. user_all_other_dict = {'count': 0, 'countryName': '其他', 'rate': 0}
  236. for url in url_list:
  237. url = url + request.path.replace('global/', '')
  238. res = requests.get(url=url, params=request_dict, headers=headers)
  239. result = res.json()
  240. if result['result_code'] == 0:
  241. user_increase_count += result['result']['userIncreaseCount']
  242. user_active_count += result['result']['userActiveCount']
  243. user_all_count += result['result']['userAllCount']
  244. device_increase_count += result['result']['deviceIncreaseCount']
  245. device_active_count += result['result']['deviceActiveCount']
  246. device_all_count += result['result']['deviceAllCount']
  247. order_total += result['result']['orderTotal']
  248. vod_order_total += result['result']['vodOrderTotal']
  249. ai_order_total += result['result']['aiOrderTotal']
  250. unicom_order_total += result['result']['unicomOrderTotal']
  251. order_all_total += result['result']['orderAllTotal']
  252. vod_order_all_total += result['result']['vodOrderAllTotal']
  253. ai_order_all_total += result['result']['aiOrderAllTotal']
  254. unicom_order_all_total += result['result']['unicomOrderAllTotal']
  255. for item in result['result']['userIncreaseRegion']:
  256. flag = 0
  257. for each in user_increase_temp_list:
  258. if item['countryName'] == each['countryName']:
  259. each['count'] += item['count']
  260. flag = 1
  261. break
  262. if flag == 0:
  263. user_increase_temp_list.append(item)
  264. for item in result['result']['userAllRegion']:
  265. flag = 0
  266. for each in user_all_temp_list:
  267. if item['countryName'] == each['countryName']:
  268. each['count'] += item['count']
  269. flag = 1
  270. break
  271. if flag == 0:
  272. user_all_temp_list.append(item)
  273. else:
  274. return response.json(result['result_code'], result['result'])
  275. if user_increase_temp_list:
  276. for item in user_increase_temp_list:
  277. if user_increase_count:
  278. rate = round(item['count'] / user_increase_count * 100, 2)
  279. else:
  280. rate = 0
  281. if rate >= 10:
  282. item['rate'] = rate
  283. user_increase_list.append(item)
  284. else:
  285. user_increase_other_dict['count'] += item['count']
  286. if user_increase_count:
  287. user_increase_other_dict['rate'] = round(
  288. user_increase_other_dict['count'] / user_increase_count * 100, 2)
  289. if user_increase_other_dict['count']:
  290. user_increase_list.append(user_increase_other_dict)
  291. if user_all_temp_list:
  292. for item in user_all_temp_list:
  293. if user_all_count:
  294. rate = round(item['count'] / user_all_count * 100, 2)
  295. else:
  296. rate = 0
  297. if rate >= 10:
  298. item['rate'] = rate
  299. user_all_list.append(item)
  300. else:
  301. user_all_other_dict['count'] += item['count']
  302. if user_all_count:
  303. user_all_other_dict['rate'] = round(user_all_other_dict['count'] / user_all_count * 100, 2)
  304. if user_all_other_dict['count']:
  305. user_all_list.append(user_all_other_dict)
  306. res = {
  307. 'userIncreaseCount': user_increase_count,
  308. 'userActiveCount': user_active_count,
  309. 'userAllCount': user_all_count,
  310. 'deviceIncreaseCount': device_increase_count,
  311. 'deviceActiveCount': device_active_count,
  312. 'deviceAllCount': device_all_count,
  313. 'orderTotal': order_total,
  314. 'vodOrderTotal': vod_order_total,
  315. 'aiOrderTotal': ai_order_total,
  316. 'unicomOrderTotal': unicom_order_total,
  317. 'orderAllTotal': order_all_total,
  318. 'vodOrderAllTotal': vod_order_all_total,
  319. 'aiOrderAllTotal': ai_order_all_total,
  320. 'unicomOrderAllTotal': unicom_order_all_total,
  321. 'userIncreaseRegion': user_increase_list,
  322. 'userAllRegion': user_all_list
  323. }
  324. return response.json(0, res)
  325. except Exception as e:
  326. return response.json(500, repr(e))
  327. @classmethod
  328. def query_global_sales_volume_data(cls, request, request_dict, response):
  329. """
  330. 查询全球销售额数据
  331. @param request:请求
  332. @param request_dict:请求参数
  333. @param response:响应对象
  334. @return:
  335. """
  336. url_list = CommonService.get_domain_name()
  337. try:
  338. headers = {
  339. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  340. }
  341. order_list = []
  342. for url in url_list:
  343. url = url + request.path.replace('global/', '')
  344. res = requests.get(url=url, params=request_dict, headers=headers)
  345. result = res.json()
  346. if result['result_code'] == 0:
  347. for item in result['result']:
  348. flag = 0
  349. for each in order_list:
  350. if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
  351. each['cnyTotal'] = round(each['cnyTotal'] + item['cnyTotal'], 2)
  352. each['usdTotal'] = round(each['usdTotal'] + item['usdTotal'], 2)
  353. flag = 1
  354. break
  355. if flag == 0:
  356. order_list.append(item)
  357. else:
  358. return response.json(result['result_code'], result['result'])
  359. return response.json(0, order_list)
  360. except Exception as e:
  361. return response.json(500, repr(e))
  362. @classmethod
  363. def export_data(cls, request_dict, response):
  364. """
  365. 下载文件
  366. @param request_dict:请求参数
  367. @request_dict tableData:表格数据
  368. @request_dict fileName:文件名
  369. @param response:响应对象
  370. @return:
  371. """
  372. table_data = request_dict.get('tableData', None)
  373. sheet_name = request_dict.get('fileName', None)
  374. if not all([table_data, sheet_name]):
  375. return response.json(444, {'error param': 'tableData or fileName'})
  376. table_data = eval(table_data)
  377. file_name = sheet_name + '.xlsx'
  378. try:
  379. res = HttpResponse(content_type='application/octet-stream')
  380. res['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file_name))
  381. wb = openpyxl.Workbook()
  382. sh = wb.create_sheet(sheet_name, 0)
  383. for row, data in enumerate(table_data):
  384. if row == 0:
  385. sh.append(list(data.keys()))
  386. sh.append(list(data.values()))
  387. wb.save(res)
  388. # with open(file_path, 'rb') as f:
  389. # res = HttpResponse(f)
  390. # res['Content-Type'] = 'application/octet-stream'
  391. # res['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
  392. return res
  393. except Exception as e:
  394. return response.json(500, repr(e))