views.py 65 KB

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