views.py 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619
  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,batchLogModel
  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,BatchOperateLogModel
  21. from .serializers import ContainerDetailGetSerializer,ContainerDetailPostSerializer,ContainerDetailSimpleGetSerializer,ContainerDetailPutSerializer
  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 .serializers import batchLogModelSerializer
  29. from .filter import ContainerDetailFilter,ContainerListFilter,ContainerOperationFilter,TaskFilter,WCSTaskFilter,ContainerDetailLogFilter,batchLogFilter
  30. from rest_framework.permissions import AllowAny
  31. import threading
  32. from django.db import close_old_connections
  33. from bin.services import AllocationService
  34. from collections import defaultdict
  35. from django.db.models import Sum
  36. from staff.models import ListModel as StaffListModel
  37. from operation_log.views import log_success_operation, log_failure_operation, log_operation
  38. logger = logging.getLogger(__name__)
  39. loggertask = logging.getLogger('wms.WCSTask')
  40. # 托盘分类视图
  41. # 借助LocationContainerLink,其中
  42. # 库位-托盘关联表(记录实时存放关系)
  43. # class LocationContainerLink(models.Model):
  44. # location = models.ForeignKey(
  45. # LocationModel,
  46. # on_delete=models.CASCADE,
  47. # related_name='container_links',
  48. # verbose_name='库位'
  49. # )
  50. # container = models.ForeignKey(
  51. # ContainerListModel,
  52. # on_delete=models.CASCADE,
  53. # related_name='location_links',
  54. # verbose_name='关联托盘'
  55. # )
  56. # task_wcs = models.ForeignKey(ContainerWCSModel, on_delete=models.CASCADE, null=True, blank=True)
  57. # task_detail = models.ForeignKey(TaskModel, on_delete=models.CASCADE, null=True, blank=True)
  58. # put_time = models.DateTimeField(auto_now_add=True, verbose_name='上架时间')
  59. # operator = models.CharField(max_length=50, verbose_name='操作人')
  60. # is_active = models.BooleanField(default=True, verbose_name='是否有效')
  61. # 借助LocationContainerLink中的is_active字段,可以查询托盘是否在库位中,
  62. # 若is_active为True,则托盘在库位中,否则托盘不在库位中。同时,再增加字段来显示在库托盘中的存储的物料信息。
  63. # class containerclassViewSet(viewsets.ModelViewSet):
  64. # 托盘流水汇总批次流水
  65. class batchLogModelViewSet(viewsets.ModelViewSet):
  66. """
  67. retrieve:
  68. Response a data list(get)
  69. list:
  70. Response a data list(all)
  71. create:
  72. Create a data line(post)
  73. delete:
  74. Delete a data line(delete)
  75. """
  76. pagination_class = MyPageNumberPagination
  77. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  78. ordering_fields = ['id', "create_time", "update_time", ]
  79. filter_class = batchLogFilter
  80. def get_project(self):
  81. try:
  82. id = self.kwargs.get('pk')
  83. return id
  84. except:
  85. return None
  86. def get_queryset(self):
  87. id = self.get_project()
  88. if self.request.user:
  89. if id is None:
  90. return batchLogModel.objects.filter()
  91. else:
  92. return batchLogModel.objects.filter(id=id)
  93. else:
  94. return batchLogModel.objects.none()
  95. def get_serializer_class(self):
  96. if self.action in ['list', 'destroy','retrieve']:
  97. return batchLogModelSerializer
  98. else:
  99. return self.http_method_not_allowed(request=self.request)
  100. def create(self, request, *args, **kwargs):
  101. data = self.request.data
  102. return Response(data, status=200, headers=headers)
  103. def update(self, request, pk):
  104. qs = self.get_object()
  105. data = self.request.data
  106. serializer = self.get_serializer(qs, data=data)
  107. serializer.is_valid(raise_exception=True)
  108. serializer.save()
  109. headers = self.get_success_headers(serializer.data)
  110. return Response(serializer.data, status=200, headers=headers)
  111. def get_container_operation_log(self,request):
  112. batchlog_id = self.request.query_params.get('batchlog_id')
  113. batch_obj = batchLogModel.objects.get(id=batchlog_id)
  114. container_operation_log = batch_obj.detail_logs.all()
  115. serializer = ContainerDetailLogSerializer(container_operation_log, many=True)
  116. return Response(serializer.data, status=200)
  117. # 进出库log查看
  118. class ContainerDetailLogModelViewSet(viewsets.ModelViewSet):
  119. """
  120. retrieve:
  121. Response a data list(get)
  122. list:
  123. Response a data list(all)
  124. create:
  125. Create a data line(post)
  126. delete:
  127. Delete a data line(delete)
  128. """
  129. # authentication_classes = [] # 禁用所有认证类
  130. # permission_classes = [AllowAny] # 允许任意访问
  131. pagination_class = MyPageNumberPagination
  132. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  133. ordering_fields = ['id', "create_time", "update_time", ]
  134. filter_class = ContainerDetailLogFilter
  135. def get_project(self):
  136. try:
  137. id = self.kwargs.get('pk')
  138. return id
  139. except:
  140. return None
  141. def get_queryset(self):
  142. id = self.get_project()
  143. if self.request.user:
  144. if id is None:
  145. return ContainerDetailLogModel.objects.filter()
  146. else:
  147. return ContainerDetailLogModel.objects.filter(id=id)
  148. else:
  149. return ContainerDetailLogModel.objects.none()
  150. def get_serializer_class(self):
  151. if self.action in ['list', 'destroy','retrieve']:
  152. return ContainerDetailLogSerializer
  153. else:
  154. return self.http_method_not_allowed(request=self.request)
  155. def create(self, request, *args, **kwargs):
  156. data = self.request.data
  157. return Response(data, status=200, headers=headers)
  158. def update(self, request, pk):
  159. qs = self.get_object()
  160. data = self.request.data
  161. serializer = self.get_serializer(qs, data=data)
  162. serializer.is_valid(raise_exception=True)
  163. serializer.save()
  164. headers = self.get_success_headers(serializer.data)
  165. return Response(serializer.data, status=200, headers=headers)
  166. # 托盘列表视图
  167. class ContainerListViewSet(viewsets.ModelViewSet):
  168. """
  169. retrieve:
  170. Response a data list(get)
  171. list:
  172. Response a data list(all)
  173. create:
  174. Create a data line(post)
  175. delete:
  176. Delete a data line(delete)
  177. """
  178. # authentication_classes = [] # 禁用所有认证类
  179. # permission_classes = [AllowAny] # 允许任意访问
  180. pagination_class = MyPageNumberPagination
  181. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  182. ordering_fields = ['id', "create_time", "update_time", ]
  183. filter_class = ContainerListFilter
  184. def get_project(self):
  185. try:
  186. id = self.kwargs.get('pk')
  187. return id
  188. except:
  189. return None
  190. def get_queryset(self):
  191. id = self.get_project()
  192. if self.request.user:
  193. if id is None:
  194. return ContainerListModel.objects.filter()
  195. else:
  196. return ContainerListModel.objects.filter(id=id)
  197. else:
  198. return ContainerListModel.objects.none()
  199. def get_serializer_class(self):
  200. if self.action in ['list', 'destroy','retrieve']:
  201. return ContainerListGetSerializer
  202. elif self.action in ['create', 'update']:
  203. return ContainerListPostSerializer
  204. else:
  205. return self.http_method_not_allowed(request=self.request)
  206. def create(self, request, *args, **kwargs):
  207. # 创建托盘:托盘码五位数字(唯一),当前库位,目标库位,状态,最后操作时间
  208. container_all = ContainerListModel.objects.all().order_by('container_code')
  209. if container_all.count() == 0:
  210. container_code = 12345
  211. else:
  212. container_code = container_all.last().container_code + 1
  213. container_obj = ContainerListModel.objects.create(
  214. container_code=container_code,
  215. current_location='N/A',
  216. target_location='N/A',
  217. status=0,
  218. last_operation=timezone.now()
  219. )
  220. serializer = ContainerListGetSerializer(container_obj)
  221. headers = self.get_success_headers(serializer.data)
  222. try:
  223. log_success_operation(
  224. request=self.request,
  225. operation_content=f"创建托盘列表:{container_code}",
  226. operation_level="new",
  227. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  228. object_id=container_obj.id,
  229. module_name="托盘管理"
  230. )
  231. except Exception as e:
  232. pass
  233. return Response(serializer.data, status=201, headers=headers)
  234. def update(self, request, pk):
  235. qs = self.get_object()
  236. data = self.request.data
  237. serializer = self.get_serializer(qs, data=data)
  238. serializer.is_valid(raise_exception=True)
  239. serializer.save()
  240. headers = self.get_success_headers(serializer.data)
  241. try:
  242. log_success_operation(
  243. request=self.request,
  244. operation_content=f"更新托盘列表 ID:{pk}",
  245. operation_level="update",
  246. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  247. object_id=pk,
  248. module_name="托盘管理"
  249. )
  250. except Exception as e:
  251. pass
  252. return Response(serializer.data, status=200, headers=headers)
  253. def check_container_postion(self, request, *args, **kwargs):
  254. # 获取查询集
  255. container_list = ContainerListModel.objects.exclude(current_location=F('target_location'))
  256. # 手动应用分页
  257. page = self.paginate_queryset(container_list)
  258. if page is not None:
  259. serializer = ContainerListGetSerializer(page, many=True)
  260. return self.get_paginated_response(serializer.data)
  261. # 如果没有分页,返回完整结果(不推荐)
  262. serializer = ContainerListGetSerializer(container_list, many=True)
  263. return Response(serializer.data, status=200)
  264. def update_container_categories(self, request, *args, **kwargs):
  265. from .utils import update_container_categories_task
  266. update_container_categories_task()
  267. return Response({'message': '托盘分类更新任务已触发'}, status=200)
  268. # wcs任务视图
  269. class WCSTaskViewSet(viewsets.ModelViewSet):
  270. """
  271. retrieve:
  272. Response a data list(get)
  273. list:
  274. Response a data list(all)
  275. create:
  276. Create a data line(post)
  277. delete:
  278. Delete a data line(delete)
  279. """
  280. # authentication_classes = [] # 禁用所有认证类
  281. # permission_classes = [AllowAny] # 允许任意访问
  282. pagination_class = MyPageNumberPagination
  283. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  284. ordering_fields = ['-id', "-create_time", "update_time", ]
  285. filter_class = WCSTaskFilter
  286. def get_project(self):
  287. try:
  288. id = self.kwargs.get('pk')
  289. return id
  290. except:
  291. return None
  292. def get_queryset(self):
  293. id = self.get_project()
  294. if self.request.user:
  295. if id is None:
  296. return ContainerWCSModel.objects.filter()
  297. else:
  298. return ContainerWCSModel.objects.filter(id=id)
  299. else:
  300. return ContainerWCSModel.objects.none()
  301. def get_serializer_class(self):
  302. if self.action in ['list', 'destroy','retrieve']:
  303. return WCSTaskGetSerializer
  304. else:
  305. return self.http_method_not_allowed(request=self.request)
  306. def send_task_to_wcs(self, request, *args, **kwargs):
  307. data = self.request.data
  308. task_id = data.get('taskid')
  309. logger.info(f"请求任务:{task_id}")
  310. data_return = {}
  311. try:
  312. task_obj = ContainerWCSModel.objects.get(id=task_id)
  313. if not task_obj:
  314. data_return = {
  315. 'code': '400',
  316. 'message': '任务不存在',
  317. 'data': data
  318. }
  319. log_failure_operation(
  320. request=self.request,
  321. operation_content=f"任务不存在:{task_id}",
  322. operation_level="other",
  323. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  324. module_name="WCS任务"
  325. )
  326. return Response(data_return, status=status.HTTP_400_BAD_REQUEST)
  327. if task_obj.working == 1:
  328. OutboundService.send_task_to_wcs(task_obj)
  329. data_return = {
  330. 'code': '200',
  331. 'message': '任务已在执行中,再次下发',
  332. 'data': data
  333. }
  334. else:
  335. data_return = {
  336. 'code': '200',
  337. 'message': '任务已执行完成',
  338. 'data': data
  339. }
  340. except ContainerWCSModel.DoesNotExist:
  341. data_return = {
  342. 'code': '404',
  343. 'message': '任务不存在',
  344. 'data': data
  345. }
  346. log_failure_operation(
  347. request=self.request,
  348. operation_content=f"任务下发失败:{task_id}",
  349. operation_level="other",
  350. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  351. module_name="WCS任务"
  352. )
  353. log_success_operation(
  354. request=self.request,
  355. operation_content=f"任务下发成功:{task_id}",
  356. operation_level="other",
  357. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  358. module_name="WCS任务"
  359. )
  360. return Response(data_return, status=status.HTTP_200_OK)
  361. # 入库任务视图
  362. class TaskViewSet(viewsets.ModelViewSet):
  363. """
  364. retrieve:
  365. Response a data list(get)
  366. list:
  367. Response a data list(all)
  368. create:
  369. Create a data line(post)
  370. delete:
  371. Delete a data line(delete)
  372. """
  373. pagination_class = MyPageNumberPagination
  374. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  375. ordering_fields = ['id', "create_time", "update_time", ]
  376. filter_class = TaskFilter
  377. def get_project(self):
  378. try:
  379. id = self.kwargs.get('pk')
  380. return id
  381. except:
  382. return None
  383. def get_queryset(self):
  384. id = self.get_project()
  385. if self.request.user:
  386. if id is None:
  387. return TaskModel.objects.filter()
  388. else:
  389. return TaskModel.objects.filter(id=id)
  390. else:
  391. return TaskModel.objects.none()
  392. def get_serializer_class(self):
  393. if self.action in ['list', 'destroy','retrieve']:
  394. return TaskGetSerializer
  395. elif self.action in ['create', 'update']:
  396. return TaskPostSerializer
  397. else:
  398. return self.http_method_not_allowed(request=self.request)
  399. def create(self, request, *args, **kwargs):
  400. data = self.request.data
  401. return Response(data, status=200, headers=headers)
  402. def update(self, request, pk):
  403. qs = self.get_object()
  404. data = self.request.data
  405. serializer = self.get_serializer(qs, data=data)
  406. serializer.is_valid(raise_exception=True)
  407. serializer.save()
  408. headers = self.get_success_headers(serializer.data)
  409. return Response(serializer.data, status=200, headers=headers)
  410. # 任务回滚
  411. class TaskRollbackMixin:
  412. def rollback_task(self, request, task_id, *args, **kwargs):
  413. """
  414. 撤销入库任务并回滚相关状态
  415. """
  416. try:
  417. # 获取任务实例并锁定数据库记录
  418. task = ContainerWCSModel.objects.get(taskid=task_id)
  419. container_code = task.container
  420. target_location = task.target_location
  421. batch = task.batch
  422. # 初始化库位分配器
  423. allocator = LocationAllocation()
  424. # ==================== 库位状态回滚 ====================
  425. # 解析目标库位信息(格式:仓库代码-行-列-层)
  426. try:
  427. warehouse_code, row, col, layer = target_location.split('-')
  428. location = LocationModel.objects.get(
  429. warehouse_code=warehouse_code,
  430. row=int(row),
  431. col=int(col),
  432. layer=int(layer)
  433. )
  434. # 回滚库位状态到可用状态
  435. allocator.update_location_status(location.location_code, 'available')
  436. # 更新库位组状态(需要根据实际逻辑实现)
  437. allocator.update_location_group_status(location.location_code)
  438. # 解除库位与托盘的关联
  439. allocator.update_location_container_link(location.location_code, None)
  440. # 清除库位组的批次关联
  441. allocator.update_location_group_batch(location, None)
  442. except (ValueError, LocationModel.DoesNotExist) as e:
  443. logger.error(f"库位解析失败: {str(e)}")
  444. raise Exception("关联库位信息无效")
  445. # ==================== 批次状态回滚 ====================
  446. if batch:
  447. # 将批次状态恢复为未处理状态(假设原状态为1)
  448. allocator.update_batch_status(batch.bound_number, '1')
  449. # ==================== 托盘状态回滚 ====================
  450. container_obj = ContainerListModel.objects.get(container_code=container_code)
  451. # 恢复托盘详细状态为初始状态(假设原状态为1)
  452. allocator.update_container_detail_status(container_code, 1)
  453. # 恢复托盘的目标位置为当前所在位置
  454. container_obj.target_location = task.current_location
  455. container_obj.save()
  456. # ==================== 删除任务记录 ====================
  457. task.delete()
  458. # ==================== 其他关联清理 ====================
  459. # 如果有其他关联数据(如inport_update_task的操作),在此处添加清理逻辑
  460. return Response(
  461. {'code': '200', 'message': '任务回滚成功', 'data': None},
  462. status=status.HTTP_200_OK
  463. )
  464. except ContainerWCSModel.DoesNotExist:
  465. logger.warning(f"任务不存在: {task_id}")
  466. return Response(
  467. {'code': '404', 'message': '任务不存在', 'data': None},
  468. status=status.HTTP_404_NOT_FOUND
  469. )
  470. except Exception as e:
  471. logger.error(f"任务回滚失败: {str(e)}", exc_info=True)
  472. return Response(
  473. {'code': '500', 'message': '服务器内部错误', 'data': None},
  474. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  475. )
  476. # 入库任务下发
  477. class ContainerWCSViewSet(viewsets.ModelViewSet):
  478. """
  479. retrieve:
  480. Response a data list(get)
  481. list:
  482. Response a data list(all)
  483. create:
  484. Create a data line(post)
  485. delete:
  486. Delete a data line(delete)
  487. """
  488. authentication_classes = [] # 禁用所有认证类
  489. permission_classes = [AllowAny] # 允许任意访问
  490. def generate_move_task(self, request, *args, **kwargs):
  491. data = self.request.data
  492. container = data.get('container_code')
  493. start_location = data.get('start_location')
  494. target_location = data.get('target_location')
  495. logger.info(f"移库请求托盘:{container},起始位置:{start_location},目标位置:{target_location}")
  496. data_return = {}
  497. try:
  498. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  499. if not container_obj:
  500. data_return = {
  501. 'code': '400',
  502. 'message': '托盘编码不存在',
  503. 'data': data
  504. }
  505. # 记录失败日志
  506. try:
  507. log_failure_operation(
  508. request=request,
  509. operation_content=f"移库任务创建失败:托盘编码不存在 - {container}",
  510. operation_level="other",
  511. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  512. module_name="WCS移库管理"
  513. )
  514. except Exception as log_error:
  515. pass
  516. return Response(data_return, status=status.HTTP_400_BAD_REQUEST)
  517. # 检查是否已在目标位置
  518. if target_location == str(container_obj.target_location) and target_location!= '203' and target_location!= '103':
  519. logger.info(f"托盘 {container} 已在目标位置")
  520. data_return = {
  521. 'code': '200',
  522. 'message': '当前位置已是目标位置',
  523. 'data': data
  524. }
  525. else:
  526. # 生成任务
  527. current_task = ContainerWCSModel.objects.filter(
  528. container=container,
  529. tasktype='inbound',
  530. working = 1,
  531. ).exclude(status=300).first()
  532. if current_task:
  533. data_return = {
  534. 'code': '200',
  535. 'message': '任务已存在,重新下发',
  536. 'data': current_task.to_dict()
  537. }
  538. else:
  539. # todo: 这里的入库操作记录里面的记录的数量不对
  540. location_min_value,allocation_target_location, batch_info = AllocationService._move_allocation(start_location, target_location,container)
  541. batch_id = batch_info['number']
  542. if batch_info['class'] == 2:
  543. self.generate_task_no_batch(container, start_location, allocation_target_location,batch_id,location_min_value.c_number)
  544. self.generate_container_operate_no_batch(container_obj, batch_id, allocation_target_location)
  545. elif batch_info['class'] == 3:
  546. self.generate_task_no_batch(container, start_location, allocation_target_location,batch_id,location_min_value.c_number)
  547. self.generate_move_container_operate(container_obj, allocation_target_location)
  548. else:
  549. self.generate_task(container, start_location, allocation_target_location,batch_id,location_min_value.c_number) # 生成任务
  550. self.generate_move_container_operate(container_obj, allocation_target_location)
  551. current_task = ContainerWCSModel.objects.get(
  552. container=container,
  553. tasktype='inbound',
  554. working=1,
  555. )
  556. OutboundService.send_task_to_wcs(current_task)
  557. data_return = {
  558. 'code': '200',
  559. 'message': '任务下发成功',
  560. 'data': current_task.to_dict()
  561. }
  562. container_obj.target_location = allocation_target_location
  563. container_obj.save()
  564. if batch_info['class'] == 1 or batch_info['class'] == 3:
  565. self.inport_update_task(current_task.id, container_obj.id)
  566. http_status = status.HTTP_200_OK if data_return['code'] == '200' else status.HTTP_400_BAD_REQUEST
  567. loggertask.info(f"任务号:{current_task.tasknumber-20000000000},移库请求托盘:{container},起始位置:{start_location},目标位置:{target_location},返回结果:{data_return}")
  568. # 记录操作日志
  569. try:
  570. if data_return['code'] == '200':
  571. task_info = data_return.get('data', {})
  572. task_id = task_info.get('tasknumber', '未知') if isinstance(task_info, dict) else '未知'
  573. log_success_operation(
  574. request=request,
  575. operation_content=f"移库任务创建成功:托盘 {container},起始位置:{start_location},目标位置:{target_location},任务号:{task_id}",
  576. operation_level="other",
  577. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  578. object_id=container_obj.id if container_obj else None,
  579. module_name="WCS移库管理"
  580. )
  581. else:
  582. log_failure_operation(
  583. request=request,
  584. operation_content=f"移库任务创建失败:托盘 {container},错误:{data_return.get('message', '未知错误')}",
  585. operation_level="other",
  586. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  587. module_name="WCS移库管理"
  588. )
  589. except Exception as log_error:
  590. pass
  591. return Response(data_return, status=http_status)
  592. except Exception as e:
  593. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  594. # 记录异常日志
  595. try:
  596. log_failure_operation(
  597. request=request,
  598. operation_content=f"移库任务处理异常:托盘 {container},错误:{str(e)}",
  599. operation_level="other",
  600. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  601. module_name="WCS移库管理"
  602. )
  603. except Exception as log_error:
  604. pass
  605. return Response(
  606. {'code': '500', 'message': '服务器内部错误', 'data': None},
  607. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  608. )
  609. def generate_out_task(self, request, *args, **kwargs):
  610. data = self.request.data
  611. container = data.get('container_code')
  612. start_location = data.get('current_location')
  613. target_location = data.get('target_location')
  614. logger.info(f"出库请求托盘:{container},起始位置:{start_location},目标位置:{target_location}")
  615. data_return = {}
  616. try:
  617. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  618. if not container_obj:
  619. data_return = {
  620. 'code': '400',
  621. 'message': '托盘编码不存在',
  622. 'data': data
  623. }
  624. # 记录失败日志
  625. try:
  626. log_failure_operation(
  627. request=request,
  628. operation_content=f"出库任务创建失败:托盘编码不存在 - {container}",
  629. operation_level="other",
  630. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  631. module_name="WCS出库管理"
  632. )
  633. except Exception as log_error:
  634. pass
  635. return Response(data_return, status=status.HTTP_400_BAD_REQUEST)
  636. # 检查是否已在目标位置
  637. if target_location == str(container_obj.target_location) :
  638. logger.info(f"托盘 {container} 已在目标位置")
  639. data_return = {
  640. 'code': '200',
  641. 'message': '当前位置已是目标位置',
  642. 'data': data
  643. }
  644. else:
  645. # 生成任务
  646. current_task = ContainerWCSModel.objects.filter(
  647. container=container,
  648. tasktype='outbound',
  649. working = 1,
  650. ).exclude(status=300).first()
  651. if current_task:
  652. data_return = {
  653. 'code': '200',
  654. 'message': '任务已存在,重新下发',
  655. 'data': current_task.to_dict()
  656. }
  657. else:
  658. # todo: 这里的入库操作记录里面的记录的数量不对
  659. allocation_target_location, batch_info = AllocationService._out_allocation(start_location, target_location,container)
  660. batch_id = batch_info['number']
  661. if batch_info['class'] == 2:
  662. self.generate_task_no_batch(container, start_location, allocation_target_location,batch_id,1,'outbound')
  663. self.generate_container_operate_no_batch(container_obj, batch_id, allocation_target_location,"outbound")
  664. elif batch_info['class'] == 3:
  665. self.generate_task_no_batch(container, start_location, allocation_target_location,batch_id,1,'outbound')
  666. self.generate_move_container_operate(container_obj, allocation_target_location,"outbound")
  667. else:
  668. self.generate_task(container, start_location, allocation_target_location,batch_id,1,'outbound') # 生成任务
  669. self.generate_move_container_operate(container_obj, allocation_target_location,"outbound")
  670. current_task = ContainerWCSModel.objects.get(
  671. container=container,
  672. tasktype='outbound',
  673. working=1,
  674. )
  675. OutboundService.send_task_to_wcs(current_task)
  676. data_return = {
  677. 'code': '200',
  678. 'message': '任务下发成功',
  679. 'data': current_task.to_dict()
  680. }
  681. container_obj.target_location = allocation_target_location
  682. container_obj.save()
  683. if batch_info['class'] == 1 or batch_info['class'] == 3:
  684. self.inport_update_task(current_task.id, container_obj.id)
  685. http_status = status.HTTP_200_OK if data_return['code'] == '200' else status.HTTP_400_BAD_REQUEST
  686. loggertask.info(f"任务号:{current_task.tasknumber-20000000000},出库请求托盘:{container}返回结果:{data_return}")
  687. # 记录操作日志
  688. try:
  689. if data_return['code'] == '200':
  690. task_info = data_return.get('data', {})
  691. task_id = task_info.get('tasknumber', '未知') if isinstance(task_info, dict) else '未知'
  692. log_success_operation(
  693. request=request,
  694. operation_content=f"出库任务创建成功:托盘 {container},起始位置:{start_location},目标位置:{target_location},任务号:{task_id}",
  695. operation_level="other",
  696. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  697. object_id=container_obj.id if container_obj else None,
  698. module_name="WCS出库管理"
  699. )
  700. else:
  701. log_failure_operation(
  702. request=request,
  703. operation_content=f"出库任务创建失败:托盘 {container},错误:{data_return.get('message', '未知错误')}",
  704. operation_level="other",
  705. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  706. module_name="WCS出库管理"
  707. )
  708. except Exception as log_error:
  709. pass
  710. return Response(data_return, status=http_status)
  711. except Exception as e:
  712. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  713. # 记录异常日志
  714. try:
  715. log_failure_operation(
  716. request=request,
  717. operation_content=f"出库任务处理异常:托盘 {container},错误:{str(e)}",
  718. operation_level="other",
  719. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  720. module_name="WCS出库管理"
  721. )
  722. except Exception as log_error:
  723. pass
  724. return Response(
  725. {'code': '500', 'message': '服务器内部错误', 'data': None},
  726. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  727. )
  728. def get_container_wcs(self, request, *args, **kwargs):
  729. data = self.request.data
  730. container = data.get('container_number')
  731. current_location = data.get('current_location')
  732. logger.info(f"入库请求托盘:{container},请求位置:{current_location}")
  733. data_return = {}
  734. try:
  735. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  736. if not container_obj:
  737. data_return = {
  738. 'code': '400',
  739. 'message': '托盘编码不存在',
  740. 'data': data
  741. }
  742. # 记录失败日志
  743. try:
  744. log_failure_operation(
  745. request=request,
  746. operation_content=f"入库请求失败:托盘编码不存在 - {container}",
  747. operation_level="other",
  748. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  749. module_name="WCS入库管理"
  750. )
  751. except Exception as log_error:
  752. pass
  753. return Response(data_return, status=status.HTTP_400_BAD_REQUEST)
  754. # 更新托盘数据(部分更新)
  755. serializer = ContainerListPostSerializer(
  756. container_obj,
  757. data=data,
  758. partial=True # 允许部分字段更新
  759. )
  760. serializer.is_valid(raise_exception=True)
  761. serializer.save()
  762. # 检查是否已在目标位置
  763. if current_location == str(container_obj.target_location) and current_location!= '203' and current_location!= '103':
  764. logger.info(f"托盘 {container} 已在目标位置")
  765. data_return = {
  766. 'code': '200',
  767. 'message': '当前位置已是目标位置',
  768. 'data': data
  769. }
  770. else:
  771. current_task = ContainerWCSModel.objects.filter(
  772. container=container,
  773. tasktype='inbound',
  774. working = 1,
  775. ).exclude(status=300).first()
  776. if current_task:
  777. data_return = {
  778. 'code': '200',
  779. 'message': '任务已存在,重新下发',
  780. 'data': current_task.to_dict()
  781. }
  782. else:
  783. # todo: 这里的入库操作记录里面的记录的数量不对
  784. location_min_value,allocation_target_location, batch_info = AllocationService.allocate(container, current_location)
  785. batch_id = batch_info['number']
  786. if batch_info['class'] == 2:
  787. self.generate_task_no_batch(container, current_location, allocation_target_location,batch_id,location_min_value.c_number)
  788. self.generate_container_operate_no_batch(container_obj, batch_id, allocation_target_location)
  789. elif batch_info['class'] == 3:
  790. self.generate_task_no_batch(container, current_location, allocation_target_location,batch_id,location_min_value.c_number)
  791. self.generate_container_operate(container_obj, allocation_target_location)
  792. else:
  793. self.generate_task(container, current_location, allocation_target_location,batch_id,location_min_value.c_number) # 生成任务
  794. self.generate_container_operate(container_obj, allocation_target_location)
  795. current_task = ContainerWCSModel.objects.get(
  796. container=container,
  797. tasktype='inbound',
  798. working=1,
  799. )
  800. data_return = {
  801. 'code': '200',
  802. 'message': '任务下发成功',
  803. 'data': current_task.to_dict()
  804. }
  805. container_obj.target_location = allocation_target_location
  806. container_obj.save()
  807. if batch_info['class'] == 1 or batch_info['class'] == 3:
  808. self.inport_update_task(current_task.id, container_obj.id)
  809. http_status = status.HTTP_200_OK if data_return['code'] == '200' else status.HTTP_400_BAD_REQUEST
  810. # 尝试从返回数据中获取任务号用于日志
  811. try:
  812. task_info = data_return.get('data', {})
  813. if isinstance(task_info, dict) and 'taskNumber' in task_info:
  814. task_number = task_info['taskNumber'] - 20000000000 if isinstance(task_info['taskNumber'], int) else '未知'
  815. loggertask.info(f"任务号:{task_number},入库请求托盘:{container},起始位置:{current_location},返回结果:{data_return}")
  816. except Exception:
  817. loggertask.info(f"入库请求托盘:{container},起始位置:{current_location},返回结果:{data_return}")
  818. # 记录操作日志
  819. try:
  820. if data_return['code'] == '200':
  821. task_info = data_return.get('data', {})
  822. task_id = task_info.get('taskNumber', '未知') if isinstance(task_info, dict) else '未知'
  823. log_success_operation(
  824. request=request,
  825. operation_content=f"入库任务创建成功:托盘 {container},起始位置:{current_location},任务号:{task_id}",
  826. operation_level="other",
  827. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  828. object_id=container_obj.id if container_obj else None,
  829. module_name="WCS入库管理"
  830. )
  831. else:
  832. log_failure_operation(
  833. request=request,
  834. operation_content=f"入库任务创建失败:托盘 {container},错误:{data_return.get('message', '未知错误')}",
  835. operation_level="other",
  836. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  837. module_name="WCS入库管理"
  838. )
  839. except Exception as log_error:
  840. pass
  841. return Response(data_return, status=http_status)
  842. except Exception as e:
  843. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  844. # 记录异常日志
  845. try:
  846. log_failure_operation(
  847. request=request,
  848. operation_content=f"入库请求处理异常:托盘 {container},错误:{str(e)}",
  849. operation_level="other",
  850. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  851. module_name="WCS入库管理"
  852. )
  853. except Exception as log_error:
  854. pass
  855. return Response(
  856. {'code': '500', 'message': '服务器内部错误', 'data': None},
  857. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  858. )
  859. # def generate_container_operate(self, container_obj, bound_number,allocation_target_location):
  860. def generate_container_operate(self, container_obj, allocation_target_location):
  861. # 获取托盘中所有有效的批次明细(排除已删除和状态3的)
  862. container_detaillist = ContainerDetailModel.objects.filter(
  863. container=container_obj,
  864. is_delete=False
  865. ).exclude(status=3)
  866. # 优化查询 - 预取批次对象
  867. container_detaillist = container_detaillist.select_related('batch')
  868. # 创建批次数量字典
  869. batch_totals = {}
  870. for detail in container_detaillist:
  871. batch_id = detail.batch_id
  872. if batch_id not in batch_totals:
  873. batch_totals[batch_id] = {
  874. 'obj': detail.batch, # 批次对象
  875. 'total_qty': 0
  876. }
  877. batch_totals[batch_id]['total_qty'] += detail.goods_qty
  878. # 当前月份(单次计算多次使用)
  879. current_month = int(timezone.now().strftime("%Y%m"))
  880. current_time = timezone.now()
  881. current_location = container_obj.current_location
  882. # 为每个批次创建操作记录
  883. for batch_id, data in batch_totals.items():
  884. batch_obj = data['obj']
  885. goods_qty = data['total_qty']
  886. ContainerOperationModel.objects.create(
  887. month=current_month,
  888. container=container_obj,
  889. goods_code=batch_obj.goods_code,
  890. goods_desc=batch_obj.goods_desc,
  891. operation_type="inbound",
  892. batch_id=batch_obj.id,
  893. goods_qty=goods_qty,
  894. goods_weight=goods_qty,
  895. from_location=current_location,
  896. to_location=allocation_target_location,
  897. timestamp=current_time,
  898. operator="WMS",
  899. memo=f"WCS入库: 批次: {batch_obj.bound_number}, 数量: {goods_qty}" # 使用实际托盘中的数量
  900. )
  901. def generate_move_container_operate(self, container_obj, allocation_target_location,operate_type="adjust"):
  902. # 获取托盘中所有有效的批次明细
  903. container_detaillist = ContainerDetailModel.objects.filter(
  904. container=container_obj,
  905. is_delete=False
  906. ).exclude(status=3)
  907. # 优化查询 - 预取批次对象
  908. container_detaillist = container_detaillist.select_related('batch')
  909. # 创建批次数量字典
  910. batch_totals = {}
  911. for detail in container_detaillist:
  912. batch_id = detail.batch_id
  913. if batch_id not in batch_totals:
  914. batch_totals[batch_id] = {
  915. 'obj': detail.batch, # 批次对象
  916. 'total_qty': 0
  917. }
  918. batch_totals[batch_id]['total_qty'] += detail.goods_qty
  919. # 获取当前时间和位置信息
  920. current_month = int(timezone.now().strftime("%Y%m"))
  921. current_time = timezone.now()
  922. current_location = container_obj.current_location
  923. # 为每个批次创建操作记录
  924. for batch_id, data in batch_totals.items():
  925. batch_obj = data['obj']
  926. goods_qty = data['total_qty']
  927. ContainerOperationModel.objects.create(
  928. month=current_month,
  929. container=container_obj,
  930. goods_code=batch_obj.goods_code,
  931. goods_desc=batch_obj.goods_desc,
  932. operation_type=operate_type, # 操作类型改为移动
  933. batch_id=batch_obj.id,
  934. goods_qty=goods_qty,
  935. goods_weight=goods_qty,
  936. from_location=current_location,
  937. to_location=allocation_target_location,
  938. timestamp=current_time,
  939. operator="WMS",
  940. memo=f"托盘移动: 批次: {batch_obj.bound_number}, 数量: {goods_qty}"
  941. )
  942. def generate_move_container_operate_no_batch(self, container_obj, bound_number,allocation_target_location):
  943. ContainerOperationModel.objects.create(
  944. month = int(timezone.now().strftime("%Y%m")),
  945. container = container_obj,
  946. goods_code = 'container',
  947. goods_desc = '托盘组',
  948. operation_type ="adjust",
  949. goods_qty = 1,
  950. goods_weight = 0,
  951. from_location = container_obj.current_location,
  952. to_location= allocation_target_location,
  953. timestamp=timezone.now(),
  954. memo=f"托盘组移库:从{container_obj.current_location}移库到{allocation_target_location}"
  955. )
  956. def generate_container_operate_no_batch(self, container_obj, bound_number,allocation_target_location,operate_type="inbound"):
  957. ContainerOperationModel.objects.create(
  958. month = int(timezone.now().strftime("%Y%m")),
  959. container = container_obj,
  960. goods_code = 'container',
  961. goods_desc = '托盘组',
  962. operation_type =operate_type,
  963. goods_qty = 1,
  964. goods_weight = 0,
  965. from_location = container_obj.current_location,
  966. to_location= allocation_target_location,
  967. timestamp=timezone.now(),
  968. memo=f"WCSs手动出库库: 批次: {bound_number}, 数量: 1"
  969. )
  970. def generate_task(self, container, current_location, target_location,batch_id,location_c_number,tasktype='inbound'):
  971. batch = BoundBatchModel.objects.filter(bound_number=batch_id).first()
  972. batch_detail = BoundDetailModel.objects.filter(bound_batch=batch).first()
  973. if not batch:
  974. logger.error(f"批次号 {batch_id} 不存在")
  975. return False
  976. data_tosave = {
  977. 'container': container,
  978. 'batch': batch,
  979. 'batch_number': batch_id,
  980. 'batch_out': None,
  981. 'bound_list': batch_detail.bound_list,
  982. 'sequence': 1,
  983. 'order_number' :location_c_number,
  984. 'priority': 1,
  985. 'current_location': current_location,
  986. 'month': timezone.now().strftime('%Y%m'),
  987. 'target_location': target_location,
  988. 'tasktype': tasktype,
  989. 'status': 103,
  990. 'is_delete': False
  991. }
  992. # 生成唯一递增的 taskid
  993. last_task = ContainerWCSModel.objects.filter(
  994. month=data_tosave['month'],
  995. ).order_by('-tasknumber').first()
  996. if last_task:
  997. number_id = last_task.tasknumber + 1
  998. new_id = f"{number_id:05d}"
  999. else:
  1000. new_id = "00001"
  1001. number_id = f"{data_tosave['month']}{new_id}"
  1002. data_tosave['taskid'] = f"inbound-{data_tosave['month']}-{new_id}"
  1003. logger.info(f"生成入库任务: {data_tosave['taskid']}")
  1004. # 每月生成唯一递增的 taskNumber
  1005. data_tosave['tasknumber'] = number_id
  1006. ContainerWCSModel.objects.create(**data_tosave)
  1007. def generate_task_no_batch(self, container, current_location, target_location,batch_id,location_c_number,tasktype='inbound'):
  1008. data_tosave = {
  1009. 'container': container,
  1010. 'batch': None,
  1011. 'batch_number': batch_id,
  1012. 'batch_out': None,
  1013. 'bound_list': None,
  1014. 'sequence': 1,
  1015. 'order_number' :location_c_number,
  1016. 'priority': 1,
  1017. 'current_location': current_location,
  1018. 'month': timezone.now().strftime('%Y%m'),
  1019. 'target_location': target_location,
  1020. 'tasktype': tasktype,
  1021. 'status': 103,
  1022. 'is_delete': False
  1023. }
  1024. # 生成唯一递增的 taskid
  1025. last_task = ContainerWCSModel.objects.filter(
  1026. month=data_tosave['month'],
  1027. ).order_by('-tasknumber').first()
  1028. if last_task:
  1029. number_id = last_task.tasknumber + 1
  1030. new_id = f"{number_id:05d}"
  1031. else:
  1032. new_id = "00001"
  1033. number_id = f"{data_tosave['month']}{new_id}"
  1034. data_tosave['taskid'] = f"inbound-{data_tosave['month']}-{new_id}"
  1035. logger.info(f"生成入库任务: {data_tosave['taskid']}")
  1036. # 每月生成唯一递增的 taskNumber
  1037. data_tosave['tasknumber'] = number_id
  1038. ContainerWCSModel.objects.create(**data_tosave)
  1039. def update_container_wcs(self, request, *args, **kwargs):
  1040. data = self.request.data
  1041. loggertask.info(f"WCS返回任务: 任务号:{data.get('taskNumber')},请求托盘:{data.get('container_number')}, 请求位置:{data.get('current_location')},")
  1042. try:
  1043. # 前置校验
  1044. container_obj, error_response = self.validate_container(data)
  1045. if error_response:
  1046. # 记录验证失败日志
  1047. try:
  1048. log_failure_operation(
  1049. request=request,
  1050. operation_content=f"WCS任务更新失败:托盘验证失败 - {data.get('container_number', '未知')}",
  1051. operation_level="update",
  1052. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  1053. module_name="WCS任务管理"
  1054. )
  1055. except Exception as log_error:
  1056. pass
  1057. return error_response
  1058. # 更新托盘数据
  1059. if not self.update_container_data(container_obj, data):
  1060. return Response(
  1061. {'code': '400', 'message': '数据更新失败', 'data': data},
  1062. status=status.HTTP_400_BAD_REQUEST
  1063. )
  1064. # 处理位置逻辑
  1065. task = ContainerWCSModel.objects.filter(
  1066. container=container_obj.container_code,
  1067. tasktype='inbound'
  1068. ).first()
  1069. if self.is_already_at_target(container_obj, data.get('current_location')):
  1070. loggertask.info(f"WMS返回数据:任务号:{task.tasknumber-20000000000},托盘 {container_obj.container_code} 已在目标位置")
  1071. # 记录任务完成日志
  1072. try:
  1073. task_number = data.get('taskNumber', '未知')
  1074. log_success_operation(
  1075. request=request,
  1076. operation_content=f"WCS任务完成:托盘 {container_obj.container_code} 已到达目标位置,任务号:{task_number}",
  1077. operation_level="update",
  1078. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  1079. object_id=container_obj.id,
  1080. module_name="WCS任务管理"
  1081. )
  1082. except Exception as log_error:
  1083. pass
  1084. return self.handle_target_reached(container_obj, data)
  1085. elif task:
  1086. data_return = {
  1087. 'code': '200',
  1088. 'message': '任务已存在,重新下发',
  1089. 'data': task.to_dict()
  1090. }
  1091. loggertask.info(f"WMS返回数据:任务号:{task.tasknumber-20000000000},入库请求托盘:{container_obj.container_code},起始位置:{data.get('current_location')},目标位置:{container_obj.target_location},返回结果:{data_return}")
  1092. return Response(data_return, status=status.HTTP_200_OK)
  1093. else:
  1094. return self.handle_new_allocation(container_obj, data)
  1095. except Exception as e:
  1096. logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
  1097. # 记录异常日志
  1098. try:
  1099. log_failure_operation(
  1100. request=request,
  1101. operation_content=f"WCS任务更新异常:托盘 {data.get('container_number', '未知')},任务号:{data.get('taskNumber', '未知')},错误:{str(e)}",
  1102. operation_level="update",
  1103. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  1104. module_name="WCS任务管理"
  1105. )
  1106. except Exception as log_error:
  1107. pass
  1108. return Response({'code': '500', 'message': '服务器内部错误', 'data': None},
  1109. status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  1110. # ---------- 辅助函数 ----------
  1111. def validate_container(self, data):
  1112. """验证托盘是否存在"""
  1113. container = data.get('container_number')
  1114. container_obj = ContainerListModel.objects.filter(container_code=container).first()
  1115. if not container_obj:
  1116. return None, Response({
  1117. 'code': '400',
  1118. 'message': '托盘编码不存在',
  1119. 'data': data
  1120. }, status=status.HTTP_400_BAD_REQUEST)
  1121. return container_obj, None
  1122. def update_container_data(self, container_obj, data):
  1123. """更新托盘数据"""
  1124. serializer = ContainerListPostSerializer(
  1125. container_obj,
  1126. data=data,
  1127. partial=True
  1128. )
  1129. if serializer.is_valid():
  1130. serializer.save()
  1131. return True
  1132. return False
  1133. def is_already_at_target(self, container_obj, current_location):
  1134. """检查是否已在目标位置"""
  1135. # print (current_location)
  1136. # print (str(container_obj.target_location))
  1137. return current_location == str(container_obj.target_location)
  1138. def handle_target_reached(self, container_obj, data):
  1139. """处理已到达目标位置的逻辑"""
  1140. logger.info(f"托盘 {container_obj.container_code} 已在目标位置")
  1141. task = self.get_task_by_tasknumber(data)
  1142. self.update_pressure_values(task, container_obj)
  1143. # if task.working == 1:
  1144. # alloca = LocationAllocation()
  1145. # alloca.update_batch_goods_in_location_qty(container_obj.container_code, 1)
  1146. task = self.process_task_completion(data)
  1147. if not task:
  1148. return Response({'code': '400', 'message': '任务不存在', 'data': data},
  1149. status=status.HTTP_400_BAD_REQUEST)
  1150. if task and task.tasktype == 'inbound':
  1151. self.update_storage_system(container_obj)
  1152. if task and task.tasktype == 'outbound' and task.status == 300:
  1153. success = self.handle_outbound_completion(container_obj, task)
  1154. if not success:
  1155. return Response({'code': '500', 'message': '出库状态更新失败', 'data': None},
  1156. status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  1157. OutboundService.process_next_task()
  1158. if task and task.tasktype == 'check' and task.status == 300:
  1159. success = self.handle_outbound_completion(container_obj, task)
  1160. if not success:
  1161. return Response({'code': '500', 'message': '出库状态更新失败', 'data': None},
  1162. status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  1163. OutboundService.process_next_task()
  1164. return Response({
  1165. 'code': '200',
  1166. 'message': '当前位置已是目标位置',
  1167. 'data': data
  1168. }, status=status.HTTP_200_OK)
  1169. def get_task_by_tasknumber(self, data):
  1170. taskNumber = data.get('taskNumber') + 20000000000
  1171. task = ContainerWCSModel.objects.filter(tasknumber=taskNumber).first()
  1172. if task:
  1173. return task
  1174. else:
  1175. return None
  1176. def process_task_completion(self, data):
  1177. """处理任务完成状态"""
  1178. taskNumber = data.get('taskNumber') + 20000000000
  1179. task = ContainerWCSModel.objects.filter(tasknumber=taskNumber).first()
  1180. if task:
  1181. task.status = 300
  1182. task.message = '任务已完成'
  1183. task.working = 0
  1184. task.save()
  1185. return task
  1186. def update_pressure_values(self, task, container_obj):
  1187. """更新压力值计算"""
  1188. if task :
  1189. base_location_obj = base_location.objects.get(id=1)
  1190. layer = int(container_obj.target_location.split('-')[-1])
  1191. pressure_field = f"layer{layer}_pressure"
  1192. logger.info(f"更新压力值,压力字段:{pressure_field}")
  1193. current_pressure = getattr(base_location_obj, pressure_field, 0)
  1194. updated_pressure = max(current_pressure - task.working, 0)
  1195. setattr(base_location_obj, pressure_field, updated_pressure)
  1196. base_location_obj.save()
  1197. def update_storage_system(self, container_obj):
  1198. """更新仓储系统状态"""
  1199. allocator = LocationAllocation()
  1200. location_code = self.get_location_code(container_obj.target_location)
  1201. # 链式更新操作
  1202. update_operations = [
  1203. (allocator.update_location_status, location_code, 'occupied'),
  1204. (allocator.update_location_container_link, location_code, container_obj.container_code),
  1205. (allocator.update_container_detail_status, container_obj.container_code, 2)
  1206. ]
  1207. for func, *args in update_operations:
  1208. if not func(*args):
  1209. logger.error(f"操作失败: {func.__name__}")
  1210. return False
  1211. return True
  1212. def get_location_code(self, target_location):
  1213. """从目标位置解析获取位置编码"""
  1214. parts = target_location.split('-')
  1215. coordinate = f"{int(parts[1])}-{int(parts[2])}-{int(parts[3])}"
  1216. return LocationModel.objects.filter(coordinate=coordinate).first().location_code
  1217. def handle_new_allocation(self, container_obj, data):
  1218. """处理新库位分配逻辑"""
  1219. allocator = LocationAllocation()
  1220. container_code = container_obj.container_code
  1221. # 获取并验证库位分配
  1222. location = allocator.get_location_by_status(container_code, data.get('current_location'))
  1223. if not location or not self.perform_initial_allocation(allocator, location, container_code):
  1224. return Response({'code': '400', 'message': '库位分配失败', 'data': data},
  1225. status=status.HTTP_400_BAD_REQUEST)
  1226. # 生成目标位置并更新托盘
  1227. target_location = self.generate_target_location(location)
  1228. container_obj.target_location = target_location
  1229. container_obj.save()
  1230. # 创建任务并返回响应
  1231. task = self.create_inbound_task(container_code, data, target_location, location)
  1232. return Response({
  1233. 'code': '200',
  1234. 'message': '任务下发成功',
  1235. 'data': task.to_dict()
  1236. }, status=status.HTTP_200_OK)
  1237. def perform_initial_allocation(self, allocator, location, container_code):
  1238. """执行初始库位分配操作"""
  1239. operations = [
  1240. (allocator.update_location_status, location.location_code, 'reserved'),
  1241. (allocator.update_location_group_status, location.location_code),
  1242. (allocator.update_batch_status, container_code, '2'),
  1243. (allocator.update_location_group_batch, location, container_code),
  1244. (allocator.update_location_container_link, location.location_code, container_code),
  1245. (allocator.update_container_detail_status, container_code, 2)
  1246. ]
  1247. for func, *args in operations:
  1248. if not func(*args):
  1249. logger.error(f"分配操作失败: {func.__name__}")
  1250. return False
  1251. return True
  1252. def generate_target_location(self, location):
  1253. """生成目标位置字符串"""
  1254. return (
  1255. f"{location.warehouse_code}-"
  1256. f"{int(location.row):02d}-"
  1257. f"{int(location.col):02d}-"
  1258. f"{int(location.layer):02d}"
  1259. )
  1260. def create_inbound_task(self, container_code, data, target_location, location):
  1261. """创建入库任务"""
  1262. batch_id = LocationAllocation().get_batch(container_code)
  1263. self.generate_task(
  1264. container_code,
  1265. data.get('current_location'),
  1266. target_location,
  1267. batch_id,
  1268. location.c_number
  1269. )
  1270. task = ContainerWCSModel.objects.get(container=container_code, tasktype='inbound')
  1271. self.inport_update_task(task.id, container_code)
  1272. return task
  1273. def inport_update_task(self, wcs_id,container_id):
  1274. try:
  1275. task_obj = ContainerWCSModel.objects.filter(id=wcs_id).first()
  1276. if task_obj:
  1277. container_detail_obj = ContainerDetailModel.objects.filter(container=container_id,is_delete=False).all()
  1278. if container_detail_obj:
  1279. for detail in container_detail_obj:
  1280. # 保存到数据库
  1281. batch = BoundDetailModel.objects.filter(bound_batch_id=detail.batch.id).first()
  1282. TaskModel.objects.create(
  1283. task_wcs = task_obj,
  1284. container_detail = detail,
  1285. batch_detail = batch
  1286. )
  1287. logger.info(f"入库任务 {wcs_id} 已更新")
  1288. else:
  1289. logger.info(f"入库任务 {container_id} 批次不存在")
  1290. else:
  1291. logger.info(f"入库任务 {wcs_id} 不存在")
  1292. except Exception as e:
  1293. logger.error(f"处理入库任务时发生错误: {str(e)}", exc_info=True)
  1294. return Response(
  1295. {'code': '500', 'message': '服务器内部错误', 'data': None},
  1296. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  1297. )
  1298. def release_location(self,request):
  1299. """释放库位"""
  1300. """添加权限管理"""
  1301. token = self.request.META.get('HTTP_TOKEN')
  1302. appid = self.request.META.get('HTTP_APPID')
  1303. if not token:
  1304. return Response({'code': '401', 'message': '请登录', 'data': None},
  1305. status=status.HTTP_200_OK)
  1306. user = StaffListModel.objects.filter(openid=token,appid=appid).first()
  1307. if not user:
  1308. return Response({'code': '401', 'message': '请登录', 'data': None},
  1309. status=status.HTTP_200_OK)
  1310. if user.staff_type not in ['Supervisor', 'Manager','Admin','管理员','经理','主管']:
  1311. return Response({'code': '401', 'message': '无权限', 'data': None},
  1312. status=status.HTTP_200_OK)
  1313. try:
  1314. location_release = request.data.get('location_release')
  1315. location_row = location_release.split('-')[1]
  1316. location_col = location_release.split('-')[2]
  1317. location_layer = location_release.split('-')[3]
  1318. location= LocationModel.objects.filter(row=location_row, col=location_col, layer=location_layer).first()
  1319. location_code = location.location_code
  1320. allocator = LocationAllocation()
  1321. with transaction.atomic():
  1322. if not allocator.release_location(location_code):
  1323. raise Exception("解除库位关联失败")
  1324. if not allocator.update_location_status(location_code, 'available'):
  1325. raise Exception("库位状态更新失败")
  1326. if not allocator.update_location_group_status(location_code):
  1327. raise Exception("库位组状态更新失败")
  1328. # 记录成功日志
  1329. try:
  1330. log_success_operation(
  1331. request=request,
  1332. operation_content=f"释放库位成功:库位编码 {location_code},库位位置 {location_release}",
  1333. operation_level="update",
  1334. operator=user.staff_name if user else None,
  1335. object_id=location.id if location else None,
  1336. module_name="WCS库位管理"
  1337. )
  1338. except Exception as log_error:
  1339. pass
  1340. except Exception as e:
  1341. logger.error(f"解除库位关联失败: {str(e)}")
  1342. # 记录失败日志
  1343. try:
  1344. location_info = request.data.get('location_release', '未知') if hasattr(request, 'data') else '未知'
  1345. log_failure_operation(
  1346. request=request,
  1347. operation_content=f"释放库位失败:库位位置 {location_info},错误:{str(e)}",
  1348. operation_level="update",
  1349. operator=user.staff_name if user else None,
  1350. module_name="WCS库位管理"
  1351. )
  1352. except Exception as log_error:
  1353. pass
  1354. return Response({'code': '500', 'message': e, 'data': None},
  1355. status=status.HTTP_200_OK)
  1356. return Response({'code': '200', 'message': '解除库位关联成功', 'data': None},
  1357. status=status.HTTP_200_OK)
  1358. def handle_outbound_completion(self, container_obj, task):
  1359. """处理出库完成后的库位释放和状态更新"""
  1360. try:
  1361. allocator = LocationAllocation()
  1362. location_task = task.current_location
  1363. if location_task == '103' or location_task == '203':
  1364. return True
  1365. else:
  1366. location_row = location_task.split('-')[1]
  1367. location_col = location_task.split('-')[2]
  1368. location_layer = location_task.split('-')[3]
  1369. location= LocationModel.objects.filter(row=location_row, col=location_col, layer=location_layer).first()
  1370. location_code = location.location_code
  1371. # 事务确保原子性
  1372. with transaction.atomic():
  1373. # 解除库位与托盘的关联
  1374. if not allocator.release_location(location_code):
  1375. raise Exception("解除库位关联失败")
  1376. # 更新库位状态为可用
  1377. if not allocator.update_location_status(location_code, 'available'):
  1378. raise Exception("库位状态更新失败")
  1379. # 更新库位组的统计信息
  1380. self.handle_group_location_status(location_code, location.location_group)
  1381. # 更新托盘状态为已出库(假设状态3表示已出库)
  1382. container_obj.status = 3
  1383. container_obj.save()
  1384. return True
  1385. except Exception as e:
  1386. logger.error(f"出库完成处理失败: {str(e)}")
  1387. return False
  1388. def handle_group_location_status(self,location_code,location_group):
  1389. """
  1390. 处理库位组和库位的关联关系
  1391. :param location_code: 库位编码
  1392. :param location_group: 库位组编码
  1393. :return:
  1394. """
  1395. # 1. 获取库位空闲状态的库位数目
  1396. location_obj_number = LocationModel.objects.filter(
  1397. location_group=location_group,
  1398. status='available'
  1399. ).all().count()
  1400. # 2. 获取库位组对象
  1401. logger.info(f"库位组 {location_group} 下的库位数目:{location_obj_number}")
  1402. # 1. 获取库位和库位组的关联关系
  1403. location_group_obj = LocationGroupModel.objects.filter(
  1404. group_code=location_group
  1405. ).first()
  1406. if not location_group_obj:
  1407. logger.info(f"库位组 {location_group} 不存在")
  1408. return None
  1409. else:
  1410. if location_obj_number == 0:
  1411. # 库位组库位已满,更新库位组状态为full
  1412. location_group_obj.status = 'full'
  1413. location_group_obj.save()
  1414. elif location_obj_number < location_group_obj.max_capacity:
  1415. location_group_obj.status = 'occupied'
  1416. location_group_obj.save()
  1417. else:
  1418. location_group_obj.status = 'available'
  1419. location_group_obj.current_batch = ''
  1420. location_group_obj.current_goods_code = ''
  1421. location_group_obj.save()
  1422. # PDA组盘入库 将扫描到的托盘编码和批次信息保存到数据库
  1423. # 1. 先查询托盘对象,如果不存在,则创建托盘对象
  1424. # 2. 循环处理每个批次,查询批次对象,
  1425. # 3. 更新批次数据(根据业务规则)
  1426. # 4. 保存到数据库
  1427. # 5. 保存操作记录到数据库
  1428. class ContainerDetailViewSet(viewsets.ModelViewSet):
  1429. """
  1430. retrieve:
  1431. Response a data list(get)
  1432. list:
  1433. Response a data list(all)
  1434. create:
  1435. Create a data line(post)
  1436. delete:
  1437. Delete a data line(delete)
  1438. """
  1439. # authentication_classes = [] # 禁用所有认证类
  1440. # permission_classes = [AllowAny] # 允许任意访问
  1441. pagination_class = MyPageNumberPagination
  1442. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1443. ordering_fields = ['id', "create_time", "update_time", ]
  1444. filter_class = ContainerDetailFilter
  1445. def get_project(self):
  1446. try:
  1447. id = self.kwargs.get('pk')
  1448. return id
  1449. except:
  1450. return None
  1451. def get_queryset(self):
  1452. id = self.get_project()
  1453. if self.request.user:
  1454. if id is None:
  1455. return ContainerDetailModel.objects.filter( is_delete=False)
  1456. else:
  1457. return ContainerDetailModel.objects.filter( id=id, is_delete=False)
  1458. else:
  1459. return ContainerDetailModel.objects.none()
  1460. def get_serializer_class(self):
  1461. if self.action in ['list', 'destroy','retrieve']:
  1462. return ContainerDetailGetSerializer
  1463. elif self.action in ['create']:
  1464. return ContainerDetailPostSerializer
  1465. elif self.action in ['update']:
  1466. return ContainerDetailPutSerializer
  1467. else:
  1468. return self.http_method_not_allowed(request=self.request)
  1469. def create(self, request, *args, **kwargs):
  1470. data = self.request.data
  1471. from .container_operate import ContainerService
  1472. ContainerService.create_container_operation(data,logger=logger)
  1473. # 将处理后的数据返回(或根据业务需求保存到数据库)
  1474. res_data={
  1475. "code": "200",
  1476. "msg": "Success Create",
  1477. "data": data
  1478. }
  1479. try:
  1480. log_success_operation(
  1481. request=self.request,
  1482. operation_content=f"创建托盘操作:{data.get('container_code', '未知')}",
  1483. operation_level="new",
  1484. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1485. module_name="托盘管理"
  1486. )
  1487. except Exception as e:
  1488. pass
  1489. return Response(res_data, status=200)
  1490. def update(self, request, pk):
  1491. qs = self.get_object()
  1492. data = self.request.data
  1493. serializer = self.get_serializer(qs, data=data)
  1494. serializer.is_valid(raise_exception=True)
  1495. serializer.save()
  1496. headers = self.get_success_headers(serializer.data)
  1497. try:
  1498. log_success_operation(
  1499. request=self.request,
  1500. operation_content=f"更新托盘详情 ID:{pk}",
  1501. operation_level="update",
  1502. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1503. object_id=pk,
  1504. module_name="托盘管理"
  1505. )
  1506. except Exception as e:
  1507. pass
  1508. return Response(serializer.data, status=200, headers=headers)
  1509. def destroy(self, request, pk):
  1510. qs = self.get_object()
  1511. qs.is_delete = True
  1512. qs.save()
  1513. try:
  1514. log_success_operation(
  1515. request=self.request,
  1516. operation_content=f"删除托盘详情 ID:{pk}",
  1517. operation_level="delete",
  1518. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1519. object_id=pk,
  1520. module_name="托盘管理"
  1521. )
  1522. except Exception as e:
  1523. pass
  1524. return Response({'code': 200,'message': '删除成功', 'data': None}, status=200)
  1525. def containerdetail_list(self, request):
  1526. """
  1527. 获取托盘详情列表
  1528. """
  1529. try:
  1530. container_id = request.query_params.get('container')
  1531. if not container_id:
  1532. return Response(
  1533. {'code': 400, 'message': '缺少托盘ID参数', 'data': None},
  1534. status=status.HTTP_400_BAD_REQUEST
  1535. )
  1536. # 获取托盘对象
  1537. try:
  1538. container = ContainerListModel.objects.get(id=container_id)
  1539. except ContainerListModel.DoesNotExist:
  1540. return Response(
  1541. {'code': 404, 'message': '指定托盘不存在', 'data': None},
  1542. status=status.HTTP_404_NOT_FOUND
  1543. )
  1544. # 查询关联批次明细(排除状态0和3)
  1545. details = ContainerDetailModel.objects.filter(
  1546. container=container,is_delete=False
  1547. ).exclude(
  1548. status__in=[0, 3]
  1549. ).select_related('batch')
  1550. details_serializer = ContainerDetailSimpleGetSerializer(details, many=True)
  1551. return Response(
  1552. {'code': 200, 'message': 'Success', 'data': details_serializer.data},
  1553. status=status.HTTP_200_OK
  1554. )
  1555. except Exception as e:
  1556. return Response(
  1557. {'code': 500, 'message': f'服务器错误: {str(e)}', 'data': None},
  1558. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  1559. )
  1560. def locationdetail_list(self, request):
  1561. """
  1562. 获取库位所处托盘的信息(按批次号 + 数量分组)
  1563. 新增批次总量统计功能
  1564. """
  1565. try:
  1566. container_id = request.query_params.get('container')
  1567. if not container_id:
  1568. return Response(
  1569. {'code': 400, 'message': '缺少托盘ID参数', 'data': None},
  1570. status=status.HTTP_400_BAD_REQUEST
  1571. )
  1572. # 获取托盘对象
  1573. try:
  1574. container = ContainerListModel.objects.get(id=container_id)
  1575. except ContainerListModel.DoesNotExist:
  1576. return Response(
  1577. {'code': 404, 'message': '指定托盘不存在', 'data': None},
  1578. status=status.HTTP_404_NOT_FOUND
  1579. )
  1580. # 查询关联批次明细(排除状态0和3)
  1581. details = ContainerDetailModel.objects.filter(
  1582. container=container,is_delete=False
  1583. ).exclude(
  1584. status__in=[0, 3]
  1585. ).select_related('batch')
  1586. if not details.exists():
  1587. return Response(
  1588. {'code': 404, 'message': '未找到有效批次数据', 'data': None},
  1589. status=status.HTTP_404_NOT_FOUND
  1590. )
  1591. # 按批次号 + 数量分组统计
  1592. batch_dict = {}
  1593. batch_qty_dict = defaultdict(int) # 使用默认字典自动初始化
  1594. for detail in details:
  1595. if not detail.batch:
  1596. continue
  1597. bound_number = detail.batch.bound_number
  1598. goods_qty = detail.goods_qty - detail.goods_out_qty # 剔除出库数量
  1599. # 组合键:批次号 + 当前数量
  1600. batch_key = (bound_number, goods_qty)
  1601. batch_qty_dict[bound_number] += goods_qty # 自动处理键初始化
  1602. # 分组统计
  1603. if batch_key not in batch_dict:
  1604. batch_obj = BoundBatchModel.objects.filter( bound_number=bound_number).first()
  1605. batch_dict[batch_key] = {
  1606. "goods_code": detail.goods_code,
  1607. "goods_desc": detail.goods_desc,
  1608. "goods_qty": goods_qty,
  1609. "goods_class": detail.goods_class,
  1610. "goods_package": batch_obj.goods_package,
  1611. "batch_total_qty": batch_obj.goods_qty,
  1612. "batch_total_in_qty": batch_obj.goods_in_qty - batch_obj.goods_out_qty,
  1613. "status": detail.status,
  1614. "group_qty": 1,
  1615. "create_time": detail.create_time,
  1616. }
  1617. else:
  1618. batch_dict[batch_key]["group_qty"] += 1
  1619. # 重构数据结构
  1620. results = []
  1621. for (bound_number, qty), data in batch_dict.items():
  1622. results.append({
  1623. **data,
  1624. "bound_number": bound_number,
  1625. "current_qty": qty,
  1626. "total_batch_qty": batch_qty_dict[bound_number] # 添加批次总量
  1627. })
  1628. batch_totals =[]
  1629. for bound_number, qty in batch_qty_dict.items():
  1630. batch_totals.append({
  1631. "bound_number": bound_number,
  1632. "total_batch_qty": qty
  1633. })
  1634. return Response(
  1635. {
  1636. "code": 200,
  1637. "message": "Success",
  1638. "data": {
  1639. "container_code": container.container_code,
  1640. "count": len(results),
  1641. "results": results,
  1642. "batch_totals": batch_totals # 可选:单独返回批次总量
  1643. }
  1644. },
  1645. status=status.HTTP_200_OK
  1646. )
  1647. except Exception as e:
  1648. return Response(
  1649. {'code': 500, 'message': f'服务器错误: {str(e)}', 'data': None},
  1650. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  1651. )
  1652. def pdadetail_list(self, request):
  1653. """
  1654. 获取PDA组盘入库的托盘详情列表
  1655. """
  1656. try:
  1657. container_code = request.query_params.get('container_code')
  1658. if not container_code:
  1659. return Response(
  1660. {'code': 400, 'message': '缺少托盘编码参数', 'data': None},
  1661. status=status.HTTP_200_OK
  1662. )
  1663. # 获取托盘对象
  1664. try:
  1665. container = ContainerListModel.objects.get(container_code=container_code)
  1666. except ContainerListModel.DoesNotExist:
  1667. return Response(
  1668. {'code': 404, 'message': '指定托盘不存在', 'data': None},
  1669. status=status.HTTP_200_OK
  1670. )
  1671. # 查询关联批次明细(排除状态0和3)
  1672. details = ContainerDetailModel.objects.filter(
  1673. container=container,is_delete=False
  1674. ).exclude(
  1675. status__in=[0, 3]
  1676. ).select_related('batch')
  1677. if not details.exists():
  1678. return Response(
  1679. {'code': 404, 'message': '未找到有效批次数据', 'data': None},
  1680. status=status.HTTP_200_OK
  1681. )
  1682. # 按批次号 + 数量分组统计
  1683. batch_dict = {}
  1684. batch_qty_dict = defaultdict(int) # 使用默认字典自动初始化
  1685. for detail in details:
  1686. if not detail.batch:
  1687. continue
  1688. bound_number = detail.batch.bound_number
  1689. goods_qty = detail.goods_qty - detail.goods_out_qty # 剔除出库数量
  1690. # 组合键:批次号 + 当前数量
  1691. batch_key = (bound_number, goods_qty)
  1692. batch_qty_dict[bound_number] += goods_qty # 自动处理键初始化
  1693. # 分组统计
  1694. if batch_key not in batch_dict:
  1695. batch_obj = BoundBatchModel.objects.filter( bound_number=bound_number).first()
  1696. batch_dict[batch_key] = {
  1697. "goods_code": detail.goods_code,
  1698. "goods_desc": detail.goods_desc,
  1699. "goods_qty": goods_qty,
  1700. "goods_class": detail.goods_class,
  1701. "goods_package": batch_obj.goods_package,
  1702. "batch_total_qty": batch_obj.goods_qty,
  1703. "batch_total_in_qty": batch_obj.goods_in_qty - batch_obj.goods_out_qty,
  1704. "status": detail.status,
  1705. "group_qty": 1,
  1706. "create_time": detail.create_time,
  1707. }
  1708. else:
  1709. batch_dict[batch_key]["group_qty"] += 1
  1710. # 重构数据结构
  1711. results = []
  1712. for (bound_number, qty), data in batch_dict.items():
  1713. results.append({
  1714. **data,
  1715. "bound_number": bound_number,
  1716. "current_qty": qty,
  1717. "total_batch_qty": batch_qty_dict[bound_number] # 添加批次总量
  1718. })
  1719. batch_totals =[]
  1720. for bound_number, qty in batch_qty_dict.items():
  1721. batch_totals.append({
  1722. "bound_number": bound_number,
  1723. "total_batch_qty": qty
  1724. })
  1725. return Response(
  1726. {
  1727. "code": 200,
  1728. "message": "Success",
  1729. "data": {
  1730. "count": len(results),
  1731. "results": results,
  1732. "batch_totals": batch_totals # 可选:单独返回批次总量
  1733. }
  1734. },
  1735. status=status.HTTP_200_OK
  1736. )
  1737. except Exception as e:
  1738. return Response(
  1739. {'code': 500, 'message': f'服务器错误: {str(e)}', 'data': None},
  1740. status=status.HTTP_200_OK
  1741. )
  1742. # 托盘操作历史记录
  1743. class ContainerOperateViewSet(viewsets.ModelViewSet):
  1744. """
  1745. retrieve:
  1746. Response a data list(get)
  1747. list:
  1748. Response a data list(all)
  1749. create:
  1750. Create a data line(post)
  1751. delete:
  1752. Delete a data line(delete)
  1753. """
  1754. # authentication_classes = [] # 禁用所有认证类
  1755. # permission_classes = [AllowAny] # 允许任意访问
  1756. pagination_class = MyPageNumberPagination
  1757. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1758. ordering_fields = ['id', "timestamp" ]
  1759. filter_class = ContainerOperationFilter
  1760. def get_project(self):
  1761. try:
  1762. id = self.kwargs.get('pk')
  1763. return id
  1764. except:
  1765. return None
  1766. def get_queryset(self):
  1767. id = self.get_project()
  1768. if self.request.user:
  1769. if id is None:
  1770. return ContainerOperationModel.objects.filter( is_delete=False)
  1771. else:
  1772. return ContainerOperationModel.objects.filter( id=id, is_delete=False)
  1773. else:
  1774. return ContainerOperationModel.objects.none()
  1775. def get_serializer_class(self):
  1776. if self.action in ['list', 'destroy','retrieve']:
  1777. return ContainerOperationGetSerializer
  1778. elif self.action in ['create', 'update']:
  1779. return ContainerOperationPostSerializer
  1780. else:
  1781. return self.http_method_not_allowed(request=self.request)
  1782. def create(self, request, *args, **kwargs):
  1783. data = self.request.data
  1784. try:
  1785. serializer = self.get_serializer(data=data)
  1786. serializer.is_valid(raise_exception=True)
  1787. serializer.save()
  1788. headers = self.get_success_headers(serializer.data)
  1789. # 记录成功日志
  1790. try:
  1791. log_success_operation(
  1792. request=self.request,
  1793. operation_content=f"创建托盘操作记录:{data.get('container_code', '未知')}",
  1794. operation_level="new",
  1795. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1796. object_id=serializer.data.get('id'),
  1797. module_name="托盘管理"
  1798. )
  1799. except Exception as e:
  1800. pass
  1801. return Response(serializer.data, status=200, headers=headers)
  1802. except Exception as e:
  1803. # 记录失败日志
  1804. try:
  1805. log_failure_operation(
  1806. request=self.request,
  1807. operation_content=f"创建托盘操作记录失败:{str(e)}",
  1808. operation_level="new",
  1809. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1810. module_name="托盘管理"
  1811. )
  1812. except Exception as log_error:
  1813. pass
  1814. raise
  1815. def update(self, request, pk):
  1816. qs = self.get_object()
  1817. data = self.request.data
  1818. try:
  1819. serializer = self.get_serializer(qs, data=data)
  1820. serializer.is_valid(raise_exception=True)
  1821. serializer.save()
  1822. headers = self.get_success_headers(serializer.data)
  1823. # 记录成功日志
  1824. try:
  1825. log_success_operation(
  1826. request=self.request,
  1827. operation_content=f"更新托盘操作记录 ID:{pk}",
  1828. operation_level="update",
  1829. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1830. object_id=pk,
  1831. module_name="托盘管理"
  1832. )
  1833. except Exception as e:
  1834. pass
  1835. return Response(serializer.data, status=200, headers=headers)
  1836. except Exception as e:
  1837. # 记录失败日志
  1838. try:
  1839. log_failure_operation(
  1840. request=self.request,
  1841. operation_content=f"更新托盘操作记录失败 ID:{pk},错误: {str(e)}",
  1842. operation_level="update",
  1843. operator=self.request.auth.name if hasattr(self.request, 'auth') and self.request.auth else None,
  1844. object_id=pk,
  1845. module_name="托盘管理"
  1846. )
  1847. except Exception as log_error:
  1848. pass
  1849. raise
  1850. # 出库任务生成
  1851. class OutboundService:
  1852. @staticmethod
  1853. def generate_task_id():
  1854. """生成唯一任务ID(格式: outbound-年月-顺序号)"""
  1855. month = timezone.now().strftime("%Y%m")
  1856. last_task = ContainerWCSModel.objects.filter(
  1857. tasktype='outbound',
  1858. month=int(month)
  1859. ).order_by('-sequence').first()
  1860. sequence = last_task.sequence + 1 if last_task else 1
  1861. return f"outbound-{month}-{sequence:05d}"
  1862. @staticmethod
  1863. def send_task_to_wcs(task):
  1864. """异步发送任务到WCS(非阻塞版本)"""
  1865. # 提取任务关键数据用于线程(避免直接传递ORM对象)
  1866. task_data = {
  1867. 'task_id': task.pk, # 使用主键而不是对象
  1868. 'send_data': {
  1869. "code":'200',
  1870. "message": task.message,
  1871. "data":{
  1872. "taskid": task.taskid,
  1873. "container": task.container,
  1874. "current_location": task.current_location,
  1875. "target_location": task.target_location,
  1876. "tasktype": task.tasktype,
  1877. "month": task.month,
  1878. "message": task.message,
  1879. "status": task.status,
  1880. "taskNumber": task.tasknumber-20000000000,
  1881. "order_number":task.order_number,
  1882. "sequence":task.sequence
  1883. }
  1884. }
  1885. }
  1886. loggertask.info(f"任务号:{task.tasknumber-20000000000}任务发送请求:{task.container},起始位置:{task.current_location},目标位置:{task.target_location},返回结果:{task_data}")
  1887. # 创建并启动线程
  1888. thread = threading.Thread(
  1889. target=OutboundService._async_send_handler,
  1890. kwargs=task_data,
  1891. daemon=True # 守护线程(主程序退出时自动终止)
  1892. )
  1893. thread.start()
  1894. return True # 立即返回表示已开始处理
  1895. @staticmethod
  1896. def _async_send_handler(task_id, send_data):
  1897. """异步处理的实际工作函数"""
  1898. try:
  1899. # 每个线程需要独立的数据库连接
  1900. close_old_connections()
  1901. # 重新获取任务对象(确保使用最新数据)
  1902. task = ContainerWCSModel.objects.get(pk=task_id)
  1903. # 发送第一个请求(不处理结果)
  1904. requests.post(
  1905. "http://127.0.0.1:8008/container/batch/",
  1906. json=send_data,
  1907. timeout=10
  1908. )
  1909. # 发送关键请求
  1910. response = requests.post(
  1911. "http://192.168.18.200:1616/wcs/WebApi/getOutTask",
  1912. json=send_data,
  1913. timeout=10
  1914. )
  1915. # 处理响应
  1916. if response.status_code == 200:
  1917. task.status = 200
  1918. task.save()
  1919. logger.info(f"任务 {task.taskid} 已发送")
  1920. else:
  1921. logger.error(f"WCS返回错误: {response.text}")
  1922. except Exception as e:
  1923. logger.error(f"发送失败: {str(e)}")
  1924. finally:
  1925. close_old_connections() # 清理数据库连接
  1926. @staticmethod
  1927. def create_initial_tasks(container_list,bound_list_id):
  1928. """生成初始任务队列"""
  1929. with transaction.atomic():
  1930. current_WCS = ContainerWCSModel.objects.filter(tasktype='outbound',bound_list_id = bound_list_id).first()
  1931. if current_WCS:
  1932. logger.error(f"当前{bound_list_id}已有出库任务")
  1933. return False
  1934. tasks = []
  1935. start_sequence = ContainerWCSModel.objects.filter(tasktype='outbound').count() + 1
  1936. tasknumber = ContainerWCSModel.objects.filter().count()
  1937. tasknumber_index = 1
  1938. for index, container in enumerate(container_list, start=start_sequence):
  1939. container_obj = ContainerListModel.objects.filter(id =container['container_number']).first()
  1940. if container_obj.current_location != container_obj.target_location:
  1941. logger.error(f"托盘 {container_obj.container_code} 未到达目的地,不生成任务")
  1942. return False
  1943. OutBoundDetail_obj = OutBoundDetailModel.objects.filter(bound_list=bound_list_id,bound_batch_number_id=container['batch_id']).first()
  1944. if not OutBoundDetail_obj:
  1945. logger.error(f"批次 {container['batch_id']} 不存在")
  1946. return False
  1947. month = int(timezone.now().strftime("%Y%m"))
  1948. task = ContainerWCSModel(
  1949. taskid=OutboundService.generate_task_id(),
  1950. batch = OutBoundDetail_obj.bound_batch_number,
  1951. batch_out = OutBoundDetail_obj.bound_batch,
  1952. bound_list = OutBoundDetail_obj.bound_list,
  1953. sequence=index,
  1954. order_number = container['c_number'],
  1955. priority=100,
  1956. tasknumber = month*100000+tasknumber_index+tasknumber,
  1957. container=container_obj.container_code,
  1958. current_location=container_obj.current_location,
  1959. target_location="103",
  1960. tasktype="outbound",
  1961. month=int(timezone.now().strftime("%Y%m")),
  1962. message="等待出库",
  1963. status=100,
  1964. )
  1965. tasknumber_index += 1
  1966. tasks.append(task)
  1967. container_obj = ContainerListModel.objects.filter(container_code=task.container).first()
  1968. container_obj.target_location = task.target_location
  1969. container_obj.save()
  1970. ContainerWCSModel.objects.bulk_create(tasks)
  1971. logger.info(f"已创建 {len(tasks)} 个初始任务")
  1972. @staticmethod
  1973. def create_initial_check_tasks(container_list,batch_id):
  1974. """生成初始任务队列"""
  1975. with transaction.atomic():
  1976. current_WCS = ContainerWCSModel.objects.filter(tasktype='check',batch_id = batch_id,is_delete=False,working=1).first()
  1977. if current_WCS:
  1978. logger.error(f"当前{batch_id}已有检查任务")
  1979. return False
  1980. tasks = []
  1981. start_sequence = ContainerWCSModel.objects.filter(tasktype='check').count() + 1
  1982. tasknumber = ContainerWCSModel.objects.filter().count()
  1983. tasknumber_index = 1
  1984. for index, container in enumerate(container_list, start=start_sequence):
  1985. container_obj = ContainerListModel.objects.filter(id =container['container_number']).first()
  1986. if container_obj.current_location != container_obj.target_location:
  1987. logger.error(f"托盘 {container_obj.container_code} 未到达目的地,不生成任务")
  1988. return False
  1989. batch_obj = BoundBatchModel.objects.filter(id =batch_id).first()
  1990. month = int(timezone.now().strftime("%Y%m"))
  1991. task = ContainerWCSModel(
  1992. taskid=OutboundService.generate_task_id(),
  1993. batch = batch_obj,
  1994. batch_out = None,
  1995. bound_list = None,
  1996. sequence=index,
  1997. order_number = container['c_number'],
  1998. priority=100,
  1999. tasknumber = month*100000+tasknumber_index+tasknumber,
  2000. container=container_obj.container_code,
  2001. current_location=container_obj.current_location,
  2002. target_location="103",
  2003. tasktype="check",
  2004. month=int(timezone.now().strftime("%Y%m")),
  2005. message="等待出库",
  2006. status=100,
  2007. )
  2008. tasknumber_index += 1
  2009. tasks.append(task)
  2010. container_obj = ContainerListModel.objects.filter(container_code=task.container).first()
  2011. container_obj.target_location = task.target_location
  2012. container_obj.save()
  2013. ContainerWCSModel.objects.bulk_create(tasks)
  2014. logger.info(f"已创建 {len(tasks)} 个初始任务")
  2015. @staticmethod
  2016. def insert_new_tasks(new_tasks):
  2017. """动态插入新任务并重新排序"""
  2018. with transaction.atomic():
  2019. pending_tasks = list(ContainerWCSModel.objects.filter(status=100))
  2020. # 插入新任务
  2021. for new_task_data in new_tasks:
  2022. new_task = ContainerWCSModel(
  2023. taskid=OutboundService.generate_task_id(),
  2024. priority=new_task_data.get('priority', 100),
  2025. container=new_task_data['container'],
  2026. current_location=new_task_data['current_location'],
  2027. target_location=new_task_data.get('target_location', 'OUT01'),
  2028. tasktype="outbound",
  2029. month=int(timezone.now().strftime("%Y%m")),
  2030. message="等待出库",
  2031. status=100,
  2032. )
  2033. # 找到插入位置
  2034. insert_pos = 0
  2035. for i, task in enumerate(pending_tasks):
  2036. if new_task.priority < task.priority:
  2037. insert_pos = i
  2038. break
  2039. else:
  2040. insert_pos = len(pending_tasks)
  2041. pending_tasks.insert(insert_pos, new_task)
  2042. # 重新分配顺序号
  2043. for i, task in enumerate(pending_tasks, start=1):
  2044. task.sequence = i
  2045. if task.pk is None:
  2046. task.save()
  2047. else:
  2048. task.save(update_fields=['sequence'])
  2049. logger.info(f"已插入 {len(new_tasks)} 个新任务")
  2050. @staticmethod
  2051. def process_next_task():
  2052. """处理下一个任务 - 优化:同一批次连续出,支持一次下发两条任务"""
  2053. # 获取待处理任务,优先按批次排序(同一批次连续出),同一批次内按sequence排序
  2054. # 使用Case处理batch_out为None的情况,确保有批次的任务优先
  2055. from django.db.models import F, Case, When, IntegerField
  2056. def get_pending_tasks():
  2057. """获取待处理任务查询集"""
  2058. return ContainerWCSModel.objects.filter(
  2059. status=100,
  2060. working=1,
  2061. is_delete=False
  2062. ).annotate(
  2063. # 为排序添加批次ID字段,None值排最后
  2064. batch_out_id_for_sort=Case(
  2065. When(batch_out__isnull=False, then=F('batch_out_id')),
  2066. default=999999999, # None值使用大数字,排到最后
  2067. output_field=IntegerField()
  2068. )
  2069. ).order_by('batch_out_id_for_sort', 'sequence')
  2070. pending_tasks = get_pending_tasks()
  2071. if not pending_tasks.exists():
  2072. logger.info("没有待处理任务")
  2073. return
  2074. # 处理任务列表(最多处理2条,保证WCS有缓冲)
  2075. processed_count = 0
  2076. max_tasks = 2
  2077. skip_count = 0
  2078. max_skip = 5 # 最多跳过5个任务,避免无限循环
  2079. dispatched_ids = set()
  2080. while processed_count < max_tasks and skip_count < max_skip:
  2081. # 重新获取待处理任务(因为可能有任务被跳过)
  2082. pending_tasks = get_pending_tasks().exclude(pk__in=dispatched_ids)
  2083. if not pending_tasks.exists():
  2084. break
  2085. next_task = pending_tasks.first()
  2086. dispatched_ids.add(next_task.pk)
  2087. location = next_task.current_location
  2088. if location == '103' or location == '203':
  2089. logger.info(f"需要跳过该任务: {next_task.taskid}, 位置: {location}")
  2090. next_task.status = 200
  2091. next_task.working = 0
  2092. next_task.save()
  2093. skip_count += 1
  2094. # 跳过这个任务后,继续处理下一个
  2095. continue
  2096. try:
  2097. allocator = LocationAllocation()
  2098. allocation_success = OutboundService.perform_initial_allocation(
  2099. allocator,
  2100. next_task.current_location
  2101. )
  2102. if not allocation_success:
  2103. logger.warning(f"任务分配失败,跳过: {next_task.taskid}")
  2104. skip_count += 1
  2105. continue
  2106. OutboundService.send_task_to_wcs(next_task)
  2107. # 标记任务为已下发,避免重复下发
  2108. next_task.status = 150
  2109. next_task.save(update_fields=['status'])
  2110. processed_count += 1
  2111. logger.info(f"成功下发任务: {next_task.taskid}, 批次: {next_task.batch_out_id if next_task.batch_out else '无批次'}")
  2112. except Exception as e:
  2113. logger.error(f"任务处理失败: {next_task.taskid}, 错误: {str(e)}")
  2114. # 处理失败后,继续尝试下一个任务
  2115. skip_count += 1
  2116. if processed_count > 0:
  2117. logger.info(f"本次共下发 {processed_count} 条任务")
  2118. elif skip_count >= max_skip:
  2119. logger.warning(f"跳过了 {skip_count} 个任务,未找到可处理的任务")
  2120. @staticmethod
  2121. def process_current_task(task_id):
  2122. """发送指定任务"""
  2123. try:
  2124. task = ContainerWCSModel.objects.get(taskid=task_id)
  2125. allocator = LocationAllocation()
  2126. OutboundService.perform_initial_allocation(allocator, task.current_location)
  2127. OutboundService.send_task_to_wcs(task)
  2128. except Exception as e:
  2129. logger.error(f"任务处理失败: {str(e)}")
  2130. def perform_initial_allocation(allocator, location):
  2131. """执行初始库位分配操作"""
  2132. location_row = location.split('-')[1]
  2133. location_col = location.split('-')[2]
  2134. location_layer = location.split('-')[3]
  2135. location_code = LocationModel.objects.filter(row=location_row, col=location_col, layer=location_layer).first().location_code
  2136. if not location_code:
  2137. logger.error(f"未找到库位: {location}")
  2138. operations = [
  2139. (allocator.update_location_status,location_code, 'reserved'),
  2140. (allocator.update_location_group_status,location_code)
  2141. ]
  2142. for func, *args in operations:
  2143. if not func(*args):
  2144. logger.error(f"分配操作失败: {func.__name__}")
  2145. return False
  2146. return True
  2147. # 出库任务下发
  2148. class OutTaskViewSet(ViewSet):
  2149. """
  2150. # fun:get_out_task:下发出库任务
  2151. # fun:get_batch_count_by_boundlist:获取出库申请下的批次数量
  2152. # fun:generate_location_by_demand:根据出库需求生成出库任务
  2153. """
  2154. # authentication_classes = [] # 禁用所有认证类
  2155. # permission_classes = [AllowAny] # 允许任意访问
  2156. def post(self, request):
  2157. try:
  2158. data = self.request.data
  2159. logger.info(f"收到 出库 推送数据: {data}")
  2160. # 从请求中获取 bound_list_id
  2161. bound_list_id = data.get('bound_list_id')
  2162. # 记录操作日志
  2163. try:
  2164. log_operation(
  2165. request=request,
  2166. operation_content=f"接收出库任务请求,出库申请ID: {bound_list_id}",
  2167. operation_level="other",
  2168. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2169. module_name="WCS出库管理"
  2170. )
  2171. except Exception as log_error:
  2172. pass
  2173. current_WCS = ContainerWCSModel.objects.filter(tasktype='outbound',bound_list_id = bound_list_id,is_delete=False).first()
  2174. if current_WCS:
  2175. logger.info(f"当前{bound_list_id}已有出库任务{current_WCS.taskid}")
  2176. if current_WCS.working == 1:
  2177. OutboundService.process_current_task(current_WCS.taskid)
  2178. # 记录成功日志
  2179. try:
  2180. log_success_operation(
  2181. request=request,
  2182. operation_content=f"重新下发出库任务成功,出库申请ID: {bound_list_id},任务ID: {current_WCS.taskid}",
  2183. operation_level="other",
  2184. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2185. module_name="WCS出库管理"
  2186. )
  2187. except Exception as log_error:
  2188. pass
  2189. return Response({"code": 200, "msg": f"下发任务{ current_WCS.taskid }到WCS成功"}, status=200)
  2190. else :
  2191. # 记录任务处理中日志
  2192. try:
  2193. log_operation(
  2194. request=request,
  2195. operation_content=f"出库任务正在处理中,出库申请ID: {bound_list_id},任务ID: {current_WCS.taskid}",
  2196. operation_level="other",
  2197. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2198. module_name="WCS出库管理"
  2199. )
  2200. except Exception as log_error:
  2201. pass
  2202. return Response({"code": 200, "msg": f"当前任务{current_WCS.taskid}正在处理中"}, status=200)
  2203. # 获取关联的出库批次
  2204. out_batches = OutBatchModel.objects.filter(
  2205. bound_list_id=bound_list_id,
  2206. is_delete=False
  2207. ).select_related('batch_number')
  2208. if not out_batches.exists():
  2209. # 记录失败日志
  2210. try:
  2211. log_failure_operation(
  2212. request=request,
  2213. operation_content=f"出库任务创建失败,出库申请ID: {bound_list_id},未找到相关出库批次",
  2214. operation_level="other",
  2215. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2216. module_name="WCS出库管理"
  2217. )
  2218. except Exception as log_error:
  2219. pass
  2220. return Response({"code": 404, "msg": "未找到相关出库批次"}, status=404)
  2221. # 构建批次需求字典
  2222. batch_demand = {}
  2223. for ob in out_batches:
  2224. if ob.batch_number_id not in batch_demand:
  2225. batch_demand[ob.batch_number_id] = {
  2226. 'required': ob.goods_out_qty,
  2227. 'allocated': ob.goods_qty,
  2228. 'remaining': ob.goods_qty - ob.goods_out_qty
  2229. }
  2230. else:
  2231. batch_demand[ob.batch_number_id]['required'] += ob.goods_out_qty
  2232. batch_demand[ob.batch_number_id]['allocated'] += ob.goods_qty
  2233. batch_demand[ob.batch_number_id]['remaining'] += (ob.goods_out_qty - ob.goods_qty)
  2234. # 生成出库任务
  2235. generate_result = self.generate_location_by_demand(
  2236. batch_demand=batch_demand,
  2237. bound_list_id=bound_list_id
  2238. )
  2239. if generate_result['code'] != '200':
  2240. # 记录失败日志
  2241. try:
  2242. log_failure_operation(
  2243. request=request,
  2244. operation_content=f"出库任务生成失败,出库申请ID: {bound_list_id},错误: {generate_result.get('msg', '未知错误')}",
  2245. operation_level="other",
  2246. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2247. module_name="WCS出库管理"
  2248. )
  2249. except Exception as log_error:
  2250. pass
  2251. return Response(generate_result, status=500)
  2252. # 创建并处理出库任务
  2253. container_list = generate_result['data']
  2254. # 2. 生成初始任务
  2255. OutboundService.create_initial_tasks(container_list,bound_list_id)
  2256. # 3. 立即发送第一个任务
  2257. OutboundService.process_next_task()
  2258. # 记录成功日志
  2259. try:
  2260. container_count = len(container_list) if container_list else 0
  2261. log_success_operation(
  2262. request=request,
  2263. operation_content=f"出库任务创建成功,出库申请ID: {bound_list_id},托盘数量: {container_count}",
  2264. operation_level="other",
  2265. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2266. module_name="WCS出库管理"
  2267. )
  2268. except Exception as log_error:
  2269. pass
  2270. return Response({"code": 200, "msg": "下发任务成功"}, status=200)
  2271. except Exception as e:
  2272. logger.error(f"任务生成失败: {str(e)}")
  2273. # 记录异常日志
  2274. try:
  2275. log_failure_operation(
  2276. request=request,
  2277. operation_content=f"出库任务生成异常,出库申请ID: {bound_list_id if 'bound_list_id' in locals() else '未知'},错误: {str(e)}",
  2278. operation_level="other",
  2279. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2280. module_name="WCS出库管理"
  2281. )
  2282. except Exception as log_error:
  2283. pass
  2284. return Response({"code": 200, "msg": str(e)}, status=200)
  2285. def post_check(self, request):
  2286. try:
  2287. data = self.request.data
  2288. logger.info(f"收到 出库抽检 推送数据: {data}")
  2289. # 从请求中获取 batch_id
  2290. batch_id = data.get('batch_id')
  2291. container_demand = int(data.get('container_demand'))
  2292. # 记录操作日志
  2293. try:
  2294. log_operation(
  2295. request=request,
  2296. operation_content=f"接收出库抽检任务请求,批次ID: {batch_id},抽检托盘数量: {container_demand}",
  2297. operation_level="other",
  2298. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2299. module_name="WCS出库抽检管理"
  2300. )
  2301. except Exception as log_error:
  2302. pass
  2303. if not batch_id or not container_demand:
  2304. # 记录失败日志
  2305. try:
  2306. log_failure_operation(
  2307. request=request,
  2308. operation_content=f"出库抽检任务创建失败,缺少抽检数目或批次号",
  2309. operation_level="other",
  2310. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2311. module_name="WCS出库抽检管理"
  2312. )
  2313. except Exception as log_error:
  2314. pass
  2315. return Response({"code": "400", "msg": "缺少抽检数目或批次号"}, status=200)
  2316. current_WCS = ContainerWCSModel.objects.filter(batch=batch_id,tasktype='check',is_delete=False,working=1).first()
  2317. if current_WCS:
  2318. logger.info(f"当前{batch_id}已有出库抽检任务{current_WCS.taskid}")
  2319. if current_WCS.working == 1:
  2320. OutboundService.process_current_task(current_WCS.taskid)
  2321. # 记录成功日志
  2322. try:
  2323. log_success_operation(
  2324. request=request,
  2325. operation_content=f"重新下发出库抽检任务成功,批次ID: {batch_id},任务ID: {current_WCS.taskid}",
  2326. operation_level="other",
  2327. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2328. module_name="WCS出库抽检管理"
  2329. )
  2330. except Exception as log_error:
  2331. pass
  2332. return Response({"code": 200, "msg": f"下发任务{ current_WCS.taskid }到WCS成功"}, status=200)
  2333. else :
  2334. # 记录任务处理中日志
  2335. try:
  2336. log_operation(
  2337. request=request,
  2338. operation_content=f"出库抽检任务正在处理中,批次ID: {batch_id},任务ID: {current_WCS.taskid}",
  2339. operation_level="other",
  2340. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2341. module_name="WCS出库抽检管理"
  2342. )
  2343. except Exception as log_error:
  2344. pass
  2345. return Response({"code": 200, "msg": f"当前任务{current_WCS.taskid}正在处理中"}, status=200)
  2346. # 获取批次号
  2347. generate_result = self.generate_location_by_check(batch_id,container_demand)
  2348. if generate_result['code'] != '200':
  2349. # 记录失败日志
  2350. try:
  2351. log_failure_operation(
  2352. request=request,
  2353. operation_content=f"出库抽检任务生成失败,批次ID: {batch_id},错误: {generate_result.get('msg', '未知错误')}",
  2354. operation_level="other",
  2355. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2356. module_name="WCS出库抽检管理"
  2357. )
  2358. except Exception as log_error:
  2359. pass
  2360. return Response(generate_result, status=200)
  2361. # 创建并处理出库任务
  2362. container_list = generate_result['data']
  2363. # 3. 立即发送第一个任务
  2364. OutboundService.create_initial_check_tasks(container_list,batch_id)
  2365. OutboundService.process_next_task()
  2366. # 记录成功日志
  2367. try:
  2368. container_count = len(container_list) if container_list else 0
  2369. log_success_operation(
  2370. request=request,
  2371. operation_content=f"出库抽检任务创建成功,批次ID: {batch_id},托盘数量: {container_count}",
  2372. operation_level="other",
  2373. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2374. module_name="WCS出库抽检管理"
  2375. )
  2376. except Exception as log_error:
  2377. pass
  2378. return Response({"code": 200, "msg": "下发任务成功"}, status=200)
  2379. except Exception as e:
  2380. logger.error(f"任务生成失败: {str(e)}")
  2381. # 记录异常日志
  2382. try:
  2383. log_failure_operation(
  2384. request=request,
  2385. operation_content=f"出库抽检任务生成异常,批次ID: {batch_id if 'batch_id' in locals() else '未知'},错误: {str(e)}",
  2386. operation_level="other",
  2387. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "WCS系统",
  2388. module_name="WCS出库抽检管理"
  2389. )
  2390. except Exception as log_error:
  2391. pass
  2392. return Response({"code": 200, "msg": str(e)}, status=200)
  2393. def get_batch_count_by_boundlist(self,bound_list_id):
  2394. try:
  2395. bound_list_obj_all = OutBoundDetailModel.objects.filter(bound_list=bound_list_id).all()
  2396. if bound_list_obj_all:
  2397. batch_count_dict = {}
  2398. # 统计批次数量(创建哈希表,去重)
  2399. for batch in bound_list_obj_all:
  2400. if batch.bound_batch_number_id not in batch_count_dict:
  2401. batch_count_dict[batch.bound_batch_number_id] = batch.bound_batch.goods_out_qty
  2402. else:
  2403. batch_count_dict[batch.bound_batch_number_id] += batch.bound_batch.goods_out_qty
  2404. return batch_count_dict
  2405. else:
  2406. logger.error(f"查询批次数量失败: {bound_list_id} 不存在")
  2407. return {}
  2408. except Exception as e:
  2409. logger.error(f"查询批次数量失败: {str(e)}")
  2410. return {}
  2411. def get_location_by_status_and_batch(self,status,bound_id):
  2412. try:
  2413. container_obj = ContainerDetailModel.objects.filter(batch=bound_id,status=status,is_delete=False).all()
  2414. if container_obj:
  2415. container_dict = {}
  2416. # 统计托盘数量(创建哈希表,去重)
  2417. for obj in container_obj:
  2418. if obj.container_id not in container_dict:
  2419. container_dict[obj.container_id] = obj.goods_qty
  2420. else:
  2421. container_dict[obj.container_id] += obj.goods_qty
  2422. return container_dict
  2423. else:
  2424. logger.error(f"查询{status}状态的批次数量失败: {bound_id} 不存在")
  2425. return {}
  2426. except Exception as e:
  2427. logger.error(f"查询{status}状态的批次数量失败: {str(e)}")
  2428. return {}
  2429. def get_order_by_batch(self,container_list,bound_id):
  2430. try:
  2431. container_dict = {}
  2432. for container in container_list:
  2433. location_container = LocationContainerLink.objects.filter(container_id=container,is_active=True).first()
  2434. if location_container:
  2435. location_c_number = location_container.location.c_number
  2436. if container not in container_dict:
  2437. container_dict[container] = {
  2438. "container_number":container,
  2439. "location_c_number":location_c_number,
  2440. "location_id ":location_container.location.id,
  2441. "location_type":location_container.location.location_type,
  2442. "batch_id":bound_id,
  2443. }
  2444. if len(container_dict.keys()) == len(container_list):
  2445. return container_dict
  2446. else:
  2447. logger.error(f"查询批次数量失败: {container_list} 不存在")
  2448. return {}
  2449. except Exception as e:
  2450. logger.error(f"查询批次数量失败: {str(e)}")
  2451. return {}
  2452. except Exception as e:
  2453. logger.error(f"查询{status}状态的批次数量失败: {str(e)}")
  2454. return {}
  2455. def get_container_allocation(self, batch_id):
  2456. """兼容所有数据库的去重方案"""
  2457. # 获取唯一托盘ID列表
  2458. container_ids = (
  2459. ContainerDetailModel.objects
  2460. .filter(batch_id=batch_id, status=2,is_delete=False)
  2461. .values_list('container_id', flat=True)
  2462. .distinct()
  2463. )
  2464. # 获取每个托盘的最新明细(按id倒序)
  2465. return (
  2466. ContainerDetailModel.objects
  2467. .filter(container_id__in=container_ids,batch_id=batch_id, status=2,is_delete=False)
  2468. .select_related('container')
  2469. .prefetch_related(
  2470. Prefetch('container__location_links',
  2471. queryset=LocationContainerLink.objects.select_related('location'),
  2472. to_attr='active_location')
  2473. )
  2474. .order_by('container_id', '-id')
  2475. )
  2476. def generate_location_by_check(self,batch_id,container_demand):
  2477. '''
  2478. 根据抽检托盘数目,把相应的库位给到出库任务
  2479. '''
  2480. try:
  2481. return_data = []
  2482. # 获取已去重的托盘列表
  2483. container_qs = self.get_container_allocation(batch_id)
  2484. # 构建托盘信息字典(自动去重)
  2485. container_map = {}
  2486. for cd in container_qs:
  2487. if cd.container_id in container_map:
  2488. continue
  2489. # 获取有效库位信息
  2490. active_location = next(
  2491. (link.location for link in cd.container.active_location
  2492. if link.is_active),
  2493. None
  2494. )
  2495. container_map[cd.container_id] = {
  2496. 'detail': cd,
  2497. 'container': cd.container,
  2498. 'location': active_location
  2499. }
  2500. # 转换为排序列表
  2501. container_list = list(container_map.values())
  2502. sorted_containers = sorted(
  2503. container_list,
  2504. key=lambda x: (
  2505. self._get_goods_class_priority(x['detail'].goods_class),
  2506. -(x['location'].c_number if x['location'] else 0),
  2507. # -(x['location'].layer if x['location'] else 0),
  2508. # x['location'].row if x['location'] else 0,
  2509. # x['location'].col if x['location'] else 0
  2510. )
  2511. )
  2512. for item in sorted_containers:
  2513. if container_demand <= 0:
  2514. break
  2515. # 获取可分配数量
  2516. # 记录分配信息
  2517. allocate_container = {
  2518. "container_number": item['container'].id,
  2519. "batch_id": batch_id,
  2520. "location_code": item['location'].location_code if item['location'] else 'N/A',
  2521. "allocate_qty": 0,
  2522. "c_number": item['location'].c_number if item['location'] else 0
  2523. }
  2524. return_data.append(allocate_container)
  2525. container_demand -= 1
  2526. # 降重 return_data,以container_number为key
  2527. return_data = list({v['container_number']: v for v in return_data}.values())
  2528. # 排序
  2529. return_data = sorted(return_data, key=lambda x: -x['c_number'])
  2530. return {"code": "200", "msg": "Success", "data": return_data}
  2531. except Exception as e:
  2532. logger.error(f"出库任务生成失败: {str(e)}", exc_info=True)
  2533. return {"code": "500", "msg": str(e)}
  2534. def generate_location_by_demand(self, batch_demand, bound_list_id):
  2535. try:
  2536. return_data = []
  2537. for batch_id, demand in batch_demand.items():
  2538. # 获取已去重的托盘列表
  2539. container_qs = self.get_container_allocation(batch_id)
  2540. # 构建托盘信息字典(自动去重)
  2541. container_map = {}
  2542. for cd in container_qs:
  2543. if cd.container_id in container_map:
  2544. container_map[cd.container_id]['goods_qty'] += cd.goods_qty - cd.goods_out_qty
  2545. continue
  2546. # 获取有效库位信息
  2547. active_location = next(
  2548. (link.location for link in cd.container.active_location
  2549. if link.is_active),
  2550. None
  2551. )
  2552. container_map[cd.container_id] = {
  2553. 'detail': cd,
  2554. 'goods_qty': cd.goods_qty - cd.goods_out_qty,
  2555. 'container': cd.container,
  2556. 'location': active_location
  2557. }
  2558. # 转换为排序列表
  2559. container_list = list(container_map.values())
  2560. # 多维度排序(优化性能版)
  2561. sorted_containers = sorted(
  2562. container_list,
  2563. key=lambda x: (
  2564. self._get_goods_class_priority(x['detail'].goods_class),
  2565. -(x['location'].c_number if x['location'] else 0),
  2566. # -(x['location'].layer if x['location'] else 0),
  2567. # x['location'].row if x['location'] else 0,
  2568. # x['location'].col if x['location'] else 0
  2569. )
  2570. )
  2571. # 分配逻辑
  2572. required = demand['required']
  2573. for item in sorted_containers:
  2574. if required <= 0:
  2575. break
  2576. # 获取可分配数量
  2577. allocatable = item['goods_qty']
  2578. allocate_qty = min(required, allocatable)
  2579. # 记录分配信息
  2580. allocate_container = {
  2581. "container_number": item['container'].id,
  2582. "batch_id": batch_id,
  2583. "location_code": item['location'].location_code if item['location'] else 'N/A',
  2584. "allocate_qty": allocate_qty,
  2585. "c_number": item['location'].c_number if item['location'] else 0
  2586. }
  2587. return_data.append(allocate_container)
  2588. required -= allocate_qty
  2589. # 更新数据库状态(需要事务处理)
  2590. self._update_allocation_status(allocate_container, allocate_qty,bound_list_id)
  2591. # 降重 return_data,以container_number为key
  2592. return_data = list({v['container_number']: v for v in return_data}.values())
  2593. # 排序
  2594. return_data = sorted(return_data, key=lambda x: -x['c_number'])
  2595. return {"code": "200", "msg": "Success", "data": return_data}
  2596. except Exception as e:
  2597. logger.error(f"出库任务生成失败: {str(e)}", exc_info=True)
  2598. return {"code": "500", "msg": str(e)}
  2599. def _get_goods_class_priority(self, goods_class):
  2600. """货物类型优先级权重"""
  2601. return {
  2602. 3: 0, # 散盘最高
  2603. 1: 1, # 成品次之
  2604. 2: 2 # 空盘最低
  2605. }.get(goods_class, 99)
  2606. def _update_allocation_status(self, allocate_container, allocate_qty,bound_list_id):
  2607. """事务化更新分配状态"""
  2608. try:
  2609. # 更新托盘明细
  2610. container_detail_all = ContainerDetailModel.objects.filter(
  2611. container_id=allocate_container['container_number'],
  2612. batch_id=allocate_container['batch_id'],
  2613. is_delete=False
  2614. ).all()
  2615. left_qty = 0
  2616. for cd in container_detail_all:
  2617. if left_qty - allocate_qty >= 0:
  2618. break
  2619. add_qty = min(allocate_qty-left_qty, cd.goods_qty - cd.goods_out_qty)
  2620. if add_qty == 0:
  2621. continue
  2622. left_qty += add_qty
  2623. last_out_qty = cd.goods_out_qty
  2624. cd.goods_out_qty += add_qty
  2625. # print(f"{left_qty/25} 更新托盘 {cd.container.container_code} 批次 {cd.batch_id} 出库数量: {cd.goods_out_qty}")
  2626. cd.save()
  2627. out_batch_detail.objects.create(
  2628. out_bound_id=bound_list_id,
  2629. container_id=cd.container_id,
  2630. container_detail_id=cd.id,
  2631. out_goods_qty=add_qty,
  2632. last_out_goods_qty = last_out_qty,
  2633. working = 1,
  2634. is_delete = False
  2635. )
  2636. return True
  2637. except Exception as e:
  2638. logger.error(f"状态更新失败: {str(e)}")
  2639. return False
  2640. def create_or_update_container_operation(self,container_obj,batch_id,bound_id,to_location,goods_qty,goods_weight):
  2641. try:
  2642. container_operation_obj = ContainerOperationModel.objects.filter(container=container_obj,batch_id=batch_id,bound_id=bound_id,operation_type="outbound").first()
  2643. if container_operation_obj:
  2644. logger.info(f"[0]查询出库任务: {container_operation_obj.operation_type} ")
  2645. logger.info(f"更新出库任务: {container_obj.container_code} 批次 {batch_id} 出库需求: {bound_id} 数量: {goods_qty} 重量: {goods_weight}")
  2646. container_operation_obj.to_location = to_location
  2647. container_operation_obj.goods_qty = goods_qty
  2648. container_operation_obj.goods_weight = goods_weight
  2649. container_operation_obj.save()
  2650. # 记录更新日志(内部方法,不记录详细日志,避免过多记录)
  2651. else:
  2652. logger.info(f"创建出库任务: {container_obj.container_code} 批次 {batch_id} 出库需求: {bound_id} 数量: {goods_qty} 重量: {goods_weight}")
  2653. batch = BoundBatchModel.objects.filter(id=batch_id).first()
  2654. if not batch:
  2655. return {"code": "500", "msg": f"批次 {batch_id} 不存在"}
  2656. ContainerOperationModel.objects.create(
  2657. month = int(timezone.now().strftime("%Y%m")),
  2658. container = container_obj,
  2659. goods_code = batch.goods_code,
  2660. goods_desc = batch.goods_desc,
  2661. operation_type ="outbound",
  2662. batch_id = batch_id,
  2663. bound_id = bound_id,
  2664. goods_qty = goods_qty,
  2665. goods_weight = goods_weight,
  2666. from_location = container_obj.current_location,
  2667. to_location= to_location,
  2668. timestamp=timezone.now(),
  2669. operator="WMS",
  2670. memo=f"出库需求: {bound_id}, 批次: {batch_id}, 数量: {goods_qty}"
  2671. )
  2672. # 记录创建日志(内部方法,不记录详细日志,避免过多记录)
  2673. return {"code": "200", "msg": "Success"}
  2674. except Exception as e:
  2675. return {"code": "500", "msg": str(e)}
  2676. def update_container_detail_out_qty(self,container_obj,batch_id):
  2677. try:
  2678. logger.info(f"[1]更新托盘出库数量: {container_obj.container_code} 批次 {batch_id} ")
  2679. container_operation_obj = ContainerOperationModel.objects.filter(container=container_obj,batch_id=batch_id,operation_type="outbound").all()
  2680. if not container_operation_obj:
  2681. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无出库任务")
  2682. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无出库任务"}
  2683. container_detail_obj = ContainerDetailModel.objects.filter(container=container_obj,batch_id=batch_id,status=2,is_delete=False).first()
  2684. if not container_detail_obj:
  2685. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无批次信息")
  2686. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无批次信息"}
  2687. out_qty = 0
  2688. for obj in container_operation_obj:
  2689. out_qty += obj.goods_qty
  2690. if out_qty >= container_detail_obj.goods_qty:
  2691. out_qty = container_detail_obj.goods_qty
  2692. container_detail_obj.status = 3
  2693. break
  2694. if out_qty == 0:
  2695. logger.error(f"[1]批次 {batch_id} 托盘 {container_obj.container_code} 无出库数量")
  2696. return {"code": "500", "msg": f"批次 {batch_id} 托盘 {container_obj.container_code} 无出库数量"}
  2697. container_detail_obj.goods_out_qty = out_qty
  2698. container_detail_obj.save()
  2699. return {"code": "200", "msg": "Success"}
  2700. except Exception as e:
  2701. return {"code": "500", "msg": str(e)}
  2702. # 出库任务监测
  2703. class BatchViewSet(viewsets.ModelViewSet):
  2704. authentication_classes = [] # 禁用所有认证类
  2705. permission_classes = [AllowAny] # 允许任意访问
  2706. def wcs_post(self, request, *args, **kwargs):
  2707. data = self.request.data
  2708. logger.info(f"收到 WMS 推送数据: {data}")
  2709. return Response({"code": "200", "msg": "Success"}, status=200)
  2710. # views.py
  2711. class OutDetailViewSet(viewsets.ModelViewSet):
  2712. pagination_class = MyPageNumberPagination
  2713. serializer_class = OutBoundDetailSerializer
  2714. def get_project(self):
  2715. try:
  2716. id = self.kwargs.get('pk')
  2717. return id
  2718. except:
  2719. return None
  2720. def get_queryset(self):
  2721. """根据不同的action调整查询集"""
  2722. if self.action == 'list':
  2723. # 获取每个out_bound的最新一条记录
  2724. # 子查询,用于获取每个out_bound对应的最新out_batch_detail记录
  2725. subquery = out_batch_detail.objects.filter(
  2726. out_bound=OuterRef('out_bound')
  2727. ).order_by('-id')
  2728. # 返回最新的out_batch_detail记录,通过子查询的结果进行过滤
  2729. return out_batch_detail.objects.filter(
  2730. id=Subquery(subquery.values('id')[:1])
  2731. )
  2732. return out_batch_detail.objects.all()
  2733. def retrieve(self, request, *args, **kwargs):
  2734. """重写retrieve方法返回关联集合"""
  2735. qs = self.get_project()
  2736. queryset = self.filter_queryset(
  2737. out_batch_detail.objects.filter(out_bound = qs)
  2738. )
  2739. # 分页处理
  2740. # page = self.paginate_queryset(queryset)
  2741. # if queryset is not None:
  2742. # serializer = self.get_serializer(queryset, many=True)
  2743. # return self.get_paginated_response(serializer.data)
  2744. serializer = self.get_serializer(queryset, many=True)
  2745. return Response(serializer.data)
  2746. def get_serializer_class(self):
  2747. """根据action切换序列化器"""
  2748. if self.action == 'retrieve':
  2749. return OutBoundFullDetailSerializer
  2750. return super().get_serializer_class()
  2751. def get_out_batch_detail(self, request):
  2752. """获取某个托盘的出库明细"""
  2753. try:
  2754. container_code = request.query_params.get('container_code')
  2755. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  2756. if not container_obj:
  2757. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  2758. out_batch_detail_all = out_batch_detail.objects.filter(container=container_obj,working=1,is_delete=False).all()
  2759. if not out_batch_detail_all:
  2760. return Response({"code": "500", "message": f"托盘 {container_code} 无出库明细"}, status=status.HTTP_200_OK)
  2761. serializer = OutBoundFullDetailSerializer(out_batch_detail_all, many=True)
  2762. return Response({"code": "200", "message": "Success", "data": serializer.data}, status=status.HTTP_200_OK)
  2763. except Exception as e:
  2764. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  2765. def confirm_out_batch_detail(self, request):
  2766. """确认出库 - 支持按批次和数量部分确认"""
  2767. try:
  2768. container_code = request.data.get('container_code')
  2769. confirm_items = request.data.get('confirm_items', []) # 格式: [{"detail_id": 1, "confirm_qty": 10}, ...]
  2770. # 记录操作日志
  2771. try:
  2772. log_operation(
  2773. request=request,
  2774. operation_content=f"接收确认出库请求,托盘编码: {container_code},确认项数量: {len(confirm_items) if confirm_items else '全部'}",
  2775. operation_level="other",
  2776. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2777. module_name="出库确认管理"
  2778. )
  2779. except Exception as log_error:
  2780. pass
  2781. if not container_code:
  2782. # 记录失败日志
  2783. try:
  2784. log_failure_operation(
  2785. request=request,
  2786. operation_content=f"确认出库失败,缺少托盘编码参数",
  2787. operation_level="other",
  2788. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2789. module_name="出库确认管理"
  2790. )
  2791. except Exception as log_error:
  2792. pass
  2793. return Response({"code": "500", "message": "缺少托盘编码参数"}, status=status.HTTP_200_OK)
  2794. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  2795. if not container_obj:
  2796. # 记录失败日志
  2797. try:
  2798. log_failure_operation(
  2799. request=request,
  2800. operation_content=f"确认出库失败,托盘 {container_code} 不存在",
  2801. operation_level="other",
  2802. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2803. module_name="出库确认管理"
  2804. )
  2805. except Exception as log_error:
  2806. pass
  2807. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  2808. # 如果没有指定确认项,则确认所有出库明细(保持向后兼容)
  2809. if not confirm_items:
  2810. out_batch_detail_all = out_batch_detail.objects.filter(container=container_obj,working=1,is_delete=False).order_by('-id').all()
  2811. if not out_batch_detail_all:
  2812. # 记录失败日志
  2813. try:
  2814. log_failure_operation(
  2815. request=request,
  2816. operation_content=f"确认出库失败,托盘 {container_code} 无出库明细",
  2817. operation_level="other",
  2818. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2819. module_name="出库确认管理"
  2820. )
  2821. except Exception as log_error:
  2822. pass
  2823. return Response({"code": "500", "message": f"托盘 {container_code} 无出库明细"}, status=status.HTTP_200_OK)
  2824. total_qty = 0
  2825. batch_list = []
  2826. for obj in out_batch_detail_all:
  2827. obj.working = 0
  2828. obj.save()
  2829. total_qty += obj.out_goods_qty
  2830. batch_list.append(f"批次{obj.container_detail.batch.id}(数量:{obj.out_goods_qty})")
  2831. BatchOperateLogModel.objects.create(
  2832. batch_id = obj.container_detail.batch,
  2833. log_type = 1,
  2834. log_date = timezone.now(),
  2835. goods_code = obj.container_detail.batch.goods_code,
  2836. goods_desc = obj.container_detail.batch.goods_desc,
  2837. goods_qty = obj.out_goods_qty,
  2838. log_content = f"出库托盘 {container_code} 批次 {obj.container_detail.batch.id} 数量 {obj.out_goods_qty}",
  2839. creater = "WMS",
  2840. openid = "WMS"
  2841. )
  2842. # 记录成功日志
  2843. try:
  2844. log_success_operation(
  2845. request=request,
  2846. operation_content=f"确认出库成功,托盘编码: {container_code},确认明细数: {len(out_batch_detail_all)},总数量: {total_qty},批次: {', '.join(batch_list)}",
  2847. operation_level="other",
  2848. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2849. module_name="出库确认管理"
  2850. )
  2851. except Exception as log_error:
  2852. pass
  2853. return Response({"code": "200", "message": "出库成功"}, status=status.HTTP_200_OK)
  2854. # 按批次和数量部分确认
  2855. from decimal import Decimal
  2856. for item in confirm_items:
  2857. out_detail_id = item.get('detail_id') # 这是 out_batch_detail 的 ID
  2858. confirm_qty = Decimal(str(item.get('confirm_qty', 0)))
  2859. if not out_detail_id or confirm_qty <= 0:
  2860. continue
  2861. # 确保 out_detail_id 是整数类型
  2862. try:
  2863. out_detail_id = int(out_detail_id)
  2864. except (ValueError, TypeError):
  2865. logger.error(f"无效的 out_detail_id: {out_detail_id}")
  2866. continue
  2867. # 添加调试日志
  2868. logger.info(f"查询出库明细: container={container_obj.container_code}, out_batch_detail_id={out_detail_id}")
  2869. # 直接通过 out_batch_detail 的 ID 查找记录
  2870. out_detail = out_batch_detail.objects.filter(
  2871. id=out_detail_id,
  2872. container_id=container_obj.id,
  2873. working=1,
  2874. is_delete=False
  2875. ).first()
  2876. if not out_detail:
  2877. # 尝试不限制 working 状态查找
  2878. out_detail_any = out_batch_detail.objects.filter(
  2879. id=out_detail_id,
  2880. container_id=container_obj.id,
  2881. is_delete=False
  2882. ).first()
  2883. if out_detail_any:
  2884. if out_detail_any.working == 0:
  2885. logger.warning(f"出库明细 {out_detail_id} 的 working 状态为 0,可能已经被处理过了")
  2886. else:
  2887. logger.warning(f"出库明细 {out_detail_id} 的 working 状态为 {out_detail_any.working},不是 1")
  2888. else:
  2889. logger.error(f"未找到出库明细: out_batch_detail_id={out_detail_id}, container={container_obj.container_code}")
  2890. continue
  2891. # 计算本次要确认的数量(不能超过该出库明细的数量)
  2892. out_qty_to_confirm = min(confirm_qty, out_detail.out_goods_qty)
  2893. # 如果确认数量等于或大于出库数量,则标记为已完成
  2894. if out_qty_to_confirm >= out_detail.out_goods_qty:
  2895. out_detail.working = 0
  2896. out_detail.save()
  2897. else:
  2898. # 部分确认,创建新的确认记录并减少剩余数量
  2899. # 创建一个新的 out_batch_detail 记录用于剩余数量
  2900. remaining_qty = out_detail.out_goods_qty - out_qty_to_confirm
  2901. out_detail.out_goods_qty = out_qty_to_confirm
  2902. out_detail.working = 0
  2903. out_detail.save()
  2904. # 创建剩余数量的记录(如果需要)
  2905. if remaining_qty > 0:
  2906. out_batch_detail.objects.create(
  2907. out_bound_id=out_detail.out_bound_id,
  2908. container_id=out_detail.container_id,
  2909. container_detail_id=out_detail.container_detail_id,
  2910. out_goods_qty=remaining_qty,
  2911. last_out_goods_qty=out_detail.last_out_goods_qty,
  2912. working=1,
  2913. is_delete=False
  2914. )
  2915. # 创建操作日志
  2916. BatchOperateLogModel.objects.create(
  2917. batch_id = out_detail.container_detail.batch,
  2918. log_type = 1,
  2919. log_date = timezone.now(),
  2920. goods_code = out_detail.container_detail.batch.goods_code,
  2921. goods_desc = out_detail.container_detail.batch.goods_desc,
  2922. goods_qty = out_qty_to_confirm,
  2923. log_content = f"出库托盘 {container_code} 批次 {out_detail.container_detail.batch.id} 数量 {out_qty_to_confirm}",
  2924. creater = "WMS",
  2925. openid = "WMS"
  2926. )
  2927. logger.info(f"确认出库明细 {out_detail_id}: 确认数量={out_qty_to_confirm}, 剩余数量={out_detail.out_goods_qty}")
  2928. # 记录成功日志
  2929. try:
  2930. confirmed_count = len(confirm_items)
  2931. total_confirmed_qty = sum(Decimal(str(item.get('confirm_qty', 0))) for item in confirm_items)
  2932. log_success_operation(
  2933. request=request,
  2934. operation_content=f"确认出库成功,托盘编码: {container_code},确认明细数: {confirmed_count},总确认数量: {total_confirmed_qty}",
  2935. operation_level="other",
  2936. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2937. module_name="出库确认管理"
  2938. )
  2939. except Exception as log_error:
  2940. pass
  2941. return Response({"code": "200", "message": "出库成功"}, status=status.HTTP_200_OK)
  2942. except Exception as e:
  2943. logger.error(f"确认出库失败: {str(e)}", exc_info=True)
  2944. # 记录异常日志
  2945. try:
  2946. log_failure_operation(
  2947. request=request,
  2948. operation_content=f"确认出库异常,托盘编码: {container_code if 'container_code' in locals() else '未知'},错误: {str(e)}",
  2949. operation_level="other",
  2950. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2951. module_name="出库确认管理"
  2952. )
  2953. except Exception as log_error:
  2954. pass
  2955. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  2956. def cancel_out_batch_detail(self, request):
  2957. """取消出库 - 支持按批次和数量部分取消"""
  2958. try:
  2959. container_code = request.data.get('container_code')
  2960. cancel_items = request.data.get('cancel_items', []) # 格式: [{"detail_id": 1, "cancel_qty": 10}, ...]
  2961. # 记录操作日志
  2962. try:
  2963. log_operation(
  2964. request=request,
  2965. operation_content=f"接收取消出库请求,托盘编码: {container_code},取消项数量: {len(cancel_items) if cancel_items else '全部'}",
  2966. operation_level="other",
  2967. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2968. module_name="出库取消管理"
  2969. )
  2970. except Exception as log_error:
  2971. pass
  2972. if not container_code:
  2973. # 记录失败日志
  2974. try:
  2975. log_failure_operation(
  2976. request=request,
  2977. operation_content=f"取消出库失败,缺少托盘编码参数",
  2978. operation_level="other",
  2979. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2980. module_name="出库取消管理"
  2981. )
  2982. except Exception as log_error:
  2983. pass
  2984. return Response({"code": "500", "message": "缺少托盘编码参数"}, status=status.HTTP_200_OK)
  2985. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  2986. if not container_obj:
  2987. # 记录失败日志
  2988. try:
  2989. log_failure_operation(
  2990. request=request,
  2991. operation_content=f"取消出库失败,托盘 {container_code} 不存在",
  2992. operation_level="other",
  2993. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  2994. module_name="出库取消管理"
  2995. )
  2996. except Exception as log_error:
  2997. pass
  2998. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  2999. # 如果没有指定取消项,则取消所有出库明细(保持向后兼容)
  3000. if not cancel_items:
  3001. out_batch_detail_all = out_batch_detail.objects.filter(container=container_obj,working=1,is_delete=False).order_by('-id').all()
  3002. if not out_batch_detail_all:
  3003. # 记录失败日志
  3004. try:
  3005. log_failure_operation(
  3006. request=request,
  3007. operation_content=f"取消出库失败,托盘 {container_code} 无出库明细",
  3008. operation_level="other",
  3009. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3010. module_name="出库取消管理"
  3011. )
  3012. except Exception as log_error:
  3013. pass
  3014. return Response({"code": "500", "message": f"托盘 {container_code} 无出库明细"}, status=status.HTTP_200_OK)
  3015. total_cancel_qty = 0
  3016. batch_list = []
  3017. for obj in out_batch_detail_all:
  3018. total_cancel_qty += obj.out_goods_qty
  3019. batch_list.append(f"批次{obj.container_detail.batch.id}(数量:{obj.out_goods_qty})")
  3020. obj.container_detail.goods_out_qty = obj.last_out_goods_qty
  3021. obj.container_detail.save()
  3022. obj.is_delete = True
  3023. obj.working = 0
  3024. obj.save()
  3025. # 记录成功日志
  3026. try:
  3027. log_success_operation(
  3028. request=request,
  3029. operation_content=f"取消出库成功,托盘编码: {container_code},取消明细数: {len(out_batch_detail_all)},总取消数量: {total_cancel_qty},批次: {', '.join(batch_list)}",
  3030. operation_level="other",
  3031. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3032. module_name="出库取消管理"
  3033. )
  3034. except Exception as log_error:
  3035. pass
  3036. return Response({"code": "200", "message": "出库取消成功"}, status=status.HTTP_200_OK)
  3037. # 按批次和数量部分取消
  3038. from decimal import Decimal
  3039. for item in cancel_items:
  3040. out_detail_id = item.get('detail_id') # 这是 out_batch_detail 的 ID
  3041. cancel_qty = Decimal(str(item.get('cancel_qty', 0)))
  3042. if not out_detail_id or cancel_qty <= 0:
  3043. continue
  3044. # 确保 out_detail_id 是整数类型
  3045. try:
  3046. out_detail_id = int(out_detail_id)
  3047. except (ValueError, TypeError):
  3048. logger.error(f"无效的 out_detail_id: {out_detail_id}")
  3049. continue
  3050. # 添加调试日志
  3051. logger.info(f"查询出库明细: container={container_obj.container_code}, out_batch_detail_id={out_detail_id}")
  3052. # 直接通过 out_batch_detail 的 ID 查找记录
  3053. out_detail = out_batch_detail.objects.filter(
  3054. id=out_detail_id,
  3055. container_id=container_obj.id,
  3056. working=1,
  3057. is_delete=False
  3058. ).first()
  3059. if not out_detail:
  3060. # 尝试不限制 working 状态查找
  3061. out_detail_any = out_batch_detail.objects.filter(
  3062. id=out_detail_id,
  3063. container_id=container_obj.id,
  3064. is_delete=False
  3065. ).first()
  3066. if out_detail_any:
  3067. if out_detail_any.working == 0:
  3068. logger.warning(f"出库明细 {out_detail_id} 的 working 状态为 0,可能已经被处理过了")
  3069. else:
  3070. logger.warning(f"出库明细 {out_detail_id} 的 working 状态为 {out_detail_any.working},不是 1")
  3071. else:
  3072. logger.error(f"未找到出库明细: out_batch_detail_id={out_detail_id}, container={container_obj.container_code}")
  3073. continue
  3074. # 计算本次要取消的数量(不能超过该出库明细的数量)
  3075. out_qty_to_cancel = min(cancel_qty, out_detail.out_goods_qty)
  3076. # 更新容器明细的出库数量
  3077. out_detail.container_detail.goods_out_qty -= out_qty_to_cancel
  3078. out_detail.container_detail.goods_out_qty = max(
  3079. out_detail.container_detail.goods_out_qty,
  3080. out_detail.last_out_goods_qty
  3081. )
  3082. out_detail.container_detail.save()
  3083. # 如果全部取消,则删除或标记该出库明细
  3084. if out_detail.out_goods_qty <= out_qty_to_cancel:
  3085. out_detail.is_delete = True
  3086. out_detail.working = 0
  3087. out_detail.out_goods_qty = Decimal('0') # 清零
  3088. else:
  3089. # 部分取消,减少出库数量
  3090. out_detail.out_goods_qty -= out_qty_to_cancel
  3091. out_detail.save()
  3092. logger.info(f"取消出库明细 {out_detail_id}: 取消数量={out_qty_to_cancel}, 剩余数量={out_detail.out_goods_qty}")
  3093. # 记录成功日志
  3094. try:
  3095. canceled_count = len(cancel_items)
  3096. total_canceled_qty = sum(Decimal(str(item.get('cancel_qty', 0))) for item in cancel_items)
  3097. log_success_operation(
  3098. request=request,
  3099. operation_content=f"取消出库成功,托盘编码: {container_code},取消明细数: {canceled_count},总取消数量: {total_canceled_qty}",
  3100. operation_level="other",
  3101. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3102. module_name="出库取消管理"
  3103. )
  3104. except Exception as log_error:
  3105. pass
  3106. return Response({"code": "200", "message": "出库取消成功"}, status=status.HTTP_200_OK)
  3107. except Exception as e:
  3108. logger.error(f"取消出库失败: {str(e)}", exc_info=True)
  3109. # 记录异常日志
  3110. try:
  3111. log_failure_operation(
  3112. request=request,
  3113. operation_content=f"取消出库异常,托盘编码: {container_code if 'container_code' in locals() else '未知'},错误: {str(e)}",
  3114. operation_level="other",
  3115. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3116. module_name="出库取消管理"
  3117. )
  3118. except Exception as log_error:
  3119. pass
  3120. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  3121. def get_contianer_detail(self, request):
  3122. try:
  3123. container_code = request.query_params.get('container_code')
  3124. # 记录操作日志(查询操作)
  3125. try:
  3126. log_operation(
  3127. request=request,
  3128. operation_content=f"查询托盘明细,托盘编码: {container_code}",
  3129. operation_level="view",
  3130. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3131. module_name="出库明细管理"
  3132. )
  3133. except Exception as log_error:
  3134. pass
  3135. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  3136. if not container_obj:
  3137. # 记录失败日志
  3138. try:
  3139. log_failure_operation(
  3140. request=request,
  3141. operation_content=f"查询托盘明细失败,托盘 {container_code} 不存在",
  3142. operation_level="view",
  3143. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3144. module_name="出库明细管理"
  3145. )
  3146. except Exception as log_error:
  3147. pass
  3148. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  3149. container_detail_all = ContainerDetailModel.objects.filter(container=container_obj,is_delete=False).all().exclude(status__in=[3])
  3150. return_data=[]
  3151. for obj in container_detail_all:
  3152. return_data.append({
  3153. "id": obj.id,
  3154. "batch": obj.batch.bound_number,
  3155. "goods_code": obj.goods_code,
  3156. "goods_desc": obj.goods_desc,
  3157. "goods_qty" :obj.goods_qty,
  3158. "out_goods_qty": obj.goods_out_qty
  3159. })
  3160. # 记录成功日志(查询成功)
  3161. try:
  3162. log_success_operation(
  3163. request=request,
  3164. operation_content=f"查询托盘明细成功,托盘编码: {container_code},明细数量: {len(return_data)}",
  3165. operation_level="view",
  3166. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3167. module_name="出库明细管理"
  3168. )
  3169. except Exception as log_error:
  3170. pass
  3171. return Response({"code": "200", "message": "Success", "data": return_data}, status=status.HTTP_200_OK)
  3172. except Exception as e:
  3173. # 记录异常日志
  3174. try:
  3175. log_failure_operation(
  3176. request=request,
  3177. operation_content=f"查询托盘明细异常,托盘编码: {container_code if 'container_code' in locals() else '未知'},错误: {str(e)}",
  3178. operation_level="view",
  3179. operator=request.auth.name if hasattr(request, 'auth') and request.auth else "系统",
  3180. module_name="出库明细管理"
  3181. )
  3182. except Exception as log_error:
  3183. pass
  3184. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)
  3185. def change_container_out_qty(self, request):
  3186. try:
  3187. container_code = request.data.get('container_code')
  3188. container_obj = ContainerListModel.objects.filter(container_code=container_code).first()
  3189. if not container_obj:
  3190. return Response({"code": "500", "message": f"托盘 {container_code} 不存在"}, status=status.HTTP_200_OK)
  3191. logger.info(f"change_container_out_qty: {request.data}")
  3192. for container_detail_id, out_qty in request.data.get('detail_list').items():
  3193. container_detail_obj = ContainerDetailModel.objects.filter(id=container_detail_id,is_delete=False).first()
  3194. if not container_detail_obj:
  3195. continue
  3196. from decimal import Decimal
  3197. out_qty = Decimal(out_qty)
  3198. container_detail_obj.goods_out_qty += out_qty
  3199. container_detail_obj.save()
  3200. return Response({"code": "200", "message": "Success"}, status=status.HTTP_200_OK)
  3201. except Exception as e:
  3202. return Response({"code": "500", "message": str(e)}, status=status.HTTP_200_OK)