views.py 63 KB

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