views.py 71 KB

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