views.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. from wsgiref import headers
  2. from rest_framework.views import APIView
  3. from rest_framework import viewsets
  4. from utils.page import MyPageNumberPagination
  5. from rest_framework.filters import OrderingFilter
  6. from django_filters.rest_framework import DjangoFilterBackend
  7. from rest_framework.response import Response
  8. from django.utils import timezone
  9. import requests
  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,OutBoundDetailModel
  15. from bin.views import LocationAllocation,base_location
  16. from bin.models import LocationModel,LocationContainerLink,LocationGroupModel
  17. from bound.models import BoundBatchModel
  18. from .serializers import ContainerDetailGetSerializer,ContainerDetailPostSerializer
  19. from .serializers import ContainerListGetSerializer,ContainerListPostSerializer
  20. from .serializers import ContainerOperationGetSerializer,ContainerOperationPostSerializer
  21. from .serializers import TaskGetSerializer,TaskPostSerializer
  22. from .filter import ContainerDetailFilter,ContainerListFilter,ContainerOperationFilter,TaskFilter
  23. from rest_framework.permissions import AllowAny
  24. import threading
  25. from django.db import close_old_connections
  26. logger = logging.getLogger(__name__)
  27. class ContainerListViewSet(viewsets.ModelViewSet):
  28. """
  29. retrieve:
  30. Response a data list(get)
  31. list:
  32. Response a data list(all)
  33. create:
  34. Create a data line(post)
  35. delete:
  36. Delete a data line(delete)
  37. """
  38. # authentication_classes = [] # 禁用所有认证类
  39. # permission_classes = [AllowAny] # 允许任意访问
  40. pagination_class = MyPageNumberPagination
  41. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  42. ordering_fields = ['id', "create_time", "update_time", ]
  43. filter_class = ContainerListFilter
  44. def get_project(self):
  45. try:
  46. id = self.kwargs.get('pk')
  47. return id
  48. except:
  49. return None
  50. def get_queryset(self):
  51. id = self.get_project()
  52. if self.request.user:
  53. if id is None:
  54. return ContainerListModel.objects.filter()
  55. else:
  56. return ContainerListModel.objects.filter(id=id)
  57. else:
  58. return ContainerListModel.objects.none()
  59. def get_serializer_class(self):
  60. if self.action in ['list', 'destroy','retrieve']:
  61. return ContainerListGetSerializer
  62. elif self.action in ['create', 'update']:
  63. return ContainerListPostSerializer
  64. else:
  65. return self.http_method_not_allowed(request=self.request)
  66. def create(self, request, *args, **kwargs):
  67. # 创建托盘:托盘码五位数字(唯一),当前库位,目标库位,状态,最后操作时间
  68. container_all = ContainerListModel.objects.all().order_by('container_code')
  69. if container_all.count() == 0:
  70. container_code = 12345
  71. else:
  72. container_code = container_all.last().container_code + 1
  73. container_obj = ContainerListModel.objects.create(
  74. container_code=container_code,
  75. current_location='N/A',
  76. target_location='N/A',
  77. status=0,
  78. last_operation=timezone.now()
  79. )
  80. serializer = ContainerListGetSerializer(container_obj)
  81. headers = self.get_success_headers(serializer.data)
  82. return Response(serializer.data, status=201, headers=headers)
  83. def update(self, request, pk):
  84. qs = self.get_object()
  85. data = self.request.data
  86. serializer = self.get_serializer(qs, data=data)
  87. serializer.is_valid(raise_exception=True)
  88. serializer.save()
  89. headers = self.get_success_headers(serializer.data)
  90. return Response(serializer.data, status=200, headers=headers)
  91. class TaskViewSet(viewsets.ModelViewSet):
  92. """
  93. retrieve:
  94. Response a data list(get)
  95. list:
  96. Response a data list(all)
  97. create:
  98. Create a data line(post)
  99. delete:
  100. Delete a data line(delete)
  101. """
  102. pagination_class = MyPageNumberPagination
  103. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  104. ordering_fields = ['id', "create_time", "update_time", ]
  105. filter_class = TaskFilter
  106. def get_project(self):
  107. try:
  108. id = self.kwargs.get('pk')
  109. return id
  110. except:
  111. return None
  112. def get_queryset(self):
  113. id = self.get_project()
  114. if self.request.user:
  115. if id is None:
  116. return TaskModel.objects.filter()
  117. else:
  118. return TaskModel.objects.filter(id=id)
  119. else:
  120. return TaskModel.objects.none()
  121. def get_serializer_class(self):
  122. if self.action in ['list', 'destroy','retrieve']:
  123. return TaskGetSerializer
  124. elif self.action in ['create', 'update']:
  125. return TaskPostSerializer
  126. else:
  127. return self.http_method_not_allowed(request=self.request)
  128. def create(self, request, *args, **kwargs):
  129. data = self.request.data
  130. return Response(data, status=200, headers=headers)
  131. def update(self, request, pk):
  132. qs = self.get_object()
  133. data = self.request.data
  134. serializer = self.get_serializer(qs, data=data)
  135. serializer.is_valid(raise_exception=True)
  136. serializer.save()
  137. headers = self.get_success_headers(serializer.data)
  138. return Response(serializer.data, status=200, headers=headers)
  139. class TaskRollbackMixin:
  140. @transaction.atomic
  141. def rollback_task(self, request, task_id, *args, **kwargs):
  142. """
  143. 撤销入库任务并回滚相关状态
  144. """
  145. try:
  146. # 获取任务实例并锁定数据库记录
  147. task = ContainerWCSModel.objects.select_for_update().get(taskid=task_id)
  148. container_code = task.container
  149. target_location = task.target_location
  150. batch = task.batch
  151. # 初始化库位分配器
  152. allocator = LocationAllocation()
  153. # ==================== 库位状态回滚 ====================
  154. # 解析目标库位信息(格式:仓库代码-行-列-层)
  155. try:
  156. warehouse_code, row, col, layer = target_location.split('-')
  157. location = LocationModel.objects.get(
  158. warehouse_code=warehouse_code,
  159. row=int(row),
  160. col=int(col),
  161. layer=int(layer)
  162. )
  163. # 回滚库位状态到可用状态
  164. allocator.update_location_status(location.location_code, 'available')
  165. # 更新库位组状态(需要根据实际逻辑实现)
  166. allocator.update_location_group_status(location.location_code)
  167. # 解除库位与托盘的关联
  168. allocator.update_location_container_link(location.location_code, None)
  169. # 清除库位组的批次关联
  170. allocator.update_location_group_batch(location, None)
  171. except (ValueError, LocationModel.DoesNotExist) as e:
  172. logger.error(f"库位解析失败: {str(e)}")
  173. raise Exception("关联库位信息无效")
  174. # ==================== 批次状态回滚 ====================
  175. if batch:
  176. # 将批次状态恢复为未处理状态(假设原状态为1)
  177. allocator.update_batch_status(batch.bound_number, '1')
  178. # ==================== 容器状态回滚 ====================
  179. container_obj = ContainerListModel.objects.get(container_code=container_code)
  180. # 恢复容器详细状态为初始状态(假设原状态为1)
  181. allocator.update_container_detail_status(container_code, 1)
  182. # 恢复容器的目标位置为当前所在位置
  183. container_obj.target_location = task.current_location
  184. container_obj.save()
  185. # ==================== 删除任务记录 ====================
  186. task.delete()
  187. # ==================== 其他关联清理 ====================
  188. # 如果有其他关联数据(如inport_update_task的操作),在此处添加清理逻辑
  189. return Response(
  190. {'code': '200', 'message': '任务回滚成功', 'data': None},
  191. status=status.HTTP_200_OK
  192. )
  193. except ContainerWCSModel.DoesNotExist:
  194. logger.warning(f"任务不存在: {task_id}")
  195. return Response(
  196. {'code': '404', 'message': '任务不存在', 'data': None},
  197. status=status.HTTP_404_NOT_FOUND
  198. )
  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. class ContainerWCSViewSet(viewsets.ModelViewSet):
  206. """
  207. retrieve:
  208. Response a data list(get)
  209. list:
  210. Response a data list(all)
  211. create:
  212. Create a data line(post)
  213. delete:
  214. Delete a data line(delete)
  215. """
  216. authentication_classes = [] # 禁用所有认证类
  217. permission_classes = [AllowAny] # 允许任意访问
  218. def get_container_wcs(self, request, *args, **kwargs):
  219. data = self.request.data
  220. container = data.get('container_number')
  221. current_location = data.get('current_location')
  222. logger.info(f"请求托盘:{container},请求位置:{current_location}")
  223. data_return = {}
  224. try:
  225. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  226. if not container_obj:
  227. data_return = {
  228. 'code': '400',
  229. 'message': '托盘编码不存在',
  230. 'data': data
  231. }
  232. return Response(data_return, status=status.HTTP_400_BAD_REQUEST)
  233. # 更新容器数据(部分更新)
  234. serializer = ContainerListPostSerializer(
  235. container_obj,
  236. data=data,
  237. partial=True # 允许部分字段更新
  238. )
  239. serializer.is_valid(raise_exception=True)
  240. serializer.save()
  241. # 检查是否已在目标位置
  242. if current_location == str(container_obj.target_location) and current_location!= '203' and current_location!= '103':
  243. logger.info(f"托盘 {container} 已在目标位置")
  244. data_return = {
  245. 'code': '200',
  246. 'message': '当前位置已是目标位置',
  247. 'data': data
  248. }
  249. else:
  250. current_task = ContainerWCSModel.objects.filter(
  251. container=container,
  252. tasktype='inbound',
  253. working = 1,
  254. ).exclude(status=300).first()
  255. if current_task:
  256. data_return = {
  257. 'code': '200',
  258. 'message': '任务已存在,重新下发',
  259. 'data': current_task.to_dict()
  260. }
  261. else:
  262. # 库位分配
  263. container_code = container
  264. print(f"开始生成库位,托盘编码:{container_code}")
  265. allocator = LocationAllocation() # 创建实例
  266. location_list_cnumber = allocator.get_location_by_status(container_code, current_location) # 获取库位列表
  267. if not location_list_cnumber:
  268. print("❌ 通用库位获取失败,请检查托盘编码")
  269. return
  270. print(f"[1]库位:{location_list_cnumber}")
  271. update_location_status = allocator.update_location_status(location_list_cnumber.location_code, 'reserved') # 更新库位状态
  272. if not update_location_status:
  273. print("❌ 库位状态更新失败,请检查托盘编码")
  274. return
  275. print(f"[2]发送任务,库位状态更新成功!")
  276. update_location_group_status = allocator.update_location_group_status(location_list_cnumber.location_code) # 更新库位组状态
  277. if not update_location_group_status:
  278. print("❌ 库位组状态更新失败,请检查托盘编码")
  279. return
  280. print(f"[3]库位组状态更新成功!")
  281. update_batch_status = allocator.update_batch_status(container_code, '2') # 更新批次状态
  282. if not update_batch_status:
  283. print("❌ 批次状态更新失败,请检查批次号")
  284. return
  285. print(f"[4]批次状态更新成功!")
  286. update_location_group_batch = allocator.update_location_group_batch(location_list_cnumber, container_code) # 更新库位组的批次
  287. if not update_location_group_batch:
  288. print("❌ 库位组批次更新失败,请检查托盘编码")
  289. return
  290. print(f"[5]库位组批次更新成功!")
  291. update_location_container_link = allocator.update_location_container_link(location_list_cnumber.location_code, container_code) # 更新库位和托盘的关联关系
  292. if not update_location_container_link:
  293. print("❌ 库位和托盘的关联关系更新失败,请检查托盘编码")
  294. return
  295. print(f"[7]库位和托盘的关联关系更新成功!")
  296. update_location_container_detail = allocator.update_container_detail_status(container_code,2) # 更新库位和托盘的关联关系
  297. if not update_location_container_detail:
  298. print("❌ 库位和托盘的关联关系更新失败,请检查托盘编码")
  299. return
  300. print(f"[8]托盘的关联关系更新成功!")
  301. allocation_target_location = (
  302. location_list_cnumber.warehouse_code + '-'
  303. + f"{int(location_list_cnumber.row):02d}" + '-'
  304. + f"{int(location_list_cnumber.col):02d}" + '-'
  305. + f"{int(location_list_cnumber.layer):02d}"
  306. )
  307. batch_id = allocator.get_batch(container_code)
  308. self.generate_task(container, current_location, allocation_target_location,batch_id,location_list_cnumber.c_number) # 生成任务
  309. current_task = ContainerWCSModel.objects.get(
  310. container=container,
  311. tasktype='inbound',
  312. working=1,
  313. )
  314. batch_obj = BoundBatchModel.objects.filter(bound_number=batch_id).first()
  315. ContainerOperationModel.objects.create(
  316. month = int(timezone.now().strftime("%Y%m")),
  317. container = container_obj,
  318. goods_code = batch_obj.goods_code,
  319. goods_desc = batch_obj.goods_desc,
  320. operation_type ="inbound",
  321. batch_id = batch_obj.id,
  322. goods_qty = batch_obj.goods_qty,
  323. goods_weight = batch_obj.goods_qty,
  324. from_location = container_obj.current_location,
  325. to_location= allocation_target_location,
  326. timestamp=timezone.now(),
  327. operator="WMS",
  328. memo=f"WCS入库: 批次: {batch_id}, 数量: {batch_obj.goods_qty}"
  329. )
  330. data_return = {
  331. 'code': '200',
  332. 'message': '任务下发成功',
  333. 'data': current_task.to_dict()
  334. }
  335. container_obj.target_location = allocation_target_location
  336. container_obj.save()
  337. self.inport_update_task(current_task.id, container_obj.id)
  338. http_status = status.HTTP_200_OK if data_return['code'] == '200' else status.HTTP_400_BAD_REQUEST
  339. return Response(data_return, status=http_status)
  340. except Exception as e:
  341. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  342. return Response(
  343. {'code': '500', 'message': '服务器内部错误', 'data': None},
  344. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  345. )
  346. @transaction.atomic
  347. def generate_task(self, container, current_location, target_location,batch_id,location_c_number):
  348. batch = BoundBatchModel.objects.filter(bound_number=batch_id).first()
  349. batch_detail = BoundDetailModel.objects.filter(bound_batch=batch).first()
  350. if not batch:
  351. logger.error(f"批次号 {batch_id} 不存在")
  352. return False
  353. data_tosave = {
  354. 'container': container,
  355. 'batch': batch,
  356. 'batch_out': None,
  357. 'bound_list': batch_detail.bound_list,
  358. 'sequence': 1,
  359. 'order_number' :location_c_number,
  360. 'priority': 1,
  361. 'current_location': current_location,
  362. 'month': timezone.now().strftime('%Y%m'),
  363. 'target_location': target_location,
  364. 'tasktype': 'inbound',
  365. 'status': 103,
  366. 'is_delete': False
  367. }
  368. # 生成唯一递增的 taskid
  369. last_task = ContainerWCSModel.objects.filter(
  370. month=data_tosave['month'],
  371. ).order_by('-tasknumber').first()
  372. if last_task:
  373. number_id = last_task.tasknumber + 1
  374. new_id = f"{number_id:05d}"
  375. else:
  376. new_id = "00001"
  377. number_id = f"{data_tosave['month']}{new_id}"
  378. data_tosave['taskid'] = f"inbound-{data_tosave['month']}-{new_id}"
  379. logger.info(f"生成入库任务: {data_tosave['taskid']}")
  380. # 每月生成唯一递增的 taskNumber
  381. data_tosave['tasknumber'] = number_id
  382. ContainerWCSModel.objects.create(**data_tosave)
  383. def update_container_wcs(self, request, *args, **kwargs):
  384. data = self.request.data
  385. logger.info(f"请求托盘:{data.get('container_number')}, 请求位置:{data.get('current_location')}, 任务号:{data.get('taskNumber')}")
  386. try:
  387. # 前置校验
  388. container_obj, error_response = self.validate_container(data)
  389. if error_response:
  390. return error_response
  391. # 更新容器数据
  392. if not self.update_container_data(container_obj, data):
  393. return Response(
  394. {'code': '400', 'message': '数据更新失败', 'data': data},
  395. status=status.HTTP_400_BAD_REQUEST
  396. )
  397. # 处理位置逻辑
  398. task = ContainerWCSModel.objects.filter(
  399. container=container_obj.container_code,
  400. tasktype='inbound'
  401. ).first()
  402. if self.is_already_at_target(container_obj, data.get('current_location')):
  403. return self.handle_target_reached(container_obj, data)
  404. elif task:
  405. data_return = {
  406. 'code': '200',
  407. 'message': '任务已存在,重新下发',
  408. 'data': task.to_dict()
  409. }
  410. return Response(data_return, status=status.HTTP_200_OK)
  411. else:
  412. return self.handle_new_allocation(container_obj, data)
  413. except Exception as e:
  414. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  415. return Response({'code': '500', 'message': '服务器内部错误', 'data': None},
  416. status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  417. # ---------- 辅助函数 ----------
  418. def validate_container(self, data):
  419. """验证容器是否存在"""
  420. container = data.get('container_number')
  421. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  422. if not container_obj:
  423. return None, Response({
  424. 'code': '400',
  425. 'message': '托盘编码不存在',
  426. 'data': data
  427. }, status=status.HTTP_400_BAD_REQUEST)
  428. return container_obj, None
  429. def update_container_data(self, container_obj, data):
  430. """更新容器数据"""
  431. serializer = ContainerListPostSerializer(
  432. container_obj,
  433. data=data,
  434. partial=True
  435. )
  436. if serializer.is_valid():
  437. serializer.save()
  438. return True
  439. return False
  440. def is_already_at_target(self, container_obj, current_location):
  441. """检查是否已在目标位置"""
  442. return current_location == str(container_obj.target_location)
  443. def handle_target_reached(self, container_obj, data):
  444. """处理已到达目标位置的逻辑"""
  445. logger.info(f"托盘 {container_obj.container_code} 已在目标位置")
  446. task = self.get_task_by_tasknumber(data)
  447. self.update_pressure_values(task, container_obj)
  448. task = self.process_task_completion(data)
  449. if not task:
  450. return Response({'code': '400', 'message': '任务不存在', 'data': data},
  451. status=status.HTTP_400_BAD_REQUEST)
  452. if task and task.tasktype == 'inbound':
  453. self.update_storage_system(container_obj)
  454. if task and task.tasktype == 'outbound' and task.status == 300:
  455. success = self.handle_outbound_completion(container_obj, task)
  456. if not success:
  457. return Response({'code': '500', 'message': '出库状态更新失败', 'data': None},
  458. status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  459. OutboundService.process_next_task()
  460. return Response({
  461. 'code': '200',
  462. 'message': '当前位置已是目标位置',
  463. 'data': data
  464. }, status=status.HTTP_200_OK)
  465. def get_task_by_tasknumber(self, data):
  466. taskNumber = data.get('taskNumber') + 20000000000
  467. task = ContainerWCSModel.objects.filter(tasknumber=taskNumber).first()
  468. if task:
  469. return task
  470. else:
  471. return None
  472. def process_task_completion(self, data):
  473. """处理任务完成状态"""
  474. taskNumber = data.get('taskNumber') + 20000000000
  475. task = ContainerWCSModel.objects.filter(tasknumber=taskNumber).first()
  476. if task:
  477. task.status = 300
  478. task.message = '任务已完成'
  479. task.working = 0
  480. task.save()
  481. return task
  482. def update_pressure_values(self, task, container_obj):
  483. """更新压力值计算"""
  484. if task and task.tasktype in ['inbound']:
  485. base_location_obj = base_location.objects.get(id=1)
  486. layer = int(container_obj.target_location.split('-')[-1])
  487. pressure_field = f"layer{layer}_pressure"
  488. logger.info(f"更新压力值,压力字段:{pressure_field}")
  489. current_pressure = getattr(base_location_obj, pressure_field, 0)
  490. updated_pressure = max(current_pressure - task.working, 0)
  491. setattr(base_location_obj, pressure_field, updated_pressure)
  492. base_location_obj.save()
  493. def update_storage_system(self, container_obj):
  494. """更新仓储系统状态"""
  495. allocator = LocationAllocation()
  496. location_code = self.get_location_code(container_obj.target_location)
  497. # 链式更新操作
  498. update_operations = [
  499. (allocator.update_location_status, location_code, 'occupied'),
  500. (allocator.update_location_container_link, location_code, container_obj.container_code),
  501. (allocator.update_container_detail_status, container_obj.container_code, 2)
  502. ]
  503. for func, *args in update_operations:
  504. if not func(*args):
  505. logger.error(f"操作失败: {func.__name__}")
  506. return False
  507. return True
  508. def get_location_code(self, target_location):
  509. """从目标位置解析获取位置编码"""
  510. parts = target_location.split('-')
  511. coordinate = f"{int(parts[1])}-{int(parts[2])}-{int(parts[3])}"
  512. return LocationModel.objects.filter(coordinate=coordinate).first().location_code
  513. def handle_new_allocation(self, container_obj, data):
  514. """处理新库位分配逻辑"""
  515. allocator = LocationAllocation()
  516. container_code = container_obj.container_code
  517. # 获取并验证库位分配
  518. location = allocator.get_location_by_status(container_code, data.get('current_location'))
  519. if not location or not self.perform_initial_allocation(allocator, location, container_code):
  520. return Response({'code': '400', 'message': '库位分配失败', 'data': data},
  521. status=status.HTTP_400_BAD_REQUEST)
  522. # 生成目标位置并更新容器
  523. target_location = self.generate_target_location(location)
  524. container_obj.target_location = target_location
  525. container_obj.save()
  526. # 创建任务并返回响应
  527. task = self.create_inbound_task(container_code, data, target_location, location)
  528. return Response({
  529. 'code': '200',
  530. 'message': '任务下发成功',
  531. 'data': task.to_dict()
  532. }, status=status.HTTP_200_OK)
  533. def perform_initial_allocation(self, allocator, location, container_code):
  534. """执行初始库位分配操作"""
  535. operations = [
  536. (allocator.update_location_status, location.location_code, 'reserved'),
  537. (allocator.update_location_group_status, location.location_code),
  538. (allocator.update_batch_status, container_code, '2'),
  539. (allocator.update_location_group_batch, location, container_code),
  540. (allocator.update_location_container_link, location.location_code, container_code),
  541. (allocator.update_container_detail_status, container_code, 2)
  542. ]
  543. for func, *args in operations:
  544. if not func(*args):
  545. logger.error(f"分配操作失败: {func.__name__}")
  546. return False
  547. return True
  548. def generate_target_location(self, location):
  549. """生成目标位置字符串"""
  550. return (
  551. f"{location.warehouse_code}-"
  552. f"{int(location.row):02d}-"
  553. f"{int(location.col):02d}-"
  554. f"{int(location.layer):02d}"
  555. )
  556. def create_inbound_task(self, container_code, data, target_location, location):
  557. """创建入库任务"""
  558. batch_id = LocationAllocation().get_batch(container_code)
  559. self.generate_task(
  560. container_code,
  561. data.get('current_location'),
  562. target_location,
  563. batch_id,
  564. location.c_number
  565. )
  566. task = ContainerWCSModel.objects.get(container=container_code, tasktype='inbound')
  567. self.inport_update_task(task.id, container_code)
  568. return task
  569. @transaction.atomic
  570. def inport_update_task(self, wcs_id,container_id):
  571. try:
  572. task_obj = ContainerWCSModel.objects.filter(id=wcs_id).first()
  573. if task_obj:
  574. container_detail_obj = ContainerDetailModel.objects.filter(container=container_id).all()
  575. if container_detail_obj:
  576. for detail in container_detail_obj:
  577. # 保存到数据库
  578. batch = BoundDetailModel.objects.filter(bound_batch_id=detail.batch.id).first()
  579. TaskModel.objects.create(
  580. task_wcs = task_obj,
  581. container_detail = detail,
  582. batch_detail = batch
  583. )
  584. logger.info(f"入库任务 {wcs_id} 已更新")
  585. else:
  586. logger.info(f"入库任务 {container_id} 批次不存在")
  587. else:
  588. logger.info(f"入库任务 {wcs_id} 不存在")
  589. except Exception as e:
  590. logger.error(f"处理入库任务时发生错误: {str(e)}", exc_info=True)
  591. return Response(
  592. {'code': '500', 'message': '服务器内部错误', 'data': None},
  593. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  594. )
  595. def handle_outbound_completion(self, container_obj, task):
  596. """处理出库完成后的库位释放和状态更新"""
  597. try:
  598. allocator = LocationAllocation()
  599. location_task = task.current_location
  600. location_row = location_task.split('-')[1]
  601. location_col = location_task.split('-')[2]
  602. location_layer = location_task.split('-')[3]
  603. location= LocationModel.objects.filter(row=location_row, col=location_col, layer=location_layer).first()
  604. location_code = location.location_code
  605. # 事务确保原子性
  606. with transaction.atomic():
  607. # 解除库位与托盘的关联
  608. if not allocator.release_location(location_code):
  609. raise Exception("解除库位关联失败")
  610. # 更新库位状态为可用
  611. if not allocator.update_location_status(location_code, 'available'):
  612. raise Exception("库位状态更新失败")
  613. # 更新库位组的统计信息
  614. self.handle_group_location_status(location_code, location.location_group)
  615. # 更新容器状态为已出库(假设状态3表示已出库)
  616. container_obj.status = 3
  617. container_obj.save()
  618. return True
  619. except Exception as e:
  620. logger.error(f"出库完成处理失败: {str(e)}")
  621. return False
  622. def handle_group_location_status(self,location_code,location_group):
  623. """
  624. 处理库位组和库位的关联关系
  625. :param location_code: 库位编码
  626. :param location_group: 库位组编码
  627. :return:
  628. """
  629. # 1. 获取库位空闲状态的库位数目
  630. location_obj_number = LocationModel.objects.filter(
  631. location_group=location_group,
  632. status='available'
  633. ).all().count()
  634. # 2. 获取库位组对象
  635. logger.info(f"库位组 {location_group} 下的库位数目:{location_obj_number}")
  636. # 1. 获取库位和库位组的关联关系
  637. location_group_obj = LocationGroupModel.objects.filter(
  638. group_code=location_group
  639. ).first()
  640. if not location_group_obj:
  641. logger.info(f"库位组 {location_group} 不存在")
  642. return None
  643. else:
  644. if location_obj_number == 0:
  645. # 库位组库位已满,更新库位组状态为full
  646. location_group_obj.status = 'full'
  647. location_group_obj.save()
  648. elif location_obj_number < location_group_obj.max_capacity:
  649. location_group_obj.status = 'occupied'
  650. location_group_obj.save()
  651. else:
  652. location_group_obj.status = 'available'
  653. location_group_obj.current_batch = ''
  654. location_group_obj.current_goods_code = ''
  655. location_group_obj.save()
  656. # PDA组盘入库 将扫描到的托盘编码和批次信息保存到数据库
  657. # 1. 先查询托盘对象,如果不存在,则创建托盘对象
  658. # 2. 循环处理每个批次,查询批次对象,
  659. # 3. 更新批次数据(根据业务规则)
  660. # 4. 保存到数据库
  661. # 5. 保存操作记录到数据库
  662. class ContainerDetailViewSet(viewsets.ModelViewSet):
  663. """
  664. retrieve:
  665. Response a data list(get)
  666. list:
  667. Response a data list(all)
  668. create:
  669. Create a data line(post)
  670. delete:
  671. Delete a data line(delete)
  672. """
  673. # authentication_classes = [] # 禁用所有认证类
  674. # permission_classes = [AllowAny] # 允许任意访问
  675. pagination_class = MyPageNumberPagination
  676. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  677. ordering_fields = ['id', "create_time", "update_time", ]
  678. filter_class = ContainerDetailFilter
  679. def get_project(self):
  680. try:
  681. id = self.kwargs.get('pk')
  682. return id
  683. except:
  684. return None
  685. def get_queryset(self):
  686. id = self.get_project()
  687. if self.request.user:
  688. if id is None:
  689. return ContainerDetailModel.objects.filter( is_delete=False)
  690. else:
  691. return ContainerDetailModel.objects.filter( id=id, is_delete=False)
  692. else:
  693. return ContainerDetailModel.objects.none()
  694. def get_serializer_class(self):
  695. if self.action in ['list', 'destroy','retrieve']:
  696. return ContainerDetailGetSerializer
  697. elif self.action in ['create', 'update']:
  698. return ContainerDetailPostSerializer
  699. else:
  700. return self.http_method_not_allowed(request=self.request)
  701. def create(self, request, *args, **kwargs):
  702. data = self.request.data
  703. from .container_operate import ContainerService
  704. ContainerService.create_container_operation(data,logger=logger)
  705. # 将处理后的数据返回(或根据业务需求保存到数据库)
  706. res_data={
  707. "code": "200",
  708. "msg": "Success Create",
  709. "data": data
  710. }
  711. return Response(res_data, status=200)
  712. def update(self, request, pk):
  713. qs = self.get_object()
  714. data = self.request.data
  715. serializer = self.get_serializer(qs, data=data)
  716. serializer.is_valid(raise_exception=True)
  717. serializer.save()
  718. headers = self.get_success_headers(serializer.data)
  719. return Response(serializer.data, status=200, headers=headers)
  720. class ContainerOperateViewSet(viewsets.ModelViewSet):
  721. """
  722. retrieve:
  723. Response a data list(get)
  724. list:
  725. Response a data list(all)
  726. create:
  727. Create a data line(post)
  728. delete:
  729. Delete a data line(delete)
  730. """
  731. # authentication_classes = [] # 禁用所有认证类
  732. # permission_classes = [AllowAny] # 允许任意访问
  733. pagination_class = MyPageNumberPagination
  734. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  735. ordering_fields = ['id', "timestamp" ]
  736. filter_class = ContainerOperationFilter
  737. def get_project(self):
  738. try:
  739. id = self.kwargs.get('pk')
  740. return id
  741. except:
  742. return None
  743. def get_queryset(self):
  744. id = self.get_project()
  745. if self.request.user:
  746. if id is None:
  747. return ContainerOperationModel.objects.filter( is_delete=False)
  748. else:
  749. return ContainerOperationModel.objects.filter( id=id, is_delete=False)
  750. else:
  751. return ContainerOperationModel.objects.none()
  752. def get_serializer_class(self):
  753. if self.action in ['list', 'destroy','retrieve']:
  754. return ContainerOperationGetSerializer
  755. elif self.action in ['create', 'update']:
  756. return ContainerOperationPostSerializer
  757. else:
  758. return self.http_method_not_allowed(request=self.request)
  759. def create(self, request, *args, **kwargs):
  760. data = self.request.data
  761. serializer = self.get_serializer(data=data)
  762. serializer.is_valid(raise_exception=True)
  763. serializer.save()
  764. headers = self.get_success_headers(serializer.data)
  765. return Response(serializer.data, status=200, headers=headers)
  766. def update(self, request, pk):
  767. qs = self.get_object()
  768. data = self.request.data
  769. serializer = self.get_serializer(qs, data=data)
  770. serializer.is_valid(raise_exception=True)
  771. serializer.save()
  772. headers = self.get_success_headers(serializer.data)
  773. return Response(serializer.data, status=200, headers=headers)
  774. class OutboundService:
  775. @staticmethod
  776. def generate_task_id():
  777. """生成唯一任务ID(格式: outbound-年月-顺序号)"""
  778. month = timezone.now().strftime("%Y%m")
  779. last_task = ContainerWCSModel.objects.filter(
  780. tasktype='outbound',
  781. month=int(month)
  782. ).order_by('-sequence').first()
  783. sequence = last_task.sequence + 1 if last_task else 1
  784. return f"outbound-{month}-{sequence:05d}"
  785. @staticmethod
  786. def send_task_to_wcs(task):
  787. """异步发送任务到WCS(非阻塞版本)"""
  788. # 提取任务关键数据用于线程(避免直接传递ORM对象)
  789. task_data = {
  790. 'task_id': task.pk, # 使用主键而不是对象
  791. 'send_data': {
  792. "code":'200',
  793. "message": task.message,
  794. "data":{
  795. "taskid": task.taskid,
  796. "container": task.container,
  797. "current_location": task.current_location,
  798. "target_location": task.target_location,
  799. "tasktype": task.tasktype,
  800. "month": task.month,
  801. "message": task.message,
  802. "status": task.status,
  803. "taskNumber": task.tasknumber-20000000000,
  804. "order_number":task.order_number,
  805. "sequence":task.sequence
  806. }
  807. }
  808. }
  809. # 创建并启动线程
  810. thread = threading.Thread(
  811. target=OutboundService._async_send_handler,
  812. kwargs=task_data,
  813. daemon=True # 守护线程(主程序退出时自动终止)
  814. )
  815. thread.start()
  816. return True # 立即返回表示已开始处理
  817. @staticmethod
  818. def _async_send_handler(task_id, send_data):
  819. """异步处理的实际工作函数"""
  820. try:
  821. # 每个线程需要独立的数据库连接
  822. close_old_connections()
  823. # 重新获取任务对象(确保使用最新数据)
  824. task = ContainerWCSModel.objects.get(pk=task_id)
  825. # 发送第一个请求(不处理结果)
  826. requests.post(
  827. "http://127.0.0.1:8008/container/batch/",
  828. json=send_data,
  829. timeout=10
  830. )
  831. # 发送关键请求
  832. response = requests.post(
  833. "http://192.168.18.67:1616/wcs/WebApi/getOutTask",
  834. json=send_data,
  835. timeout=10
  836. )
  837. # 处理响应
  838. if response.status_code == 200:
  839. task.status = 200
  840. task.save()
  841. logger.info(f"任务 {task.taskid} 已发送")
  842. else:
  843. logger.error(f"WCS返回错误: {response.text}")
  844. except Exception as e:
  845. logger.error(f"发送失败: {str(e)}")
  846. finally:
  847. close_old_connections() # 清理数据库连接
  848. @staticmethod
  849. def create_initial_tasks(container_list,bound_list_id):
  850. """生成初始任务队列"""
  851. with transaction.atomic():
  852. current_WCS = ContainerWCSModel.objects.filter(tasktype='outbound',bound_list_id = bound_list_id).first()
  853. if current_WCS:
  854. logger.error(f"当前{bound_list_id}已有出库任务")
  855. return False
  856. tasks = []
  857. start_sequence = ContainerWCSModel.objects.filter(tasktype='outbound').count() + 1
  858. tasknumber = ContainerWCSModel.objects.filter().count()
  859. tasknumber_index = 1
  860. for index, container in enumerate(container_list, start=start_sequence):
  861. container_obj = ContainerListModel.objects.filter(id =container['container_number']).first()
  862. if container_obj.current_location != container_obj.target_location:
  863. logger.error(f"托盘 {container_obj.container_code} 未到达目的地,不生成任务")
  864. return False
  865. OutBoundDetail_obj = OutBoundDetailModel.objects.filter(bound_list=bound_list_id,bound_batch_number_id=container['batch_id']).first()
  866. if not OutBoundDetail_obj:
  867. logger.error(f"批次 {container['batch_id']} 不存在")
  868. return False
  869. month = int(timezone.now().strftime("%Y%m"))
  870. task = ContainerWCSModel(
  871. taskid=OutboundService.generate_task_id(),
  872. batch = OutBoundDetail_obj.bound_batch_number,
  873. batch_out = OutBoundDetail_obj.bound_batch,
  874. bound_list = OutBoundDetail_obj.bound_list,
  875. sequence=index,
  876. order_number = container['location_c_number'],
  877. priority=100,
  878. tasknumber = month*100000+tasknumber_index+tasknumber,
  879. container=container_obj.container_code,
  880. current_location=container_obj.current_location,
  881. target_location="203",
  882. tasktype="outbound",
  883. month=int(timezone.now().strftime("%Y%m")),
  884. message="等待出库",
  885. status=100,
  886. )
  887. tasknumber_index += 1
  888. tasks.append(task)
  889. container_obj = ContainerListModel.objects.filter(container_code=task.container).first()
  890. container_obj.target_location = task.target_location
  891. container_obj.save()
  892. ContainerWCSModel.objects.bulk_create(tasks)
  893. logger.info(f"已创建 {len(tasks)} 个初始任务")
  894. @staticmethod
  895. def insert_new_tasks(new_tasks):
  896. """动态插入新任务并重新排序"""
  897. with transaction.atomic():
  898. pending_tasks = list(ContainerWCSModel.objects.select_for_update().filter(status=100))
  899. # 插入新任务
  900. for new_task_data in new_tasks:
  901. new_task = ContainerWCSModel(
  902. taskid=OutboundService.generate_task_id(),
  903. priority=new_task_data.get('priority', 100),
  904. container=new_task_data['container'],
  905. current_location=new_task_data['current_location'],
  906. target_location=new_task_data.get('target_location', 'OUT01'),
  907. tasktype="outbound",
  908. month=int(timezone.now().strftime("%Y%m")),
  909. message="等待出库",
  910. status=100,
  911. )
  912. # 找到插入位置
  913. insert_pos = 0
  914. for i, task in enumerate(pending_tasks):
  915. if new_task.priority < task.priority:
  916. insert_pos = i
  917. break
  918. else:
  919. insert_pos = len(pending_tasks)
  920. pending_tasks.insert(insert_pos, new_task)
  921. # 重新分配顺序号
  922. for i, task in enumerate(pending_tasks, start=1):
  923. task.sequence = i
  924. if task.pk is None:
  925. task.save()
  926. else:
  927. task.save(update_fields=['sequence'])
  928. logger.info(f"已插入 {len(new_tasks)} 个新任务")
  929. @staticmethod
  930. def process_next_task():
  931. """处理下一个任务"""
  932. next_task = ContainerWCSModel.objects.filter(status=100).order_by('sequence').first()
  933. if not next_task:
  934. logger.info("没有待处理任务")
  935. return
  936. allocator = LocationAllocation()
  937. OutboundService.perform_initial_allocation(allocator, next_task.current_location)
  938. OutboundService.send_task_to_wcs(next_task)
  939. def perform_initial_allocation(allocator, location):
  940. """执行初始库位分配操作"""
  941. location_row = location.split('-')[1]
  942. location_col = location.split('-')[2]
  943. location_layer = location.split('-')[3]
  944. location_code = LocationModel.objects.filter(row=location_row, col=location_col, layer=location_layer).first().location_code
  945. if not location_code:
  946. logger.error(f"未找到库位: {location}")
  947. operations = [
  948. (allocator.update_location_status,location_code, 'reserved'),
  949. (allocator.update_location_group_status,location_code)
  950. ]
  951. for func, *args in operations:
  952. if not func(*args):
  953. logger.error(f"分配操作失败: {func.__name__}")
  954. return False
  955. return True
  956. class OutTaskViewSet(APIView):
  957. """
  958. # fun:get_out_task:下发出库任务
  959. # fun:get_batch_count_by_boundlist:获取出库申请下的批次数量
  960. # fun:generate_location_by_demand:根据出库需求生成出库任务
  961. """
  962. # authentication_classes = [] # 禁用所有认证类
  963. # permission_classes = [AllowAny] # 允许任意访问
  964. def post(self, request):
  965. try:
  966. data = self.request.data
  967. logger.info(f"收到 WMS 推送数据: {data}")
  968. # 假设从请求中获取 bound_list_id
  969. bound_list_id = data.get('bound_list_id')
  970. batch_count = self.get_batch_count_by_boundlist(bound_list_id)
  971. logger.info(f"出库批次数量: {batch_count}")
  972. # 获取需要出库的托盘列表
  973. generate_result = self.generate_location_by_demand(batch_count,bound_list_id)
  974. if generate_result['code'] != '200':
  975. current_WCS = ContainerWCSModel.objects.filter(tasktype='outbound',bound_list_id = bound_list_id).first()
  976. if current_WCS:
  977. OutboundService.process_next_task()
  978. return Response({"code": "200", "msg": "Success 再次发送任务"}, status=200)
  979. return Response(generate_result, status=500)
  980. container_list = generate_result['data']
  981. logger.info(f"生成出库任务: {container_list}")
  982. # 2. 生成初始任务
  983. OutboundService.create_initial_tasks(container_list,bound_list_id)
  984. # 3. 立即发送第一个任务
  985. OutboundService.process_next_task()
  986. return Response({"code": "200", "msg": "Success"}, status=200)
  987. except Exception as e:
  988. logger.error(f"任务生成失败: {str(e)}")
  989. return Response({"code": "500", "msg": str(e)}, status=500)
  990. # 获取出库需求
  991. def get_batch_count_by_boundlist(self,bound_list_id):
  992. try:
  993. bound_list_obj_all = OutBoundDetailModel.objects.filter(bound_list=bound_list_id).all()
  994. if bound_list_obj_all:
  995. batch_count_dict = {}
  996. # 统计批次数量(创建哈希表,去重)
  997. for batch in bound_list_obj_all:
  998. if batch.bound_batch_number_id not in batch_count_dict:
  999. batch_count_dict[batch.bound_batch_number_id] = batch.bound_batch.goods_out_qty
  1000. else:
  1001. batch_count_dict[batch.bound_batch_number_id] += batch.bound_batch.goods_out_qty
  1002. return batch_count_dict
  1003. else:
  1004. logger.error(f"查询批次数量失败: {bound_list_id} 不存在")
  1005. return {}
  1006. except Exception as e:
  1007. logger.error(f"查询批次数量失败: {str(e)}")
  1008. return {}
  1009. def get_location_by_status_and_batch(self,status,bound_id):
  1010. try:
  1011. container_obj = ContainerDetailModel.objects.filter(batch=bound_id,status=status).all()
  1012. if container_obj:
  1013. container_dict = {}
  1014. # 统计托盘数量(创建哈希表,去重)
  1015. for obj in container_obj:
  1016. if obj.container_id not in container_dict:
  1017. container_dict[obj.container_id] = obj.goods_qty
  1018. else:
  1019. container_dict[obj.container_id] += obj.goods_qty
  1020. return container_dict
  1021. else:
  1022. logger.error(f"查询{status}状态的批次数量失败: {bound_id} 不存在")
  1023. return {}
  1024. except Exception as e:
  1025. logger.error(f"查询{status}状态的批次数量失败: {str(e)}")
  1026. return {}
  1027. def get_order_by_batch(self,container_list,bound_id):
  1028. try:
  1029. container_dict = {}
  1030. for container in container_list:
  1031. location_container = LocationContainerLink.objects.filter(container_id=container,is_active=True).first()
  1032. if location_container:
  1033. location_c_number = location_container.location.c_number
  1034. if container not in container_dict:
  1035. container_dict[container] = {
  1036. "container_number":container,
  1037. "location_c_number":location_c_number,
  1038. "location_id ":location_container.location.id,
  1039. "location_type":location_container.location.location_type,
  1040. "batch_id":bound_id,
  1041. }
  1042. if len(container_dict.keys()) == len(container_list):
  1043. return container_dict
  1044. else:
  1045. logger.error(f"查询批次数量失败: {container_list} 不存在")
  1046. return {}
  1047. except Exception as e:
  1048. logger.error(f"查询批次数量失败: {str(e)}")
  1049. return {}
  1050. except Exception as e:
  1051. logger.error(f"查询{status}状态的批次数量失败: {str(e)}")
  1052. return {}
  1053. def generate_location_by_demand(self,demand_list,bound_list_id):
  1054. # demand_list {1: 25, 2: 17}
  1055. try:
  1056. return_location =[]
  1057. for demand_id, demand_qty in demand_list.items():
  1058. container_list = self.get_location_by_status_and_batch(2, demand_id)
  1059. if not container_list:
  1060. return {"code": "500", "msg": f"批次 {demand_id} 不存在"}
  1061. container_id_list = container_list.keys()
  1062. container_order = self.get_order_by_batch(container_id_list,demand_id)
  1063. if not container_order:
  1064. return {"code": "500", "msg": f"托盘 {container_id_list} 不存在"}
  1065. order = sorted(
  1066. container_order.values(),
  1067. key=lambda x: (
  1068. int(x['location_type'][-1]), # 提取最后一位数字并转为整数
  1069. -x['location_c_number'] # 按location_c_number降序
  1070. )
  1071. )
  1072. current_qty = 0
  1073. for container in order:
  1074. container_detail_obj = ContainerDetailModel.objects.filter(container_id=container['container_number'],batch_id=demand_id,status=2).all()
  1075. container_obj = ContainerListModel.objects.filter(id=container['container_number']).first()
  1076. if not container_obj:
  1077. return {"code": "500", "msg": f"托盘 {container['container_number']} 不存在"}
  1078. if not container_detail_obj:
  1079. return {"code": "500", "msg": f"托盘上无该批次,请检查{container['container_number']} 不存在"}
  1080. goods_qty = 0
  1081. for obj in container_detail_obj:
  1082. goods_qty += obj.goods_qty
  1083. if current_qty < demand_qty:
  1084. now_qty = current_qty
  1085. current_qty += goods_qty
  1086. return_location.append(container)
  1087. logger.info(f"批次 {demand_id} 托盘 {container['container_number']} 当前数量 {current_qty}")
  1088. self.create_or_update_container_operation(container_obj,demand_id,bound_list_id,203,min(demand_qty-now_qty,goods_qty),min(demand_qty-now_qty,goods_qty))
  1089. self.update_container_detail_out_qty(container_obj,demand_id)
  1090. else:
  1091. break
  1092. return {"code": "200", "msg": "Success", "data": return_location}
  1093. except Exception as e:
  1094. return {"code": "500", "msg": str(e)}
  1095. def create_or_update_container_operation(self,container_obj,batch_id,bound_id,to_location,goods_qty,goods_weight):
  1096. try:
  1097. container_operation_obj = ContainerOperationModel.objects.filter(container=container_obj,batch_id=batch_id,bound_id=bound_id,operation_type="outbound").first()
  1098. if container_operation_obj:
  1099. logger.info(f"[0]查询出库任务: {container_operation_obj.operation_type} ")
  1100. logger.info(f"更新出库任务: {container_obj.container_code} 批次 {batch_id} 出库需求: {bound_id} 数量: {goods_qty} 重量: {goods_weight}")
  1101. container_operation_obj.to_location = to_location
  1102. container_operation_obj.goods_qty = goods_qty
  1103. container_operation_obj.goods_weight = goods_weight
  1104. container_operation_obj.save()
  1105. else:
  1106. logger.info(f"创建出库任务: {container_obj.container_code} 批次 {batch_id} 出库需求: {bound_id} 数量: {goods_qty} 重量: {goods_weight}")
  1107. batch = BoundBatchModel.objects.filter(id=batch_id).first()
  1108. if not batch:
  1109. return {"code": "500", "msg": f"批次 {batch_id} 不存在"}
  1110. ContainerOperationModel.objects.create(
  1111. month = int(timezone.now().strftime("%Y%m")),
  1112. container = container_obj,
  1113. goods_code = batch.goods_code,
  1114. goods_desc = batch.goods_desc,
  1115. operation_type ="outbound",
  1116. batch_id = batch_id,
  1117. bound_id = bound_id,
  1118. goods_qty = goods_qty,
  1119. goods_weight = goods_weight,
  1120. from_location = container_obj.current_location,
  1121. to_location= to_location,
  1122. timestamp=timezone.now(),
  1123. operator="WMS",
  1124. memo=f"出库需求: {bound_id}, 批次: {batch_id}, 数量: {goods_qty}"
  1125. )
  1126. return {"code": "200", "msg": "Success"}
  1127. except Exception as e:
  1128. return {"code": "500", "msg": str(e)}
  1129. def update_container_detail_out_qty(self,container_obj,batch_id):
  1130. try:
  1131. logger.info(f"[1]更新托盘出库数量: {container_obj.container_code} 批次 {batch_id} ")
  1132. container_operation_obj = ContainerOperationModel.objects.filter(container=container_obj,batch_id=batch_id,operation_type="outbound").all()
  1133. if not container_operation_obj:
  1134. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无出库任务")
  1135. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无出库任务"}
  1136. container_detail_obj = ContainerDetailModel.objects.filter(container=container_obj,batch_id=batch_id,status=2).first()
  1137. if not container_detail_obj:
  1138. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无批次信息")
  1139. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无批次信息"}
  1140. out_qty = 0
  1141. for obj in container_operation_obj:
  1142. out_qty += obj.goods_qty
  1143. if out_qty >= container_detail_obj.goods_qty:
  1144. out_qty = container_detail_obj.goods_qty
  1145. container_detail_obj.status = 3
  1146. break
  1147. if out_qty == 0:
  1148. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无出库数量")
  1149. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无出库数量"}
  1150. container_detail_obj.goods_out_qty = out_qty
  1151. container_detail_obj.save()
  1152. return {"code": "200", "msg": "Success"}
  1153. except Exception as e:
  1154. return {"code": "500", "msg": str(e)}
  1155. class BatchViewSet(viewsets.ModelViewSet):
  1156. authentication_classes = [] # 禁用所有认证类
  1157. permission_classes = [AllowAny] # 允许任意访问
  1158. def wcs_post(self, request, *args, **kwargs):
  1159. data = self.request.data
  1160. logger.info(f"收到 WMS 推送数据: {data}")
  1161. return Response({"code": "200", "msg": "Success"}, status=200)