views.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. from rest_framework import viewsets
  2. from utils.page import MyPageNumberPagination
  3. from utils.datasolve import sumOfList, transportation_calculate
  4. from utils.md5 import Md5
  5. from rest_framework.filters import OrderingFilter
  6. from django_filters.rest_framework import DjangoFilterBackend
  7. from rest_framework.response import Response
  8. from rest_framework.exceptions import APIException
  9. from django.utils import timezone
  10. from django.db import transaction
  11. import logging
  12. from rest_framework import status
  13. from .models import ContainerListModel,ContainerDetailModel,ContainerOperationModel,ContainerWCSModel,TaskModel
  14. from bound.models import BoundBatchModel,BoundDetailModel,BoundListModel
  15. # from .files import FileListRenderCN, FileDetailRenderCN
  16. from .serializers import ContainerDetailGetSerializer,ContainerDetailPostSerializer
  17. from .serializers import ContainerListGetSerializer,ContainerListPostSerializer
  18. from .serializers import ContainerOperationGetSerializer,ContainerOperationPostSerializer
  19. from .serializers import TaskGetSerializer,TaskPostSerializer
  20. from .filter import ContainerDetailFilter,ContainerListFilter,ContainerOperationFilter,TaskFilter
  21. # 以后添加模
  22. from warehouse.models import ListModel as warehouse
  23. from staff.models import ListModel as staff
  24. from rest_framework.permissions import AllowAny
  25. logger = logging.getLogger(__name__)
  26. class ContainerListViewSet(viewsets.ModelViewSet):
  27. """
  28. retrieve:
  29. Response a data list(get)
  30. list:
  31. Response a data list(all)
  32. create:
  33. Create a data line(post)
  34. delete:
  35. Delete a data line(delete)
  36. """
  37. # authentication_classes = [] # 禁用所有认证类
  38. # permission_classes = [AllowAny] # 允许任意访问
  39. pagination_class = MyPageNumberPagination
  40. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  41. ordering_fields = ['id', "create_time", "update_time", ]
  42. filter_class = ContainerListFilter
  43. def get_project(self):
  44. try:
  45. id = self.kwargs.get('pk')
  46. return id
  47. except:
  48. return None
  49. def get_queryset(self):
  50. id = self.get_project()
  51. if self.request.user:
  52. if id is None:
  53. return ContainerListModel.objects.filter()
  54. else:
  55. return ContainerListModel.objects.filter( id=id)
  56. else:
  57. return ContainerListModel.objects.none()
  58. def get_serializer_class(self):
  59. if self.action in ['list', 'destroy','retrieve']:
  60. return ContainerListGetSerializer
  61. elif self.action in ['create', 'update']:
  62. return ContainerListPostSerializer
  63. else:
  64. return self.http_method_not_allowed(request=self.request)
  65. def create(self, request, *args, **kwargs):
  66. data = self.request.data
  67. order_month = str(timezone.now().strftime('%Y%m'))
  68. data['month'] = order_month
  69. data['last_operate'] = str(timezone.now())
  70. serializer = self.get_serializer(data=data)
  71. serializer.is_valid(raise_exception=True)
  72. serializer.save()
  73. headers = self.get_success_headers(serializer.data)
  74. return Response(serializer.data, status=200, headers=headers)
  75. def update(self, request, pk):
  76. qs = self.get_object()
  77. data = self.request.data
  78. serializer = self.get_serializer(qs, data=data)
  79. serializer.is_valid(raise_exception=True)
  80. serializer.save()
  81. headers = self.get_success_headers(serializer.data)
  82. return Response(serializer.data, status=200, headers=headers)
  83. class TaskViewSet(viewsets.ModelViewSet):
  84. """
  85. retrieve:
  86. Response a data list(get)
  87. list:
  88. Response a data list(all)
  89. create:
  90. Create a data line(post)
  91. delete:
  92. Delete a data line(delete)
  93. """
  94. pagination_class = MyPageNumberPagination
  95. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  96. ordering_fields = ['id', "create_time", "update_time", ]
  97. filter_class = TaskFilter
  98. def get_project(self):
  99. try:
  100. id = self.kwargs.get('pk')
  101. return id
  102. except:
  103. return None
  104. def get_queryset(self):
  105. id = self.get_project()
  106. if self.request.user:
  107. if id is None:
  108. return TaskModel.objects.filter()
  109. else:
  110. return TaskModel.objects.filter( id=id)
  111. else:
  112. return TaskModel.objects.none()
  113. def get_serializer_class(self):
  114. if self.action in ['list', 'destroy','retrieve']:
  115. return TaskGetSerializer
  116. elif self.action in ['create', 'update']:
  117. return TaskPostSerializer
  118. else:
  119. return self.http_method_not_allowed(request=self.request)
  120. def create(self, request, *args, **kwargs):
  121. data = self.request.data
  122. return Response(data, status=200, headers=headers)
  123. def update(self, request, pk):
  124. qs = self.get_object()
  125. data = self.request.data
  126. serializer = self.get_serializer(qs, data=data)
  127. serializer.is_valid(raise_exception=True)
  128. serializer.save()
  129. headers = self.get_success_headers(serializer.data)
  130. return Response(serializer.data, status=200, headers=headers)
  131. class ContainerWCSViewSet(viewsets.ModelViewSet):
  132. """
  133. retrieve:
  134. Response a data list(get)
  135. list:
  136. Response a data list(all)
  137. create:
  138. Create a data line(post)
  139. delete:
  140. Delete a data line(delete)
  141. """
  142. authentication_classes = [] # 禁用所有认证类
  143. permission_classes = [AllowAny] # 允许任意访问
  144. def get_container_wcs(self, request, *args, **kwargs):
  145. data = self.request.data
  146. container = data.get('container_number')
  147. current_location = data.get('current_location')
  148. data_return = {}
  149. try:
  150. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  151. if not container_obj:
  152. data_return = {
  153. 'code': '400',
  154. 'message': '托盘编码不存在',
  155. 'data': data
  156. }
  157. return Response(data_return, status=status.HTTP_400_BAD_REQUEST)
  158. # 更新容器数据(部分更新)
  159. serializer = ContainerListPostSerializer(
  160. container_obj,
  161. data=data,
  162. partial=True # 允许部分字段更新
  163. )
  164. serializer.is_valid(raise_exception=True)
  165. serializer.save()
  166. # 检查是否已在目标位置
  167. if current_location == str(container_obj.target_location):
  168. logger.info(f"托盘 {container} 已在目标位置")
  169. data_return = {
  170. 'code': '200',
  171. 'message': '当前位置已是目标位置',
  172. 'data': data
  173. }
  174. else:
  175. current_task = ContainerWCSModel.objects.filter(
  176. container=container,
  177. tasktype='inbound'
  178. ).first()
  179. if current_task:
  180. data_return = {
  181. 'code': '200',
  182. 'message': '任务已存在,重新下发',
  183. 'data': current_task.to_dict()
  184. }
  185. else:
  186. self.generate_task(container, current_location, container_obj.target_location)
  187. current_task = ContainerWCSModel.objects.get(
  188. container=container,
  189. tasktype='inbound'
  190. )
  191. data_return = {
  192. 'code': '200',
  193. 'message': '任务下发成功',
  194. 'data': current_task.to_dict()
  195. }
  196. self.inport_update_task(current_task.id, container_obj.id)
  197. http_status = status.HTTP_200_OK if data_return['code'] == '200' else status.HTTP_400_BAD_REQUEST
  198. return Response(data_return, status=http_status)
  199. except Exception as e:
  200. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  201. return Response(
  202. {'code': '500', 'message': '服务器内部错误', 'data': None},
  203. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  204. )
  205. @transaction.atomic
  206. def generate_task(self, container, current_location, target_location):
  207. data_tosave = {
  208. 'container': container,
  209. 'current_location': current_location,
  210. 'month': timezone.now().strftime('%Y%m'),
  211. 'target_location': target_location,
  212. 'tasktype': 'inbound',
  213. 'status': 103,
  214. 'is_delete': False
  215. }
  216. # 生成唯一递增的 taskid
  217. last_task = ContainerWCSModel.objects.filter(
  218. month=data_tosave['month'],
  219. tasktype='inbound'
  220. ).order_by('-taskid').first()
  221. if last_task:
  222. last_id = int(last_task.taskid.split('-')[-1])
  223. new_id = f"{last_id + 1:04}"
  224. else:
  225. new_id = "0001"
  226. data_tosave['taskid'] = f"inbound-{data_tosave['month']}-{new_id}"
  227. logger.info(f"生成入库任务: {data_tosave['taskid']}")
  228. # 每月生成唯一递增的 taskNumber
  229. data_tosave['tasknumber'] = f"{data_tosave['month']}{new_id}"
  230. ContainerWCSModel.objects.create(**data_tosave)
  231. @transaction.atomic
  232. def inport_update_task(self, wcs_id,container_id):
  233. try:
  234. task_obj = ContainerWCSModel.objects.filter(id=wcs_id).first()
  235. if task_obj:
  236. container_detail_obj = ContainerDetailModel.objects.filter(container=container_id).all()
  237. if container_detail_obj:
  238. for detail in container_detail_obj:
  239. # 保存到数据库
  240. batch = BoundDetailModel.objects.filter(bound_batch_id=detail.batch.id).first()
  241. TaskModel.objects.create(
  242. task_wcs = task_obj,
  243. container_detail = detail,
  244. batch_detail = batch
  245. )
  246. logger.info(f"入库任务 {wcs_id} 已更新")
  247. else:
  248. logger.info(f"入库任务 {container_id} 批次不存在")
  249. else:
  250. logger.info(f"入库任务 {wcs_id} 不存在")
  251. except Exception as e:
  252. logger.error(f"处理入库任务时发生错误: {str(e)}", exc_info=True)
  253. return Response(
  254. {'code': '500', 'message': '服务器内部错误', 'data': None},
  255. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  256. )
  257. # PDA组盘入库 将扫描到的托盘编码和批次信息保存到数据库
  258. # 1. 先查询托盘对象,如果不存在,则创建托盘对象
  259. # 2. 循环处理每个批次,查询批次对象,
  260. # 3. 更新批次数据(根据业务规则)
  261. # 4. 保存到数据库
  262. # 5. 保存操作记录到数据库
  263. class ContainerDetailViewSet(viewsets.ModelViewSet):
  264. """
  265. retrieve:
  266. Response a data list(get)
  267. list:
  268. Response a data list(all)
  269. create:
  270. Create a data line(post)
  271. delete:
  272. Delete a data line(delete)
  273. """
  274. # authentication_classes = [] # 禁用所有认证类
  275. # permission_classes = [AllowAny] # 允许任意访问
  276. pagination_class = MyPageNumberPagination
  277. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  278. ordering_fields = ['id', "create_time", "update_time", ]
  279. filter_class = ContainerDetailFilter
  280. def get_project(self):
  281. try:
  282. id = self.kwargs.get('pk')
  283. return id
  284. except:
  285. return None
  286. def get_queryset(self):
  287. id = self.get_project()
  288. if self.request.user:
  289. if id is None:
  290. return ContainerDetailModel.objects.filter( is_delete=False)
  291. else:
  292. return ContainerDetailModel.objects.filter( id=id, is_delete=False)
  293. else:
  294. return ContainerDetailModel.objects.none()
  295. def get_serializer_class(self):
  296. if self.action in ['list', 'destroy','retrieve']:
  297. return ContainerDetailGetSerializer
  298. elif self.action in ['create', 'update']:
  299. return ContainerDetailPostSerializer
  300. else:
  301. return self.http_method_not_allowed(request=self.request)
  302. def create(self, request, *args, **kwargs):
  303. data = self.request.data
  304. order_month = str(timezone.now().strftime('%Y%m'))
  305. data['month'] = order_month
  306. container_code = data.get('container')
  307. batches = data.get('batches', []) # 确保有默认空列表
  308. print('扫描到的托盘编码', container_code)
  309. # 处理托盘对象
  310. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  311. if container_obj:
  312. data['container'] = container_obj.id
  313. logger.info(f"托盘 {container_code} 已存在")
  314. else:
  315. logger.info(f"托盘 {container_code} 不存在,创建托盘对象")
  316. serializer_list = ContainerListPostSerializer(data={'container_code': container_code})
  317. serializer_list.is_valid(raise_exception=True)
  318. serializer_list.save()
  319. data['container'] = serializer_list.data.get('id')
  320. # 循环处理每个批次
  321. for batch in batches:
  322. bound_number = batch.get('goods_code')
  323. goods_qty = batch.get('goods_qty')
  324. # 查询商品对象
  325. bound_obj = BoundBatchModel.objects.filter(bound_number=bound_number).first()
  326. if not bound_obj:
  327. # 如果商品不存在,返回错误,这里暂时在程序中进行提醒,后续需要改为前端弹窗提醒
  328. logger.error(f"批次 {bound_number} 不存在")
  329. # 跳出此次循环
  330. continue
  331. # return Response({"error": f"商品编码 {bound_number} 不存在"}, status=400)
  332. # 3. 更新批次数据(根据业务规则)
  333. try:
  334. last_qty = bound_obj.goods_in_qty
  335. bound_obj.goods_in_qty += batch.get("goods_qty", 0)
  336. if bound_obj.goods_in_qty >= bound_obj.goods_qty:
  337. bound_obj.goods_in_qty = bound_obj.goods_qty
  338. bound_obj.status = 1 # 批次状态为组盘完成
  339. print('批次id',bound_obj.id)
  340. bound_detail_obj = BoundDetailModel.objects.filter(bound_batch=bound_obj.id).first()
  341. if bound_detail_obj:
  342. bound_detail_obj.status = 1
  343. bound_detail_obj.save()
  344. print('入库申请id',bound_detail_obj.bound_list_id)
  345. # 入库申请全部批次入库完成
  346. bound_batch_all = BoundDetailModel.objects.filter(bound_list=bound_detail_obj.bound_list_id).all()
  347. if bound_batch_all.count() == bound_batch_all.filter(status=1).count():
  348. bound_list_obj = BoundListModel.objects.filter(id=bound_detail_obj.bound_list_id).first()
  349. print('当前状态',bound_list_obj.bound_status)
  350. bound_list_obj.bound_status = 102
  351. print('更新状态',bound_list_obj.bound_status)
  352. bound_list_obj.save()
  353. print('入库申请全部批次组盘完成')
  354. else:
  355. print('入库申请部分批次组盘完成')
  356. else:
  357. bound_obj.status = 0
  358. bound_obj.save() # 保存到数据库
  359. # 创建托盘详情记录(每个批次独立)
  360. print('新增个数',bound_obj.goods_in_qty-last_qty)
  361. if bound_obj.goods_in_qty-last_qty == goods_qty:
  362. detail_data = {
  363. "container": data['container'], # 托盘ID
  364. "batch": bound_obj.id, # 外键关联批次
  365. "goods_code": bound_obj.goods_code,
  366. "goods_desc": bound_obj.goods_desc,
  367. "goods_qty": goods_qty,
  368. "goods_weight": bound_obj.goods_weight,
  369. "status": 1,
  370. "month": data['month'],
  371. "creater": data.get('creater', 'zl') # 默认值兜底
  372. }
  373. serializer = self.get_serializer(data=detail_data)
  374. serializer.is_valid(raise_exception=True)
  375. serializer.save() # 必须保存到数据库
  376. operate_data = {
  377. "month" : data['month'],
  378. "container": data['container'], # 托盘ID
  379. "operation_type" : 'container',
  380. "batch" : bound_obj.id, # 外键关联批次
  381. "goods_code": bound_obj.goods_code,
  382. "goods_desc": bound_obj.goods_desc,
  383. "goods_qty": goods_qty,
  384. "goods_weight": bound_obj.goods_weight,
  385. "operator": data.get('creater', 'zl'), # 默认值兜底
  386. "timestamp": timezone.now(),
  387. "from_location": "container",
  388. "to_location": "container",
  389. "memo": "入库PDA组盘,pda入库"+str(bound_obj.goods_code)+"数量"+str(goods_qty)
  390. }
  391. serializer_operate = ContainerOperationPostSerializer(data=operate_data)
  392. serializer_operate.is_valid(raise_exception=True)
  393. serializer_operate.save() # 必须保存到数据库
  394. elif bound_obj.goods_in_qty-last_qty > 0:
  395. print('批次数量不一致')
  396. detail_data = {
  397. "container": data['container'], # 托盘ID
  398. "batch": bound_obj.id, # 外键关联批次
  399. "goods_code": bound_obj.goods_code,
  400. "goods_desc": bound_obj.goods_desc,
  401. "goods_qty": bound_obj.goods_in_qty-last_qty,
  402. "goods_weight": bound_obj.goods_weight,
  403. "status": 1,
  404. "month": data['month'],
  405. "creater": data.get('creater', 'zl') # 默认值兜底
  406. }
  407. serializer = self.get_serializer(data=detail_data)
  408. serializer.is_valid(raise_exception=True)
  409. serializer.save() # 必须保存到数据库
  410. operate_data = {
  411. "month" : data['month'],
  412. "container": data['container'], # 托盘ID
  413. "operation_type" : 'container',
  414. "batch" : bound_obj.id, # 外键关联批次
  415. "goods_code": bound_obj.goods_code,
  416. "goods_desc": bound_obj.goods_desc,
  417. "goods_qty": bound_obj.goods_in_qty-last_qty,
  418. "goods_weight": bound_obj.goods_weight,
  419. "operator": data.get('creater', 'zl'), # 默认值兜底
  420. "timestamp": timezone.now(),
  421. "from_location": "container",
  422. "to_location": "container",
  423. "memo": "入库PDA组盘,(数量不一致)pda入库"+str(bound_obj.goods_code)+"数量"+str(goods_qty)
  424. }
  425. serializer_operate = ContainerOperationPostSerializer(data=operate_data)
  426. serializer_operate.is_valid(raise_exception=True)
  427. serializer_operate.save() # 必须保存到数据库
  428. else :
  429. print('重复组盘')
  430. except Exception as e:
  431. print(f"更新批次 {bound_number} 失败: {str(e)}")
  432. continue
  433. # 将处理后的数据返回(或根据业务需求保存到数据库)
  434. res_data={
  435. "code": "200",
  436. "msg": "Success Create",
  437. "data": data
  438. }
  439. return Response(res_data, status=200)
  440. def update(self, request, pk):
  441. qs = self.get_object()
  442. data = self.request.data
  443. serializer = self.get_serializer(qs, data=data)
  444. serializer.is_valid(raise_exception=True)
  445. serializer.save()
  446. headers = self.get_success_headers(serializer.data)
  447. return Response(serializer.data, status=200, headers=headers)
  448. class ContainerOperateViewSet(viewsets.ModelViewSet):
  449. """
  450. retrieve:
  451. Response a data list(get)
  452. list:
  453. Response a data list(all)
  454. create:
  455. Create a data line(post)
  456. delete:
  457. Delete a data line(delete)
  458. """
  459. # authentication_classes = [] # 禁用所有认证类
  460. # permission_classes = [AllowAny] # 允许任意访问
  461. pagination_class = MyPageNumberPagination
  462. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  463. ordering_fields = ['id', "timestamp" ]
  464. filter_class = ContainerOperationFilter
  465. def get_project(self):
  466. try:
  467. id = self.kwargs.get('pk')
  468. return id
  469. except:
  470. return None
  471. def get_queryset(self):
  472. id = self.get_project()
  473. if self.request.user:
  474. if id is None:
  475. return ContainerOperationModel.objects.filter( is_delete=False)
  476. else:
  477. return ContainerOperationModel.objects.filter( id=id, is_delete=False)
  478. else:
  479. return ContainerOperationModel.objects.none()
  480. def get_serializer_class(self):
  481. if self.action in ['list', 'destroy','retrieve']:
  482. return ContainerOperationGetSerializer
  483. elif self.action in ['create', 'update']:
  484. return ContainerOperationPostSerializer
  485. else:
  486. return self.http_method_not_allowed(request=self.request)
  487. def create(self, request, *args, **kwargs):
  488. data = self.request.data
  489. serializer = self.get_serializer(data=data)
  490. serializer.is_valid(raise_exception=True)
  491. serializer.save()
  492. headers = self.get_success_headers(serializer.data)
  493. return Response(serializer.data, status=200, headers=headers)
  494. def update(self, request, pk):
  495. qs = self.get_object()
  496. data = self.request.data
  497. serializer = self.get_serializer(qs, data=data)
  498. serializer.is_valid(raise_exception=True)
  499. serializer.save()
  500. headers = self.get_success_headers(serializer.data)
  501. return Response(serializer.data, status=200, headers=headers)