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