views.py 62 KB

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