ProblemEntryManagementController.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import json
  2. import time
  3. from django.core.paginator import Paginator
  4. from django.db import transaction
  5. from django.views import View
  6. from Ansjer.test.util.email_log import response
  7. from Model.models import DeviceScheme, ProductTroubleshoot, AbnormalEventCode, ProductsScheme, AbnormalEvent
  8. from Object.ResponseObject import ResponseObject
  9. from Service.CommonService import CommonService
  10. class ProblemEntryView(View):
  11. def get(self, request, *args, **kwargs):
  12. request.encoding = 'utf-8'
  13. operation = kwargs.get('operation')
  14. request_dict = request.GET
  15. return self.validation(request, request_dict, operation)
  16. def post(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. operation = kwargs.get('operation')
  19. request_dict = request.POST
  20. return self.validation(request, request_dict, operation)
  21. def validation(self, request, request_dict, operation):
  22. language = request_dict.get('language', 'en')
  23. response = ResponseObject(language, 'pc')
  24. if operation == 'addProductProblem':
  25. return self.add_product_problem(request_dict, response)
  26. elif operation == 'queryEventSubcategory':
  27. return self.query_event_subcategory(request_dict, response)
  28. elif operation == 'queryDeviceScheme':
  29. return self.query_device_scheme(request_dict, response)
  30. elif operation == 'ProductProblemList':
  31. return self.product_problem_list(request_dict, response)
  32. elif operation == 'editProductProblemStatus':
  33. return self.edit_product_problem_status(request_dict, response)
  34. else:
  35. return response.json(414)
  36. @staticmethod
  37. def add_product_problem(request_dict, response):
  38. try:
  39. # 解析请求数据
  40. date_times = json.loads(request_dict.get('dateTimes', '[]'))
  41. deivce_ids = json.loads(request_dict.get('deviceIds', '[]'))
  42. device_types = json.loads(request_dict.get('deviceTypes', '[]'))
  43. storage_codes = json.loads(request_dict.get('storageCodes', '[]'))
  44. event_codes = json.loads(request_dict.get('eventCodes', '[]'))
  45. remarks = json.loads(request_dict.get('remarks', '[]'))
  46. # 基础数据校验
  47. list_lengths = {
  48. "dateTimes": len(date_times),
  49. "serialNumbers": len(deivce_ids),
  50. "deviceTypes": len(device_types),
  51. "storageCodes": len(storage_codes),
  52. "eventCodes": len(event_codes),
  53. "remarks": len(remarks)
  54. }
  55. # 检查各字段数据长度一致性
  56. if len(set(list_lengths.values())) != 1:
  57. return response.json(400, f'参数长度不一致: {", ".join([f"{k}({v})" for k, v in list_lengths.items()])}')
  58. current_time = int(time.time())
  59. products = []
  60. # 数据预处理
  61. for idx in range(len(date_times)):
  62. # 字段值提取
  63. date_time = date_times[idx]
  64. deivce_id = deivce_ids[idx].strip() # 去除前后空格
  65. device_type = device_types[idx]
  66. storage_code = storage_codes[idx]
  67. event_code = event_codes[idx].strip()
  68. remark = remarks[idx].strip()
  69. # 构建对象
  70. products.append(
  71. ProductTroubleshoot(
  72. date_time=date_time,
  73. device_id=deivce_id,
  74. device_type=device_type,
  75. event_code=event_code,
  76. storage_code=storage_code,
  77. status=0,
  78. remark=remark,
  79. created_time=current_time,
  80. updated_time=current_time
  81. )
  82. )
  83. # 批量写入数据库
  84. with transaction.atomic():
  85. ProductTroubleshoot.objects.bulk_create(products)
  86. return response.json(0)
  87. except Exception as e:
  88. print(e)
  89. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  90. @staticmethod
  91. def query_event_subcategory(request_dict, response):
  92. event_type_code = request_dict.get('eventTypeCode', None)
  93. abnormal_event_code_qs = AbnormalEventCode.objects.all()
  94. if event_type_code:
  95. abnormal_event_code_qs = abnormal_event_code_qs.filter(event_code__istartswith=event_type_code)
  96. data = []
  97. for abnormal_event_code in abnormal_event_code_qs:
  98. # 第0个是大类 第一个是细分
  99. event_list = abnormal_event_code.event.split("-")
  100. data.append(
  101. {
  102. "eventTypeCode": abnormal_event_code.event_code[0:2],
  103. "eventType": abnormal_event_code.event_type,
  104. "eventSegCode": abnormal_event_code.event_code[2:4],
  105. "eventSeg": event_list[1] if len(event_list) > 1 else "",
  106. "eventDescriptionCode": abnormal_event_code.event_code[4:],
  107. "eventDescription": event_list[2] if len(event_list) > 2 else "",
  108. }
  109. )
  110. return response.json(0, data)
  111. @staticmethod
  112. def query_device_scheme(request_dict, response):
  113. device_id = request_dict.get('deviceId', None)
  114. if not device_id:
  115. return response.json(0, msg="设备ID不能为空")
  116. try:
  117. # 获取设备信息
  118. device_scheme = DeviceScheme.objects.filter(serial_number=device_id).values("device_type",
  119. "storage_code").first()
  120. if not device_scheme:
  121. return response.json(0)
  122. # 获取产品方案信息
  123. product_scheme = ProductsScheme.objects.filter(
  124. storage_code=device_scheme["storage_code"]
  125. ).values(
  126. "order_quantity", "created_time", "storage_code", "flash",
  127. "ddr", "main_controller", "wifi", "four_g", "ad", "sensor", "phy"
  128. ).first()
  129. if not product_scheme:
  130. return response.json(0, {"deviceType": device_scheme["device_type"]})
  131. # 拼接方案字符串,过滤空值
  132. scheme_parts = [
  133. product_scheme["flash"],
  134. product_scheme["ddr"],
  135. product_scheme["main_controller"],
  136. product_scheme["wifi"],
  137. product_scheme["four_g"],
  138. product_scheme["ad"],
  139. product_scheme["sensor"],
  140. product_scheme["phy"]
  141. ]
  142. scheme = " + ".join(part for part in scheme_parts if part)
  143. return response.json(0, {
  144. "deviceType": device_scheme["device_type"],
  145. "quantity": product_scheme["order_quantity"],
  146. "createdTime": product_scheme["created_time"],
  147. "storageCode": product_scheme["storage_code"],
  148. "scheme": scheme,
  149. })
  150. except Exception as e:
  151. print(e)
  152. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  153. @staticmethod
  154. def product_problem_list(request_dict, response):
  155. device_id = request_dict.get("deviceId", None)
  156. storage_code = request_dict.get("storageCode", None)
  157. event_code = request_dict.get("eventCode", None)
  158. status = request_dict.get("status", None)
  159. page = request_dict.get("page", 1)
  160. pageSize = request_dict.get("pageSize", 10)
  161. # 1. 先查询ProductTroubleshoot表
  162. product_troubleshoot_qs = ProductTroubleshoot.objects.all()
  163. if device_id:
  164. product_troubleshoot_qs = product_troubleshoot_qs.filter(device_id=device_id)
  165. if storage_code:
  166. product_troubleshoot_qs = product_troubleshoot_qs.filter(storage_code__contains=storage_code)
  167. if event_code:
  168. product_troubleshoot_qs = product_troubleshoot_qs.filter(event_code__contains=event_code)
  169. if status:
  170. product_troubleshoot_qs = product_troubleshoot_qs.filter(status=status)
  171. paginator = Paginator(product_troubleshoot_qs.order_by('status', '-id'), pageSize)
  172. product_trouble_page = paginator.page(page)
  173. # 获取当前页的数据列表
  174. product_trouble_list = list(product_trouble_page.object_list.values(
  175. 'id',
  176. 'date_time',
  177. 'device_type',
  178. 'device_id',
  179. 'storage_code',
  180. 'event_code',
  181. 'status',
  182. 'remark',
  183. ))
  184. # 2. 收集所有storage_code用于批量查询ProductsScheme表
  185. storage_codes = [item['storage_code'] for item in product_trouble_list if item['storage_code']]
  186. product_schemes = ProductsScheme.objects.filter(storage_code__in=storage_codes)
  187. # 3. 创建映射字典并拼接字段
  188. scheme_info_dict = {}
  189. for scheme in product_schemes:
  190. # 拼接需要的字段,过滤掉空值
  191. fields_to_join = [
  192. scheme.flash,
  193. scheme.ddr,
  194. scheme.main_controller,
  195. scheme.wifi,
  196. scheme.four_g,
  197. scheme.ad,
  198. scheme.sensor,
  199. scheme.customer_code,
  200. scheme.phy,
  201. ]
  202. # 过滤掉None和空字符串,然后用逗号连接
  203. joined_info = '+'.join(filter(None, fields_to_join))
  204. scheme_info_dict[scheme.storage_code] = joined_info
  205. # 4. 将拼接后的信息添加到原数据中
  206. for item in product_trouble_list:
  207. storage_code = item['storage_code']
  208. item['product_scheme_info'] = scheme_info_dict.get(storage_code, '')
  209. data = {
  210. "list": product_trouble_list,
  211. "total": paginator.count,
  212. }
  213. return response.json(0, data)
  214. @staticmethod
  215. def edit_product_problem_status(request_dict, response):
  216. try:
  217. record_id = request_dict.get("id", None)
  218. new_status = request_dict.get("status", None)
  219. if not all([record_id, new_status]):
  220. return response.json(444)
  221. new_status = int(new_status)
  222. try:
  223. troubleshoot_record = ProductTroubleshoot.objects.get(id=record_id)
  224. except ProductTroubleshoot.DoesNotExist:
  225. return response.json(173)
  226. # 更新状态
  227. troubleshoot_record.status = new_status
  228. updated_time = int(time.time())
  229. troubleshoot_record.save()
  230. # 如果是审批通过状态(1),创建异常事件
  231. if new_status == 1:
  232. device_id = troubleshoot_record.device_id
  233. device_type = troubleshoot_record.device_type
  234. # 获取UID
  235. uid = device_id if device_type == 2 else CommonService.get_uid_by_serial_number(device_id)
  236. # 获取设备型号
  237. device_model = 0
  238. device_scheme = DeviceScheme.objects.filter(serial_number=device_id).first()
  239. if device_scheme:
  240. device_model = device_scheme.device_type
  241. # 创建异常事件
  242. AbnormalEvent.objects.create(
  243. uid=uid,
  244. event_code=troubleshoot_record.event_code,
  245. device_type=device_model,
  246. content=troubleshoot_record.remark,
  247. report_type=1,
  248. created_time=int(time.time())
  249. )
  250. return response.json(0) # 成功
  251. except Exception as e:
  252. print(e)
  253. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))