AgentDeviceController.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : AgentDeviceController.py
  4. @Time : 2024/3/8 13:55
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import os
  10. import csv
  11. import time
  12. from datetime import datetime
  13. from dateutil.relativedelta import relativedelta
  14. from collections import defaultdict
  15. from decimal import Decimal
  16. import traceback
  17. import threading
  18. from django.db import transaction
  19. from django.http import QueryDict
  20. from django.views import View
  21. from django.core.paginator import Paginator
  22. from AgentModel.models import AgentCustomerInfo, AgentDeviceOrder, AgentDevice, AgentCloudServicePackage
  23. from Model.models import DeviceTypeModel
  24. from Object.ResponseObject import ResponseObject
  25. from Ansjer.config import LOGGER
  26. from Object.TokenObject import TokenObject
  27. class AgentDeviceView(View):
  28. def get(self, request, *args, **kwargs):
  29. request.encoding = 'utf-8'
  30. operation = kwargs.get('operation')
  31. return self.validation(request.GET, request, operation)
  32. def post(self, request, *args, **kwargs):
  33. request.encoding = 'utf-8'
  34. operation = kwargs.get('operation')
  35. return self.validation(request.POST, request, operation)
  36. def delete(self, request, *args, **kwargs):
  37. request.encoding = 'utf-8'
  38. operation = kwargs.get('operation')
  39. delete = QueryDict(request.body)
  40. if not delete:
  41. delete = request.GET
  42. return self.validation(delete, request, operation)
  43. def put(self, request, *args, **kwargs):
  44. request.encoding = 'utf-8'
  45. operation = kwargs.get('operation')
  46. put = QueryDict(request.body)
  47. return self.validation(put, request, operation)
  48. def validation(self, request_dict, request, operation):
  49. language = request_dict.get('language', 'en')
  50. response = ResponseObject(language, 'pc')
  51. # 订单结算界面
  52. if operation == 'XXXXX':
  53. pass
  54. else:
  55. tko = TokenObject(
  56. request.META.get('HTTP_AUTHORIZATION'),
  57. returntpye='pc')
  58. if tko.code != 0:
  59. return response.json(tko.code)
  60. response.lang = tko.lang
  61. userID = tko.userID
  62. if operation == 'getAgentDevice':
  63. return self.get_agent_device(userID, request_dict, response)
  64. elif operation == 'getAgentDeviceOrder':
  65. return self.get_agent_device_order(userID, request_dict, response)
  66. elif operation == 'batchBandDevice':
  67. return self.batch_band_device(userID, request, request_dict, response)
  68. else:
  69. return response.json(444, 'operation')
  70. def get_agent_device(self, userID, request_dict, response):
  71. """
  72. 查询设备明细
  73. @param userID: userID
  74. @param request_dict: 请求参数
  75. @param request_dict ac_id: 代理商id
  76. @param request_dict device_name: 设备名字
  77. @param request_dict status: 设备类型
  78. @param request_dict serial_number: 设备9位序列号
  79. @param response: 响应对象
  80. @return:
  81. """
  82. device_name = request_dict.get('device_name', None)
  83. status = request_dict.get('status', None)
  84. serial_number = request_dict.get('serial_number', None)
  85. page = int(request_dict.get('page', 1)) # 默认为第一页
  86. page_size = int(request_dict.get('page_size', 10)) # 默认每页10条记录
  87. try:
  88. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  89. if agent_customer_info is None:
  90. agent_device_qs = AgentDevice.objects.order_by('ac_id', '-created_time')
  91. else:
  92. ac_id = agent_customer_info.id
  93. agent_device_qs = AgentDevice.objects.filter(ac_id=ac_id).order_by('ac_id', '-created_time')
  94. if device_name:
  95. # 根据device_name查询对应的type值
  96. device_types = list(DeviceTypeModel.objects.filter(name=device_name).values_list('type', flat=True))
  97. agent_device_qs = agent_device_qs.filter(type__in=device_types)
  98. if status:
  99. agent_device_qs = agent_device_qs.filter(status=status)
  100. if serial_number:
  101. agent_device_qs = agent_device_qs.filter(serial_number=serial_number)
  102. # 应用分页
  103. paginator = Paginator(agent_device_qs, page_size)
  104. current_page = paginator.get_page(page)
  105. # 构造返回列表
  106. device_list = []
  107. for device in current_page:
  108. device_type = DeviceTypeModel.objects.filter(type=device.type).first()
  109. device_name = device_type.name if device_type else device.type
  110. agent_customer_info = AgentCustomerInfo.objects.filter(id=device.ac_id).first()
  111. company_name = agent_customer_info.company_name if agent_customer_info else device.ac_id
  112. device_list.append({
  113. 'id': device.id,
  114. 'ac_id': device.ac_id,
  115. 'company_name': company_name,
  116. 'status': device.status,
  117. 'serial_number': device.serial_number,
  118. 'device_name': device_name,
  119. 'at_time': device.at_time,
  120. })
  121. # 包含分页信息的响应
  122. response_data = {
  123. 'list': device_list,
  124. 'total': paginator.count,
  125. 'page': current_page.number,
  126. 'page_size': page_size,
  127. 'num_pages': paginator.num_pages,
  128. }
  129. return response.json(0, response_data)
  130. except Exception as e:
  131. print(e)
  132. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  133. def calculate_profit_or_revenue(self, agent_device_orders, package_details, time_unit, metric_type, start_time, end_time):
  134. """
  135. 计算利润或者营业额
  136. @param agent_device_orders: 代理设备订单
  137. @param package_details: 代理套餐详情
  138. @param time_unit: 时间单位
  139. @param metric_type: 利润或者营业额
  140. @param start_time: 开始时间
  141. @param end_time: 结束时间
  142. @return:
  143. """
  144. summary = defaultdict(lambda: {"云存": Decimal('0.00'), "4G": Decimal('0.00'), "all": Decimal('0.00')})
  145. time_format = {
  146. "month": "%Y-%m",
  147. "year": "%Y",
  148. "quarter": lambda x: f"{x.year}年{(x.month - 1) // 3 + 1}季度"
  149. }
  150. for order in agent_device_orders:
  151. package = package_details.get(order.csp_id)
  152. if not package:
  153. continue
  154. # 根据利润类型计算利润或者直接使用营业额
  155. if metric_type == 1: # 利润
  156. profit = order.profit
  157. else: # 营业额
  158. profit = order.profit_amount
  159. # 区分云服务 + 4G套餐并加入 summary
  160. service_type = "云存" if package.type == 1 else "4G"
  161. time_key = datetime.fromtimestamp(order.created_time).strftime(
  162. time_format[time_unit]) if time_unit != "quarter" else time_format[time_unit](
  163. datetime.fromtimestamp(order.created_time))
  164. summary[time_key][service_type] += profit
  165. summary[time_key]["all"] += profit
  166. # 补全时间段内所有可能的时间单位
  167. current_time = start_time
  168. end_time += relativedelta(days=1) # 包括结束日期
  169. while current_time < end_time:
  170. time_key = current_time.strftime(time_format[time_unit]) if time_unit != "quarter" else time_format[
  171. time_unit](current_time)
  172. if time_key not in summary:
  173. summary[time_key] = {"云存": Decimal('0.00'), "4G": Decimal('0.00'), "all": Decimal('0.00')}
  174. current_time += relativedelta(months=1) if time_unit == "month" else relativedelta(
  175. years=1) if time_unit == "year" else relativedelta(months=3)
  176. return [{"time": time, **data} for time, data in sorted(summary.items())]
  177. def get_agent_device_order(self, userID, request_dict, response):
  178. """
  179. 查询设备订单明细
  180. @param userID: userID
  181. @param request_dict: 请求参数
  182. @param request_dict startTime: 开始时间
  183. @param request_dict endTime: 结束时间
  184. @param request_dict timeUnit: 时间单位
  185. @param request_dict metric_type: 利润或者营业额
  186. @param response: 响应对象
  187. @return:
  188. """
  189. try:
  190. startTime = int(request_dict.get('startTime', 1704038400))
  191. endTime = int(request_dict.get('endTime', 1732982400))
  192. timeUnit = request_dict.get('timeUnit', 'month')
  193. metric_type = int(request_dict.get('metric_type', 0))
  194. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  195. if not agent_customer_info:
  196. return response.json(104, 'Agent customer not found')
  197. agent_device_orders = AgentDeviceOrder.objects.filter(
  198. ac_id=agent_customer_info.id, created_time__gte=startTime, created_time__lte=endTime, status__in=[1, 2]
  199. )
  200. # 获取代理套餐包id
  201. package_ids = agent_device_orders.values_list('csp_id', flat=True).distinct()
  202. package_details = {pkg.id: pkg for pkg in AgentCloudServicePackage.objects.filter(id__in=package_ids)}
  203. start_time = datetime.fromtimestamp(startTime)
  204. end_time = datetime.fromtimestamp(endTime)
  205. result = self.calculate_profit_or_revenue(agent_device_orders, package_details, timeUnit, metric_type,
  206. start_time, end_time)
  207. total_4G = Decimal('0.00')
  208. total_cloud = Decimal('0.00')
  209. # 遍历result列表来累加4G和云存的值
  210. for item in result:
  211. total_4G = item['4G'] + total_4G
  212. total_cloud = item['云存'] + total_cloud
  213. response_data = {
  214. "list": result,
  215. "total_4G": total_4G, # 4G的总和
  216. "total_云存": total_cloud, # 云存的总和
  217. }
  218. return response.json(0, response_data)
  219. except Exception as e:
  220. error_msg = f"error_line:{traceback.format_exc()}, error_msg:{str(e)}"
  221. return response.json(500, error_msg)
  222. def agent_devices_from_csv(self, ac_id, device_type, userID, file_path):
  223. """
  224. 异步批量绑定设备
  225. """
  226. try:
  227. with open(file_path, 'r') as file:
  228. reader = csv.DictReader(file)
  229. devices_to_create = []
  230. existing_serial_numbers = set(AgentDevice.objects.values_list('serial_number', flat=True))
  231. for row in reader:
  232. serial_number = row.get('serial_number')
  233. if serial_number not in existing_serial_numbers:
  234. device = AgentDevice(
  235. ac_id=ac_id,
  236. serial_number=serial_number,
  237. type=device_type,
  238. status=0,
  239. created_time=int(time.time()),
  240. created_by=userID,
  241. updated_time=int(time.time()),
  242. updated_by=userID
  243. )
  244. devices_to_create.append(device)
  245. # 使用Django的bulk_create来批量创建对象
  246. if devices_to_create:
  247. with transaction.atomic():
  248. AgentDevice.objects.bulk_create(devices_to_create, batch_size=200)
  249. # 删除文件
  250. os.remove(file_path)
  251. except Exception as e:
  252. LOGGER.info('errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  253. def batch_band_device(self, userID, request, request_dict, response):
  254. """
  255. 批量绑定设备
  256. @param ac_id: ac_id 代理商id
  257. @param userID: userID
  258. @param csv_file_path: 文件路径
  259. @param response: 响应对象
  260. @return:
  261. """
  262. ac_id = request_dict.get('ac_id', None)
  263. device_name = request_dict.get('device_name', None)
  264. csv_file = request.FILES['file']
  265. upload_dir = os.path.join('static', 'uploaded_files')
  266. if not all([ac_id, device_name]):
  267. return response.json(444)
  268. try:
  269. device_type_dict = DeviceTypeModel.objects.filter(name=device_name).values('type').first()
  270. device_type = device_type_dict['type']
  271. if not os.path.exists(upload_dir):
  272. os.makedirs(upload_dir)
  273. file_path = os.path.join(upload_dir, csv_file.name)
  274. with open(file_path, 'wb+') as destination:
  275. for chunk in csv_file.chunks():
  276. destination.write(chunk)
  277. # 创建并启动线程来异步执行任务
  278. thread = threading.Thread(target=self.agent_devices_from_csv, args=(ac_id, device_type, userID, file_path))
  279. thread.start()
  280. return response.json(0)
  281. except Exception as e:
  282. print(e)
  283. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))