views.py 91 KB

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