views.py 58 KB

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