views.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. ContainerWCSModel.objects.create(**data_tosave)
  229. @transaction.atomic
  230. def inport_update_task(self, wcs_id,container_id):
  231. try:
  232. task_obj = ContainerWCSModel.objects.filter(id=wcs_id).first()
  233. if task_obj:
  234. container_detail_obj = ContainerDetailModel.objects.filter(container=container_id).all()
  235. if container_detail_obj:
  236. for detail in container_detail_obj:
  237. # 保存到数据库
  238. batch = BoundBatchModel.objects.filter(id=detail.batch.id).first()
  239. TaskModel.objects.create(
  240. task_wcs = task_obj,
  241. container_detail = detail,
  242. )
  243. logger.info(f"入库任务 {wcs_id} 已更新")
  244. else:
  245. logger.info(f"入库任务 {container_id} 批次不存在")
  246. else:
  247. logger.info(f"入库任务 {wcs_id} 不存在")
  248. except Exception as e:
  249. logger.error(f"处理入库任务时发生错误: {str(e)}", exc_info=True)
  250. return Response(
  251. {'code': '500', 'message': '服务器内部错误', 'data': None},
  252. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  253. )
  254. # PDA组盘入库 将扫描到的托盘编码和批次信息保存到数据库
  255. # 1. 先查询托盘对象,如果不存在,则创建托盘对象
  256. # 2. 循环处理每个批次,查询批次对象,
  257. # 3. 更新批次数据(根据业务规则)
  258. # 4. 保存到数据库
  259. # 5. 保存操作记录到数据库
  260. class ContainerDetailViewSet(viewsets.ModelViewSet):
  261. """
  262. retrieve:
  263. Response a data list(get)
  264. list:
  265. Response a data list(all)
  266. create:
  267. Create a data line(post)
  268. delete:
  269. Delete a data line(delete)
  270. """
  271. # authentication_classes = [] # 禁用所有认证类
  272. # permission_classes = [AllowAny] # 允许任意访问
  273. pagination_class = MyPageNumberPagination
  274. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  275. ordering_fields = ['id', "create_time", "update_time", ]
  276. filter_class = ContainerDetailFilter
  277. def get_project(self):
  278. try:
  279. id = self.kwargs.get('pk')
  280. return id
  281. except:
  282. return None
  283. def get_queryset(self):
  284. id = self.get_project()
  285. if self.request.user:
  286. if id is None:
  287. return ContainerDetailModel.objects.filter( is_delete=False)
  288. else:
  289. return ContainerDetailModel.objects.filter( id=id, is_delete=False)
  290. else:
  291. return ContainerDetailModel.objects.none()
  292. def get_serializer_class(self):
  293. if self.action in ['list', 'destroy','retrieve']:
  294. return ContainerDetailGetSerializer
  295. elif self.action in ['create', 'update']:
  296. return ContainerDetailPostSerializer
  297. else:
  298. return self.http_method_not_allowed(request=self.request)
  299. def create(self, request, *args, **kwargs):
  300. data = self.request.data
  301. order_month = str(timezone.now().strftime('%Y%m'))
  302. data['month'] = order_month
  303. container_code = data.get('container')
  304. batches = data.get('batches', []) # 确保有默认空列表
  305. print('扫描到的托盘编码', container_code)
  306. # 处理托盘对象
  307. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  308. if container_obj:
  309. data['container'] = container_obj.id
  310. logger.info(f"托盘 {container_code} 已存在")
  311. else:
  312. logger.info(f"托盘 {container_code} 不存在,创建托盘对象")
  313. serializer_list = ContainerListPostSerializer(data={'container_code': container_code})
  314. serializer_list.is_valid(raise_exception=True)
  315. serializer_list.save()
  316. data['container'] = serializer_list.data.get('id')
  317. # 循环处理每个批次
  318. for batch in batches:
  319. bound_number = batch.get('goods_code')
  320. goods_qty = batch.get('goods_qty')
  321. # 查询商品对象
  322. bound_obj = BoundBatchModel.objects.filter(bound_number=bound_number).first()
  323. if not bound_obj:
  324. # 如果商品不存在,返回错误,这里暂时在程序中进行提醒,后续需要改为前端弹窗提醒
  325. logger.error(f"批次 {bound_number} 不存在")
  326. # 跳出此次循环
  327. continue
  328. # return Response({"error": f"商品编码 {bound_number} 不存在"}, status=400)
  329. # 3. 更新批次数据(根据业务规则)
  330. try:
  331. last_qty = bound_obj.goods_in_qty
  332. bound_obj.goods_in_qty += batch.get("goods_qty", 0)
  333. if bound_obj.goods_in_qty >= bound_obj.goods_qty:
  334. bound_obj.goods_in_qty = bound_obj.goods_qty
  335. bound_obj.status = 1 # 批次状态为组盘完成
  336. print('批次id',bound_obj.id)
  337. bound_detail_obj = BoundDetailModel.objects.filter(bound_batch=bound_obj.id).first()
  338. if bound_detail_obj:
  339. bound_detail_obj.status = 1
  340. bound_detail_obj.save()
  341. print('入库申请id',bound_detail_obj.bound_list_id)
  342. # 入库申请全部批次入库完成
  343. bound_batch_all = BoundDetailModel.objects.filter(bound_list=bound_detail_obj.bound_list_id).all()
  344. if bound_batch_all.count() == bound_batch_all.filter(status=1).count():
  345. bound_list_obj = BoundListModel.objects.filter(id=bound_detail_obj.bound_list_id).first()
  346. print('当前状态',bound_list_obj.bound_status)
  347. bound_list_obj.bound_status = 102
  348. print('更新状态',bound_list_obj.bound_status)
  349. bound_list_obj.save()
  350. print('入库申请全部批次组盘完成')
  351. else:
  352. print('入库申请部分批次组盘完成')
  353. else:
  354. bound_obj.status = 0
  355. bound_obj.save() # 保存到数据库
  356. # 创建托盘详情记录(每个批次独立)
  357. print('新增个数',bound_obj.goods_in_qty-last_qty)
  358. if bound_obj.goods_in_qty-last_qty == goods_qty:
  359. detail_data = {
  360. "container": data['container'], # 托盘ID
  361. "batch": bound_obj.id, # 外键关联批次
  362. "goods_code": bound_obj.goods_code,
  363. "goods_desc": bound_obj.goods_desc,
  364. "goods_qty": goods_qty,
  365. "goods_weight": bound_obj.goods_weight,
  366. "status": 1,
  367. "month": data['month'],
  368. "creater": data.get('creater', 'zl') # 默认值兜底
  369. }
  370. serializer = self.get_serializer(data=detail_data)
  371. serializer.is_valid(raise_exception=True)
  372. serializer.save() # 必须保存到数据库
  373. operate_data = {
  374. "month" : data['month'],
  375. "container": data['container'], # 托盘ID
  376. "operation_type" : 'container',
  377. "batch" : bound_obj.id, # 外键关联批次
  378. "goods_code": bound_obj.goods_code,
  379. "goods_desc": bound_obj.goods_desc,
  380. "goods_qty": goods_qty,
  381. "goods_weight": bound_obj.goods_weight,
  382. "operator": data.get('creater', 'zl'), # 默认值兜底
  383. "timestamp": timezone.now(),
  384. "from_location": "container",
  385. "to_location": "container",
  386. "memo": "入库PDA组盘,pda入库"+str(bound_obj.goods_code)+"数量"+str(goods_qty)
  387. }
  388. serializer_operate = ContainerOperationPostSerializer(data=operate_data)
  389. serializer_operate.is_valid(raise_exception=True)
  390. serializer_operate.save() # 必须保存到数据库
  391. elif bound_obj.goods_in_qty-last_qty > 0:
  392. print('批次数量不一致')
  393. detail_data = {
  394. "container": data['container'], # 托盘ID
  395. "batch": bound_obj.id, # 外键关联批次
  396. "goods_code": bound_obj.goods_code,
  397. "goods_desc": bound_obj.goods_desc,
  398. "goods_qty": bound_obj.goods_in_qty-last_qty,
  399. "goods_weight": bound_obj.goods_weight,
  400. "status": 1,
  401. "month": data['month'],
  402. "creater": data.get('creater', 'zl') # 默认值兜底
  403. }
  404. serializer = self.get_serializer(data=detail_data)
  405. serializer.is_valid(raise_exception=True)
  406. serializer.save() # 必须保存到数据库
  407. operate_data = {
  408. "month" : data['month'],
  409. "container": data['container'], # 托盘ID
  410. "operation_type" : 'container',
  411. "batch" : bound_obj.id, # 外键关联批次
  412. "goods_code": bound_obj.goods_code,
  413. "goods_desc": bound_obj.goods_desc,
  414. "goods_qty": bound_obj.goods_in_qty-last_qty,
  415. "goods_weight": bound_obj.goods_weight,
  416. "operator": data.get('creater', 'zl'), # 默认值兜底
  417. "timestamp": timezone.now(),
  418. "from_location": "container",
  419. "to_location": "container",
  420. "memo": "入库PDA组盘,(数量不一致)pda入库"+str(bound_obj.goods_code)+"数量"+str(goods_qty)
  421. }
  422. serializer_operate = ContainerOperationPostSerializer(data=operate_data)
  423. serializer_operate.is_valid(raise_exception=True)
  424. serializer_operate.save() # 必须保存到数据库
  425. else :
  426. print('重复组盘')
  427. except Exception as e:
  428. print(f"更新批次 {bound_number} 失败: {str(e)}")
  429. continue
  430. # 将处理后的数据返回(或根据业务需求保存到数据库)
  431. res_data={
  432. "code": "200",
  433. "msg": "Success Create",
  434. "data": data
  435. }
  436. return Response(res_data, status=200)
  437. def update(self, request, pk):
  438. qs = self.get_object()
  439. data = self.request.data
  440. serializer = self.get_serializer(qs, data=data)
  441. serializer.is_valid(raise_exception=True)
  442. serializer.save()
  443. headers = self.get_success_headers(serializer.data)
  444. return Response(serializer.data, status=200, headers=headers)
  445. class ContainerOperateViewSet(viewsets.ModelViewSet):
  446. """
  447. retrieve:
  448. Response a data list(get)
  449. list:
  450. Response a data list(all)
  451. create:
  452. Create a data line(post)
  453. delete:
  454. Delete a data line(delete)
  455. """
  456. # authentication_classes = [] # 禁用所有认证类
  457. # permission_classes = [AllowAny] # 允许任意访问
  458. pagination_class = MyPageNumberPagination
  459. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  460. ordering_fields = ['id', "timestamp" ]
  461. filter_class = ContainerOperationFilter
  462. def get_project(self):
  463. try:
  464. id = self.kwargs.get('pk')
  465. return id
  466. except:
  467. return None
  468. def get_queryset(self):
  469. id = self.get_project()
  470. if self.request.user:
  471. if id is None:
  472. return ContainerOperationModel.objects.filter( is_delete=False)
  473. else:
  474. return ContainerOperationModel.objects.filter( id=id, is_delete=False)
  475. else:
  476. return ContainerOperationModel.objects.none()
  477. def get_serializer_class(self):
  478. if self.action in ['list', 'destroy','retrieve']:
  479. return ContainerOperationGetSerializer
  480. elif self.action in ['create', 'update']:
  481. return ContainerOperationPostSerializer
  482. else:
  483. return self.http_method_not_allowed(request=self.request)
  484. def create(self, request, *args, **kwargs):
  485. data = self.request.data
  486. serializer = self.get_serializer(data=data)
  487. serializer.is_valid(raise_exception=True)
  488. serializer.save()
  489. headers = self.get_success_headers(serializer.data)
  490. return Response(serializer.data, status=200, headers=headers)
  491. def update(self, request, pk):
  492. qs = self.get_object()
  493. data = self.request.data
  494. serializer = self.get_serializer(qs, data=data)
  495. serializer.is_valid(raise_exception=True)
  496. serializer.save()
  497. headers = self.get_success_headers(serializer.data)
  498. return Response(serializer.data, status=200, headers=headers)