ProblemEntryManagementController.py 11 KB

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