views.py 103 KB

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