views.py 182 KB

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