views.py 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  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. "container_code": container.container_code,
  910. "count": len(results),
  911. "results": results,
  912. "batch_totals": batch_totals # 可选:单独返回批次总量
  913. }
  914. },
  915. status=status.HTTP_200_OK
  916. )
  917. except Exception as e:
  918. return Response(
  919. {'code': 500, 'message': f'服务器错误: {str(e)}', 'data': None},
  920. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  921. )
  922. def pdadetail_list(self, request):
  923. """
  924. 获取PDA组盘入库的托盘详情列表
  925. """
  926. try:
  927. container_code = request.query_params.get('container_code')
  928. if not container_code:
  929. return Response(
  930. {'code': 400, 'message': '缺少托盘编码参数', 'data': None},
  931. status=status.HTTP_200_OK
  932. )
  933. # 获取托盘对象
  934. try:
  935. container = ContainerListModel.objects.get(container_code=container_code)
  936. except ContainerListModel.DoesNotExist:
  937. return Response(
  938. {'code': 404, 'message': '指定托盘不存在', 'data': None},
  939. status=status.HTTP_200_OK
  940. )
  941. # 查询关联批次明细(排除状态0和3)
  942. details = ContainerDetailModel.objects.filter(
  943. container=container,is_delete=False
  944. ).exclude(
  945. status__in=[0, 3]
  946. ).select_related('batch')
  947. if not details.exists():
  948. return Response(
  949. {'code': 404, 'message': '未找到有效批次数据', 'data': None},
  950. status=status.HTTP_200_OK
  951. )
  952. # 按批次号 + 数量分组统计
  953. batch_dict = {}
  954. batch_qty_dict = defaultdict(int) # 使用默认字典自动初始化
  955. for detail in details:
  956. if not detail.batch:
  957. continue
  958. bound_number = detail.batch.bound_number
  959. goods_qty = detail.goods_qty - detail.goods_out_qty # 剔除出库数量
  960. # 组合键:批次号 + 当前数量
  961. batch_key = (bound_number, goods_qty)
  962. batch_qty_dict[bound_number] += goods_qty # 自动处理键初始化
  963. # 分组统计
  964. if batch_key not in batch_dict:
  965. batch_obj = BoundBatchModel.objects.filter( bound_number=bound_number).first()
  966. batch_dict[batch_key] = {
  967. "goods_code": detail.goods_code,
  968. "goods_desc": detail.goods_desc,
  969. "goods_qty": goods_qty,
  970. "goods_class": detail.goods_class,
  971. "goods_package": batch_obj.goods_package,
  972. "batch_total_qty": batch_obj.goods_qty,
  973. "batch_total_in_qty": batch_obj.goods_in_qty - batch_obj.goods_out_qty,
  974. "status": detail.status,
  975. "group_qty": 1,
  976. "create_time": detail.create_time,
  977. }
  978. else:
  979. batch_dict[batch_key]["group_qty"] += 1
  980. # 重构数据结构
  981. results = []
  982. for (bound_number, qty), data in batch_dict.items():
  983. results.append({
  984. **data,
  985. "bound_number": bound_number,
  986. "current_qty": qty,
  987. "total_batch_qty": batch_qty_dict[bound_number] # 添加批次总量
  988. })
  989. batch_totals =[]
  990. for bound_number, qty in batch_qty_dict.items():
  991. batch_totals.append({
  992. "bound_number": bound_number,
  993. "total_batch_qty": qty
  994. })
  995. return Response(
  996. {
  997. "code": 200,
  998. "message": "Success",
  999. "data": {
  1000. "count": len(results),
  1001. "results": results,
  1002. "batch_totals": batch_totals # 可选:单独返回批次总量
  1003. }
  1004. },
  1005. status=status.HTTP_200_OK
  1006. )
  1007. except Exception as e:
  1008. return Response(
  1009. {'code': 500, 'message': f'服务器错误: {str(e)}', 'data': None},
  1010. status=status.HTTP_200_OK
  1011. )
  1012. # 托盘操作历史记录
  1013. class ContainerOperateViewSet(viewsets.ModelViewSet):
  1014. """
  1015. retrieve:
  1016. Response a data list(get)
  1017. list:
  1018. Response a data list(all)
  1019. create:
  1020. Create a data line(post)
  1021. delete:
  1022. Delete a data line(delete)
  1023. """
  1024. # authentication_classes = [] # 禁用所有认证类
  1025. # permission_classes = [AllowAny] # 允许任意访问
  1026. pagination_class = MyPageNumberPagination
  1027. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1028. ordering_fields = ['id', "timestamp" ]
  1029. filter_class = ContainerOperationFilter
  1030. def get_project(self):
  1031. try:
  1032. id = self.kwargs.get('pk')
  1033. return id
  1034. except:
  1035. return None
  1036. def get_queryset(self):
  1037. id = self.get_project()
  1038. if self.request.user:
  1039. if id is None:
  1040. return ContainerOperationModel.objects.filter( is_delete=False)
  1041. else:
  1042. return ContainerOperationModel.objects.filter( id=id, is_delete=False)
  1043. else:
  1044. return ContainerOperationModel.objects.none()
  1045. def get_serializer_class(self):
  1046. if self.action in ['list', 'destroy','retrieve']:
  1047. return ContainerOperationGetSerializer
  1048. elif self.action in ['create', 'update']:
  1049. return ContainerOperationPostSerializer
  1050. else:
  1051. return self.http_method_not_allowed(request=self.request)
  1052. def create(self, request, *args, **kwargs):
  1053. data = self.request.data
  1054. serializer = self.get_serializer(data=data)
  1055. serializer.is_valid(raise_exception=True)
  1056. serializer.save()
  1057. headers = self.get_success_headers(serializer.data)
  1058. return Response(serializer.data, status=200, headers=headers)
  1059. def update(self, request, pk):
  1060. qs = self.get_object()
  1061. data = self.request.data
  1062. serializer = self.get_serializer(qs, data=data)
  1063. serializer.is_valid(raise_exception=True)
  1064. serializer.save()
  1065. headers = self.get_success_headers(serializer.data)
  1066. return Response(serializer.data, status=200, headers=headers)
  1067. # 出库任务生成
  1068. class OutboundService:
  1069. @staticmethod
  1070. def generate_task_id():
  1071. """生成唯一任务ID(格式: outbound-年月-顺序号)"""
  1072. month = timezone.now().strftime("%Y%m")
  1073. last_task = ContainerWCSModel.objects.filter(
  1074. tasktype='outbound',
  1075. month=int(month)
  1076. ).order_by('-sequence').first()
  1077. sequence = last_task.sequence + 1 if last_task else 1
  1078. return f"outbound-{month}-{sequence:05d}"
  1079. @staticmethod
  1080. def send_task_to_wcs(task):
  1081. """异步发送任务到WCS(非阻塞版本)"""
  1082. # 提取任务关键数据用于线程(避免直接传递ORM对象)
  1083. task_data = {
  1084. 'task_id': task.pk, # 使用主键而不是对象
  1085. 'send_data': {
  1086. "code":'200',
  1087. "message": task.message,
  1088. "data":{
  1089. "taskid": task.taskid,
  1090. "container": task.container,
  1091. "current_location": task.current_location,
  1092. "target_location": task.target_location,
  1093. "tasktype": task.tasktype,
  1094. "month": task.month,
  1095. "message": task.message,
  1096. "status": task.status,
  1097. "taskNumber": task.tasknumber-20000000000,
  1098. "order_number":task.order_number,
  1099. "sequence":task.sequence
  1100. }
  1101. }
  1102. }
  1103. # 创建并启动线程
  1104. thread = threading.Thread(
  1105. target=OutboundService._async_send_handler,
  1106. kwargs=task_data,
  1107. daemon=True # 守护线程(主程序退出时自动终止)
  1108. )
  1109. thread.start()
  1110. return True # 立即返回表示已开始处理
  1111. @staticmethod
  1112. def _async_send_handler(task_id, send_data):
  1113. """异步处理的实际工作函数"""
  1114. try:
  1115. # 每个线程需要独立的数据库连接
  1116. close_old_connections()
  1117. # 重新获取任务对象(确保使用最新数据)
  1118. task = ContainerWCSModel.objects.get(pk=task_id)
  1119. # 发送第一个请求(不处理结果)
  1120. requests.post(
  1121. "http://127.0.0.1:8008/container/batch/",
  1122. json=send_data,
  1123. timeout=10
  1124. )
  1125. # 发送关键请求
  1126. response = requests.post(
  1127. "http://192.168.18.200:1616/wcs/WebApi/getOutTask",
  1128. json=send_data,
  1129. timeout=10
  1130. )
  1131. # 处理响应
  1132. if response.status_code == 200:
  1133. task.status = 200
  1134. task.save()
  1135. logger.info(f"任务 {task.taskid} 已发送")
  1136. else:
  1137. logger.error(f"WCS返回错误: {response.text}")
  1138. except Exception as e:
  1139. logger.error(f"发送失败: {str(e)}")
  1140. finally:
  1141. close_old_connections() # 清理数据库连接
  1142. @staticmethod
  1143. def create_initial_tasks(container_list,bound_list_id):
  1144. """生成初始任务队列"""
  1145. with transaction.atomic():
  1146. current_WCS = ContainerWCSModel.objects.filter(tasktype='outbound',bound_list_id = bound_list_id).first()
  1147. if current_WCS:
  1148. logger.error(f"当前{bound_list_id}已有出库任务")
  1149. return False
  1150. tasks = []
  1151. start_sequence = ContainerWCSModel.objects.filter(tasktype='outbound').count() + 1
  1152. tasknumber = ContainerWCSModel.objects.filter().count()
  1153. tasknumber_index = 1
  1154. for index, container in enumerate(container_list, start=start_sequence):
  1155. container_obj = ContainerListModel.objects.filter(id =container['container_number']).first()
  1156. if container_obj.current_location != container_obj.target_location:
  1157. logger.error(f"托盘 {container_obj.container_code} 未到达目的地,不生成任务")
  1158. return False
  1159. OutBoundDetail_obj = OutBoundDetailModel.objects.filter(bound_list=bound_list_id,bound_batch_number_id=container['batch_id']).first()
  1160. if not OutBoundDetail_obj:
  1161. logger.error(f"批次 {container['batch_id']} 不存在")
  1162. return False
  1163. month = int(timezone.now().strftime("%Y%m"))
  1164. task = ContainerWCSModel(
  1165. taskid=OutboundService.generate_task_id(),
  1166. batch = OutBoundDetail_obj.bound_batch_number,
  1167. batch_out = OutBoundDetail_obj.bound_batch,
  1168. bound_list = OutBoundDetail_obj.bound_list,
  1169. sequence=index,
  1170. order_number = container['c_number'],
  1171. priority=100,
  1172. tasknumber = month*100000+tasknumber_index+tasknumber,
  1173. container=container_obj.container_code,
  1174. current_location=container_obj.current_location,
  1175. target_location="103",
  1176. tasktype="outbound",
  1177. month=int(timezone.now().strftime("%Y%m")),
  1178. message="等待出库",
  1179. status=100,
  1180. )
  1181. tasknumber_index += 1
  1182. tasks.append(task)
  1183. container_obj = ContainerListModel.objects.filter(container_code=task.container).first()
  1184. container_obj.target_location = task.target_location
  1185. container_obj.save()
  1186. ContainerWCSModel.objects.bulk_create(tasks)
  1187. logger.info(f"已创建 {len(tasks)} 个初始任务")
  1188. @staticmethod
  1189. def insert_new_tasks(new_tasks):
  1190. """动态插入新任务并重新排序"""
  1191. with transaction.atomic():
  1192. pending_tasks = list(ContainerWCSModel.objects.select_for_update().filter(status=100))
  1193. # 插入新任务
  1194. for new_task_data in new_tasks:
  1195. new_task = ContainerWCSModel(
  1196. taskid=OutboundService.generate_task_id(),
  1197. priority=new_task_data.get('priority', 100),
  1198. container=new_task_data['container'],
  1199. current_location=new_task_data['current_location'],
  1200. target_location=new_task_data.get('target_location', 'OUT01'),
  1201. tasktype="outbound",
  1202. month=int(timezone.now().strftime("%Y%m")),
  1203. message="等待出库",
  1204. status=100,
  1205. )
  1206. # 找到插入位置
  1207. insert_pos = 0
  1208. for i, task in enumerate(pending_tasks):
  1209. if new_task.priority < task.priority:
  1210. insert_pos = i
  1211. break
  1212. else:
  1213. insert_pos = len(pending_tasks)
  1214. pending_tasks.insert(insert_pos, new_task)
  1215. # 重新分配顺序号
  1216. for i, task in enumerate(pending_tasks, start=1):
  1217. task.sequence = i
  1218. if task.pk is None:
  1219. task.save()
  1220. else:
  1221. task.save(update_fields=['sequence'])
  1222. logger.info(f"已插入 {len(new_tasks)} 个新任务")
  1223. @staticmethod
  1224. def process_next_task():
  1225. """处理下一个任务"""
  1226. next_task = ContainerWCSModel.objects.filter(status=100).order_by('sequence').first()
  1227. if not next_task:
  1228. logger.info("没有待处理任务")
  1229. return
  1230. allocator = LocationAllocation()
  1231. OutboundService.perform_initial_allocation(allocator, next_task.current_location)
  1232. OutboundService.send_task_to_wcs(next_task)
  1233. def perform_initial_allocation(allocator, location):
  1234. """执行初始库位分配操作"""
  1235. location_row = location.split('-')[1]
  1236. location_col = location.split('-')[2]
  1237. location_layer = location.split('-')[3]
  1238. location_code = LocationModel.objects.filter(row=location_row, col=location_col, layer=location_layer).first().location_code
  1239. if not location_code:
  1240. logger.error(f"未找到库位: {location}")
  1241. operations = [
  1242. (allocator.update_location_status,location_code, 'reserved'),
  1243. (allocator.update_location_group_status,location_code)
  1244. ]
  1245. for func, *args in operations:
  1246. if not func(*args):
  1247. logger.error(f"分配操作失败: {func.__name__}")
  1248. return False
  1249. return True
  1250. # 出库任务下发
  1251. class OutTaskViewSet(APIView):
  1252. """
  1253. # fun:get_out_task:下发出库任务
  1254. # fun:get_batch_count_by_boundlist:获取出库申请下的批次数量
  1255. # fun:generate_location_by_demand:根据出库需求生成出库任务
  1256. """
  1257. # authentication_classes = [] # 禁用所有认证类
  1258. # permission_classes = [AllowAny] # 允许任意访问
  1259. def post(self, request):
  1260. try:
  1261. data = self.request.data
  1262. logger.info(f"收到 WMS 推送数据: {data}")
  1263. # 假设从请求中获取 bound_list_id
  1264. bound_list_id = data.get('bound_list_id')
  1265. # 获取关联的出库批次
  1266. out_batches = OutBatchModel.objects.filter(
  1267. bound_list_id=bound_list_id,
  1268. is_delete=False
  1269. ).select_related('batch_number')
  1270. if not out_batches.exists():
  1271. return Response({"code": "404", "msg": "未找到相关出库批次"}, status=404)
  1272. # 构建批次需求字典
  1273. batch_demand = {}
  1274. for ob in out_batches:
  1275. if ob.batch_number_id not in batch_demand:
  1276. batch_demand[ob.batch_number_id] = {
  1277. 'required': ob.goods_out_qty,
  1278. 'allocated': ob.goods_qty,
  1279. 'remaining': ob.goods_qty - ob.goods_out_qty
  1280. }
  1281. else:
  1282. batch_demand[ob.batch_number_id]['required'] += ob.goods_out_qty
  1283. batch_demand[ob.batch_number_id]['allocated'] += ob.goods_qty
  1284. batch_demand[ob.batch_number_id]['remaining'] += (ob.goods_out_qty - ob.goods_qty)
  1285. # 生成出库任务
  1286. generate_result = self.generate_location_by_demand(
  1287. batch_demand=batch_demand,
  1288. bound_list_id=bound_list_id
  1289. )
  1290. if generate_result['code'] != '200':
  1291. return Response(generate_result, status=500)
  1292. # 创建并处理出库任务
  1293. container_list = generate_result['data']
  1294. # 2. 生成初始任务
  1295. OutboundService.create_initial_tasks(container_list,bound_list_id)
  1296. # 3. 立即发送第一个任务
  1297. OutboundService.process_next_task()
  1298. return Response({"code": "200", "msg": "Success"}, status=200)
  1299. except Exception as e:
  1300. logger.error(f"任务生成失败: {str(e)}")
  1301. return Response({"code": "500", "msg": str(e)}, status=500)
  1302. # 获取出库需求
  1303. def get_batch_count_by_boundlist(self,bound_list_id):
  1304. try:
  1305. bound_list_obj_all = OutBoundDetailModel.objects.filter(bound_list=bound_list_id).all()
  1306. if bound_list_obj_all:
  1307. batch_count_dict = {}
  1308. # 统计批次数量(创建哈希表,去重)
  1309. for batch in bound_list_obj_all:
  1310. if batch.bound_batch_number_id not in batch_count_dict:
  1311. batch_count_dict[batch.bound_batch_number_id] = batch.bound_batch.goods_out_qty
  1312. else:
  1313. batch_count_dict[batch.bound_batch_number_id] += batch.bound_batch.goods_out_qty
  1314. return batch_count_dict
  1315. else:
  1316. logger.error(f"查询批次数量失败: {bound_list_id} 不存在")
  1317. return {}
  1318. except Exception as e:
  1319. logger.error(f"查询批次数量失败: {str(e)}")
  1320. return {}
  1321. def get_location_by_status_and_batch(self,status,bound_id):
  1322. try:
  1323. container_obj = ContainerDetailModel.objects.filter(batch=bound_id,status=status,is_delete=False).all()
  1324. if container_obj:
  1325. container_dict = {}
  1326. # 统计托盘数量(创建哈希表,去重)
  1327. for obj in container_obj:
  1328. if obj.container_id not in container_dict:
  1329. container_dict[obj.container_id] = obj.goods_qty
  1330. else:
  1331. container_dict[obj.container_id] += obj.goods_qty
  1332. return container_dict
  1333. else:
  1334. logger.error(f"查询{status}状态的批次数量失败: {bound_id} 不存在")
  1335. return {}
  1336. except Exception as e:
  1337. logger.error(f"查询{status}状态的批次数量失败: {str(e)}")
  1338. return {}
  1339. def get_order_by_batch(self,container_list,bound_id):
  1340. try:
  1341. container_dict = {}
  1342. for container in container_list:
  1343. location_container = LocationContainerLink.objects.filter(container_id=container,is_active=True).first()
  1344. if location_container:
  1345. location_c_number = location_container.location.c_number
  1346. if container not in container_dict:
  1347. container_dict[container] = {
  1348. "container_number":container,
  1349. "location_c_number":location_c_number,
  1350. "location_id ":location_container.location.id,
  1351. "location_type":location_container.location.location_type,
  1352. "batch_id":bound_id,
  1353. }
  1354. if len(container_dict.keys()) == len(container_list):
  1355. return container_dict
  1356. else:
  1357. logger.error(f"查询批次数量失败: {container_list} 不存在")
  1358. return {}
  1359. except Exception as e:
  1360. logger.error(f"查询批次数量失败: {str(e)}")
  1361. return {}
  1362. except Exception as e:
  1363. logger.error(f"查询{status}状态的批次数量失败: {str(e)}")
  1364. return {}
  1365. def get_container_allocation(self, batch_id):
  1366. """兼容所有数据库的去重方案"""
  1367. # 获取唯一托盘ID列表
  1368. container_ids = (
  1369. ContainerDetailModel.objects
  1370. .filter(batch_id=batch_id, status=2,is_delete=False)
  1371. .values_list('container_id', flat=True)
  1372. .distinct()
  1373. )
  1374. # 获取每个托盘的最新明细(按id倒序)
  1375. return (
  1376. ContainerDetailModel.objects
  1377. .filter(container_id__in=container_ids,batch_id=batch_id, status=2,is_delete=False)
  1378. .select_related('container')
  1379. .prefetch_related(
  1380. Prefetch('container__location_links',
  1381. queryset=LocationContainerLink.objects.select_related('location'),
  1382. to_attr='active_location')
  1383. )
  1384. .order_by('container_id', '-id')
  1385. )
  1386. def generate_location_by_demand(self, batch_demand, bound_list_id):
  1387. try:
  1388. return_data = []
  1389. for batch_id, demand in batch_demand.items():
  1390. # 获取已去重的托盘列表
  1391. container_qs = self.get_container_allocation(batch_id)
  1392. # 构建托盘信息字典(自动去重)
  1393. container_map = {}
  1394. for cd in container_qs:
  1395. if cd.container_id in container_map:
  1396. container_map[cd.container_id]['goods_qty'] += cd.goods_qty - cd.goods_out_qty
  1397. continue
  1398. # 获取有效库位信息
  1399. active_location = next(
  1400. (link.location for link in cd.container.active_location
  1401. if link.is_active),
  1402. None
  1403. )
  1404. container_map[cd.container_id] = {
  1405. 'detail': cd,
  1406. 'goods_qty': cd.goods_qty - cd.goods_out_qty,
  1407. 'container': cd.container,
  1408. 'location': active_location
  1409. }
  1410. # 转换为排序列表
  1411. container_list = list(container_map.values())
  1412. # 多维度排序(优化性能版)
  1413. sorted_containers = sorted(
  1414. container_list,
  1415. key=lambda x: (
  1416. self._get_goods_class_priority(x['detail'].goods_class),
  1417. -(x['location'].c_number if x['location'] else 0),
  1418. # -(x['location'].layer if x['location'] else 0),
  1419. # x['location'].row if x['location'] else 0,
  1420. # x['location'].col if x['location'] else 0
  1421. )
  1422. )
  1423. # 分配逻辑
  1424. required = demand['required']
  1425. for item in sorted_containers:
  1426. if required <= 0:
  1427. break
  1428. # 获取可分配数量
  1429. allocatable = item['goods_qty']
  1430. allocate_qty = min(required, allocatable)
  1431. # 记录分配信息
  1432. allocate_container = {
  1433. "container_number": item['container'].id,
  1434. "batch_id": batch_id,
  1435. "location_code": item['location'].location_code if item['location'] else 'N/A',
  1436. "allocate_qty": allocate_qty,
  1437. "c_number": item['location'].c_number if item['location'] else 0
  1438. }
  1439. return_data.append(allocate_container)
  1440. required -= allocate_qty
  1441. # 更新数据库状态(需要事务处理)
  1442. self._update_allocation_status(allocate_container, allocate_qty,bound_list_id)
  1443. # 降重 return_data,以container_number为key
  1444. return_data = list({v['container_number']: v for v in return_data}.values())
  1445. # 排序
  1446. return_data = sorted(return_data, key=lambda x: -x['c_number'])
  1447. return {"code": "200", "msg": "Success", "data": return_data}
  1448. except Exception as e:
  1449. logger.error(f"出库任务生成失败: {str(e)}", exc_info=True)
  1450. return {"code": "500", "msg": str(e)}
  1451. def _get_goods_class_priority(self, goods_class):
  1452. """货物类型优先级权重"""
  1453. return {
  1454. 3: 0, # 散盘最高
  1455. 1: 1, # 成品次之
  1456. 2: 2 # 空盘最低
  1457. }.get(goods_class, 99)
  1458. @transaction.atomic
  1459. def _update_allocation_status(self, allocate_container, allocate_qty,bound_list_id):
  1460. """事务化更新分配状态"""
  1461. try:
  1462. # 更新托盘明细
  1463. container_detail_all = ContainerDetailModel.objects.filter(
  1464. container_id=allocate_container['container_number'],
  1465. batch_id=allocate_container['batch_id'],
  1466. is_delete=False
  1467. ).all()
  1468. left_qty = 0
  1469. for cd in container_detail_all:
  1470. if left_qty - allocate_qty >= 0:
  1471. break
  1472. add_qty = min(allocate_qty-left_qty, cd.goods_qty - cd.goods_out_qty)
  1473. last_out_qty = cd.goods_out_qty
  1474. cd.goods_out_qty += add_qty
  1475. left_qty += add_qty
  1476. cd.save()
  1477. if cd.goods_qty - cd.goods_out_qty == 0:
  1478. cd.status = 3
  1479. cd.save()
  1480. # 新建出库detail
  1481. out_batch_detail.objects.create(
  1482. out_bound_id=bound_list_id,
  1483. container_id=cd.container_id,
  1484. container_detail_id=cd.id,
  1485. out_goods_qty=add_qty,
  1486. last_out_goods_qty = last_out_qty,
  1487. working = 1,
  1488. is_delete = False
  1489. )
  1490. return True
  1491. except Exception as e:
  1492. logger.error(f"状态更新失败: {str(e)}")
  1493. return False
  1494. def create_or_update_container_operation(self,container_obj,batch_id,bound_id,to_location,goods_qty,goods_weight):
  1495. try:
  1496. container_operation_obj = ContainerOperationModel.objects.filter(container=container_obj,batch_id=batch_id,bound_id=bound_id,operation_type="outbound").first()
  1497. if container_operation_obj:
  1498. logger.info(f"[0]查询出库任务: {container_operation_obj.operation_type} ")
  1499. logger.info(f"更新出库任务: {container_obj.container_code} 批次 {batch_id} 出库需求: {bound_id} 数量: {goods_qty} 重量: {goods_weight}")
  1500. container_operation_obj.to_location = to_location
  1501. container_operation_obj.goods_qty = goods_qty
  1502. container_operation_obj.goods_weight = goods_weight
  1503. container_operation_obj.save()
  1504. else:
  1505. logger.info(f"创建出库任务: {container_obj.container_code} 批次 {batch_id} 出库需求: {bound_id} 数量: {goods_qty} 重量: {goods_weight}")
  1506. batch = BoundBatchModel.objects.filter(id=batch_id).first()
  1507. if not batch:
  1508. return {"code": "500", "msg": f"批次 {batch_id} 不存在"}
  1509. ContainerOperationModel.objects.create(
  1510. month = int(timezone.now().strftime("%Y%m")),
  1511. container = container_obj,
  1512. goods_code = batch.goods_code,
  1513. goods_desc = batch.goods_desc,
  1514. operation_type ="outbound",
  1515. batch_id = batch_id,
  1516. bound_id = bound_id,
  1517. goods_qty = goods_qty,
  1518. goods_weight = goods_weight,
  1519. from_location = container_obj.current_location,
  1520. to_location= to_location,
  1521. timestamp=timezone.now(),
  1522. operator="WMS",
  1523. memo=f"出库需求: {bound_id}, 批次: {batch_id}, 数量: {goods_qty}"
  1524. )
  1525. return {"code": "200", "msg": "Success"}
  1526. except Exception as e:
  1527. return {"code": "500", "msg": str(e)}
  1528. def update_container_detail_out_qty(self,container_obj,batch_id):
  1529. try:
  1530. logger.info(f"[1]更新托盘出库数量: {container_obj.container_code} 批次 {batch_id} ")
  1531. container_operation_obj = ContainerOperationModel.objects.filter(container=container_obj,batch_id=batch_id,operation_type="outbound").all()
  1532. if not container_operation_obj:
  1533. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无出库任务")
  1534. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无出库任务"}
  1535. container_detail_obj = ContainerDetailModel.objects.filter(container=container_obj,batch_id=batch_id,status=2,is_delete=False).first()
  1536. if not container_detail_obj:
  1537. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无批次信息")
  1538. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无批次信息"}
  1539. out_qty = 0
  1540. for obj in container_operation_obj:
  1541. out_qty += obj.goods_qty
  1542. if out_qty >= container_detail_obj.goods_qty:
  1543. out_qty = container_detail_obj.goods_qty
  1544. container_detail_obj.status = 3
  1545. break
  1546. if out_qty == 0:
  1547. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无出库数量")
  1548. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无出库数量"}
  1549. container_detail_obj.goods_out_qty = out_qty
  1550. container_detail_obj.save()
  1551. return {"code": "200", "msg": "Success"}
  1552. except Exception as e:
  1553. return {"code": "500", "msg": str(e)}
  1554. # 出库任务监测
  1555. class BatchViewSet(viewsets.ModelViewSet):
  1556. authentication_classes = [] # 禁用所有认证类
  1557. permission_classes = [AllowAny] # 允许任意访问
  1558. def wcs_post(self, request, *args, **kwargs):
  1559. data = self.request.data
  1560. logger.info(f"收到 WMS 推送数据: {data}")
  1561. return Response({"code": "200", "msg": "Success"}, status=200)
  1562. # views.py
  1563. class OutDetailViewSet(viewsets.ModelViewSet):
  1564. pagination_class = MyPageNumberPagination
  1565. serializer_class = OutBoundDetailSerializer
  1566. def get_project(self):
  1567. try:
  1568. id = self.kwargs.get('pk')
  1569. return id
  1570. except:
  1571. return None
  1572. def get_queryset(self):
  1573. """根据不同的action调整查询集"""
  1574. if self.action == 'list':
  1575. # 获取每个out_bound的最新一条记录
  1576. # 子查询,用于获取每个out_bound对应的最新out_batch_detail记录
  1577. subquery = out_batch_detail.objects.filter(
  1578. out_bound=OuterRef('out_bound')
  1579. ).order_by('-id')
  1580. # 返回最新的out_batch_detail记录,通过子查询的结果进行过滤
  1581. return out_batch_detail.objects.filter(
  1582. id=Subquery(subquery.values('id')[:1])
  1583. )
  1584. return out_batch_detail.objects.all()
  1585. def retrieve(self, request, *args, **kwargs):
  1586. """重写retrieve方法返回关联集合"""
  1587. qs = self.get_project()
  1588. queryset = self.filter_queryset(
  1589. out_batch_detail.objects.filter(out_bound = qs)
  1590. )
  1591. # 分页处理
  1592. # page = self.paginate_queryset(queryset)
  1593. # if queryset is not None:
  1594. # serializer = self.get_serializer(queryset, many=True)
  1595. # return self.get_paginated_response(serializer.data)
  1596. serializer = self.get_serializer(queryset, many=True)
  1597. return Response(serializer.data)
  1598. def get_serializer_class(self):
  1599. """根据action切换序列化器"""
  1600. if self.action == 'retrieve':
  1601. return OutBoundFullDetailSerializer
  1602. return super().get_serializer_class()
  1603. def get_out_batch_detail(self, request):
  1604. """获取某个托盘的出库明细"""
  1605. try:
  1606. container_code = request.query_params.get('container_code')
  1607. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  1608. if not container_obj:
  1609. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  1610. out_batch_detail_all = out_batch_detail.objects.filter(container=container_obj,working=1,is_delete=False).all()
  1611. if not out_batch_detail_all:
  1612. return Response({"code": "500", "message": f"托盘 {container_code} 无出库明细"}, status=status.HTTP_200_OK)
  1613. serializer = OutBoundFullDetailSerializer(out_batch_detail_all, many=True)
  1614. return Response({"code": "200", "message": "Success", "data": serializer.data}, status=status.HTTP_200_OK)
  1615. except Exception as e:
  1616. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  1617. def confirm_out_batch_detail(self, request):
  1618. """确认出库"""
  1619. try:
  1620. container_code = request.query_params.get('container_code')
  1621. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  1622. if not container_obj:
  1623. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  1624. out_batch_detail_all = out_batch_detail.objects.filter(container=container_obj,working=1,is_delete=False).all()
  1625. if not out_batch_detail_all:
  1626. return Response({"code": "500", "message": f"托盘 {container_code} 无出库明细"}, status=status.HTTP_200_OK)
  1627. for obj in out_batch_detail_all:
  1628. obj.working = 0
  1629. obj.save()
  1630. BatchLogModel.objects.create(
  1631. batch_id = obj.container_detail.batch,
  1632. log_type = 1,
  1633. log_date = timezone.now(),
  1634. goods_code = obj.container_detail.batch.goods_code,
  1635. goods_desc = obj.container_detail.batch.goods_desc,
  1636. goods_qty = obj.out_goods_qty,
  1637. log_content = f"出库托盘 {container_code} 批次 {obj.container_detail.batch.id} 数量 {obj.out_goods_qty}",
  1638. creater = "WMS",
  1639. openid = "WMS"
  1640. )
  1641. return Response({"code": "200", "message": "出库成功"}, status=status.HTTP_200_OK)
  1642. except Exception as e:
  1643. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  1644. def cancel_out_batch_detail(self, request):
  1645. """取消出库"""
  1646. try:
  1647. container_code = request.query_params.get('container_code')
  1648. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  1649. if not container_obj:
  1650. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  1651. out_batch_detail_all = out_batch_detail.objects.filter(container=container_obj,working=1,is_delete=False).all()
  1652. if not out_batch_detail_all:
  1653. return Response({"code": "500", "message": f"托盘 {container_code} 无出库明细"}, status=status.HTTP_200_OK)
  1654. for obj in out_batch_detail_all:
  1655. obj.container_detail.goods_out_qty = obj.last_out_goods_qty
  1656. obj.container_detail.save()
  1657. obj.is_delete = True
  1658. obj.working = 0
  1659. obj.save()
  1660. return Response({"code": "200", "message": "出库取消成功"}, status=status.HTTP_200_OK)
  1661. except Exception as e:
  1662. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  1663. def get_contianer_detail(self, request):
  1664. try:
  1665. container_code = request.query_params.get('container_code')
  1666. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  1667. if not container_obj:
  1668. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  1669. container_detail_all = ContainerDetailModel.objects.filter(container=container_obj,is_delete=False).all().exclude(status__in=[3])
  1670. return_data=[]
  1671. for obj in container_detail_all:
  1672. return_data.append({
  1673. "id": obj.id,
  1674. "batch": obj.batch.bound_number,
  1675. "goods_code": obj.goods_code,
  1676. "goods_desc": obj.goods_desc,
  1677. "goods_qty" :obj.goods_qty,
  1678. "out_goods_qty": obj.goods_out_qty
  1679. })
  1680. return Response({"code": "200", "message": "Success", "data": return_data}, status=status.HTTP_200_OK)
  1681. except Exception as e:
  1682. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  1683. def change_container_out_qty(self, request):
  1684. try:
  1685. container_code = request.data.get('container_code')
  1686. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  1687. if not container_obj:
  1688. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  1689. for container_detail_id, out_qty in request.data.get('detail_list').items():
  1690. container_detail_obj = ContainerDetailModel.objects.filter(id=container_detail_id,is_delete=False).first()
  1691. if not container_detail_obj:
  1692. continue
  1693. container_detail_obj.goods_out_qty += out_qty
  1694. container_detail_obj.save()
  1695. return Response({"code": "200", "message": "Success"}, status=status.HTTP_200_OK)
  1696. except Exception as e:
  1697. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)