WorkOrder.php 223 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  5. use PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf;
  6. use think\Config;
  7. use think\Db;
  8. use think\Exception;
  9. use think\Log;
  10. use think\Request;
  11. use PhpOffice\PhpSpreadsheet\IOFactory;
  12. use function EasyWeChat\Kernel\Support\rsa_public_encrypt;
  13. use function fast\e;
  14. /**
  15. * 工单资料管理
  16. */
  17. class WorkOrder extends Api
  18. {
  19. protected $noNeedLogin = ['*'];
  20. protected $noNeedRight = ['*'];
  21. /**
  22. * 接口访问配置
  23. * 每个模块包含:
  24. * - api_key:API 调用密钥(Token)
  25. * - api_url:对应功能的服务端地址
  26. */
  27. protected $config = [
  28. //文生文-gtp-4
  29. 'txttotxtgtp' => [
  30. 'api_key' => 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss',
  31. 'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
  32. ]
  33. ];
  34. public function _initialize()
  35. {
  36. if (isset($_SERVER['HTTP_ORIGIN'])) {
  37. header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
  38. }
  39. //跨域检测
  40. check_cors_request();
  41. if (!isset($_COOKIE['PHPSESSID'])) {
  42. Config::set('session.id', $this->request->server("HTTP_SID"));
  43. }
  44. parent::_initialize();
  45. }
  46. /**
  47. * 订单资料管理左侧菜单
  48. */
  49. public function DataList()
  50. {
  51. $where['j.Mod_rq'] = null;
  52. $allCustomers = \db('erp_客户供应商')->alias('e')
  53. ->field('e.编号 as 客户编号')
  54. ->select();
  55. $customerData = [];
  56. foreach ($allCustomers as $customer) {
  57. $customerID = $customer['客户编号'];
  58. $customerData[$customerID] = ['计划中' => 0, '生产中' => 0, '已完工' => 0];
  59. }
  60. $data = \db('erp_客户供应商')->alias('e')
  61. ->join('工单_基本资料 j', 'e.编号 = j.客户编号', 'LEFT')
  62. ->field('e.编号 as 客户编号, j.订单编号, j.gd_statu')
  63. ->where($where)
  64. ->select();
  65. foreach ($data as $row) {
  66. $customerID = $row['客户编号'];
  67. $status = $row['gd_statu'];
  68. if ($status == '1-计划中') {
  69. $customerData[$customerID]['计划中']++;
  70. } elseif ($status == '2-生产中') {
  71. $customerData[$customerID]['生产中']++;
  72. } elseif ($status == '已完工') {
  73. $customerData[$customerID]['已完工']++;
  74. }
  75. }
  76. ksort($customerData);
  77. $output = [];
  78. foreach ($customerData as $customerID => $statusCounts) {
  79. $statusString = [];
  80. if ($statusCounts['计划中'] > 0) {
  81. $statusString[] = "计划中:{$statusCounts['计划中']}";
  82. }
  83. if ($statusCounts['生产中'] > 0) {
  84. $statusString[] = "生产中:{$statusCounts['生产中']}";
  85. }
  86. if ($statusCounts['已完工'] > 0) {
  87. $statusString[] = "已完工:{$statusCounts['已完工']}";
  88. }
  89. $output[] = "{$customerID}【" . implode(' ', $statusString) . "】";
  90. }
  91. $this->success('成功', $output);
  92. }
  93. /**
  94. * 订单发货管理左侧菜单
  95. */
  96. public function Send_Out_Goods()
  97. {
  98. $data = \db('工单_发货基本资料')->alias('f')
  99. ->join('工单_基本资料 j', 'f.订单编号 = j.订单编号', 'LEFT')
  100. ->field('DISTINCT j.客户编号')
  101. ->whereNotNull('j.客户编号')
  102. ->select();
  103. $customerCodes = [];
  104. foreach ($data as $row) {
  105. if (!empty($row['客户编号'])) {
  106. $customerCodes[] = $row['客户编号'];
  107. }
  108. }
  109. return json([
  110. 'code' => 0,
  111. 'msg' => '成功',
  112. 'time' => time(),
  113. 'data' => $customerCodes
  114. ]);
  115. }
  116. /**
  117. * 工单基本资料列表
  118. * @ApiMethod (GET)
  119. * @param string $limit 查询长度
  120. * @param string $Gd_khdh 客户代号
  121. * @param string $startTime 接单日期开始时间
  122. * @param string $endTime 接单日期结束时间
  123. * @return \think\response\Json
  124. * @throws \think\exception\DbException
  125. */
  126. public function WorkOrderList()
  127. {
  128. if ($this->request->isGet() === false) {
  129. $this->error('请求错误');
  130. }
  131. $search = input('search');
  132. $page = input('page');
  133. $limit = input('limit');
  134. $param = $this->request->param();
  135. $where = [];
  136. if (!empty($search)) {
  137. $where['订单编号|生产款号|客户编号|款式|审核|Sys_id'] = ['like', '%' . $search . '%'];
  138. }
  139. $where['Mod_rq'] = null;
  140. $list = \db('工单_基本资料')
  141. ->where($where)
  142. ->order('订单编号 desc, Gd_statu desc, Sys_rq desc')
  143. ->limit(($page - 1) * $limit, $limit)
  144. ->select();
  145. $count = \db('工单_基本资料')
  146. ->where($where)
  147. ->order('订单编号 desc, Gd_statu desc, Sys_rq desc')
  148. ->select();
  149. // 提取所有订单编号
  150. $orderIds = array_column($list, '订单编号');
  151. // 查询所有在“工单_相关附件”表中存在的订单编号
  152. $relatedOrders = \db('工单_相关附件')
  153. ->whereIn('关联编号', $orderIds)
  154. ->whereIn('附件备注', '技术附件')
  155. ->whereNull('mod_rq')
  156. ->column('关联编号');
  157. // 遍历数据,判断每个订单编号是否在相关附件表中
  158. foreach ($list as &$value) {
  159. if (in_array($value['订单编号'], $relatedOrders)) {
  160. $value['status'] = ''; // 有相关附件,status为空
  161. } else {
  162. $value['status'] = '*'; // 没有相关附件,标记为新订单
  163. }
  164. if ($value['落货日期']) {
  165. $value['落货日期'] = date('Y-m-d', strtotime($value['落货日期']));
  166. }
  167. // 格式化接单日期,去掉时间部分
  168. if ($value['接单日期']) {
  169. $value['接单日期'] = date('Y-m-d', strtotime($value['接单日期']));
  170. }
  171. }
  172. $this->success('成功', ['data' => $list, 'total' => count($count)]);
  173. }
  174. /**
  175. * 月度客户订单汇总
  176. */
  177. public function ProductInformation()
  178. {
  179. if ($this->request->isGet() === false) {
  180. $this->error('请求错误');
  181. }
  182. $data = \db('工单_基本资料')->alias('j')
  183. ->field('j.客户编号,
  184. REPLACE(DATE_FORMAT(j.Sys_rq, "%Y-%m"), "-", "") as 年月,
  185. SUM(CASE WHEN j.gd_statu LIKE "%已完工%" THEN 1 ELSE 0 END) as 已完工数量,
  186. SUM(CASE WHEN j.gd_statu LIKE "%1-计划中%" THEN 1 ELSE 0 END) as 计划中数量
  187. ')
  188. ->where('j.Mod_rq', null)
  189. ->whereNotNull('j.客户编号')
  190. ->whereNotNull('j.gd_statu')
  191. ->group('j.客户编号, 年月')
  192. ->order('j.客户编号 asc')
  193. ->select();
  194. // 格式化数据
  195. $result = [];
  196. foreach ($data as $item) {
  197. $result[$item['年月']][] = $item['客户编号'] . '【已完工' . $item['已完工数量'] . ',计划中' . $item['计划中数量'] . '】';
  198. }
  199. $this->success('请求成功', ['data' => $result]);
  200. }
  201. /**
  202. * U8工单资料删除(软删除)
  203. * @param string Uniqid 工单Uniqid
  204. */
  205. public function orderDataDel()
  206. {
  207. if (!$this->request->isGet()) {
  208. $this->error('请求错误');
  209. }
  210. $uniqid = $this->request->param('Uniqid');
  211. if (empty($uniqid)) {
  212. $this->error('参数错误');
  213. }
  214. $order = Db::table('工单_基本资料')
  215. ->where('Uniqid|UniqId', $uniqid)
  216. ->whereNull('Mod_rq')
  217. ->field('Uniqid,UniqId,订单编号')
  218. ->find();
  219. if (empty($order)) {
  220. $this->error('工单不存在或已删除');
  221. }
  222. $orderNo = $order['订单编号'];
  223. $now = date('Y-m-d H:i:s');
  224. $softDelete = ['Mod_rq' => $now];
  225. Db::startTrans();
  226. try {
  227. Db::table('工单_印件资料')
  228. ->where('订单编号', $orderNo)
  229. ->whereNull('Mod_rq')
  230. ->update($softDelete);
  231. Db::table('工单_工艺资料')
  232. ->where('订单编号', $orderNo)
  233. ->whereNull('Mod_rq')
  234. ->update($softDelete);
  235. $result = Db::table('工单_基本资料')
  236. ->where('Uniqid|UniqId', $uniqid)
  237. ->whereNull('Mod_rq')
  238. ->update($softDelete);
  239. if ($result === false) {
  240. throw new \Exception('删除工单失败');
  241. }
  242. if ($result === 0) {
  243. throw new \Exception('未找到可删除的工单');
  244. }
  245. Db::commit();
  246. } catch (\think\exception\HttpResponseException $e) {
  247. throw $e;
  248. } catch (\Exception $e) {
  249. Db::rollback();
  250. $this->error('删除失败:' . $e->getMessage());
  251. }
  252. $this->success('成功');
  253. }
  254. /**
  255. * 新增工单->添加工单
  256. * @ApiMethod (POST)
  257. * @param
  258. */
  259. public function WorkOrderAdd()
  260. {
  261. if (Request::instance()->isPost() === false){
  262. $this->error('请求错误');
  263. }
  264. $param = Request::instance()->post();
  265. if (empty($param)){
  266. $this->error('参数错误');
  267. }
  268. $param['Sys_rq'] = date('Y-m-d H:i:s');
  269. $param['gd_statu'] = '1-计划中';
  270. // $prefix = substr($param['订单编号'], 0, 2);
  271. // $maxOrder = \db('工单_基本资料')
  272. // ->where('订单编号', 'like', "{$prefix}%")
  273. // ->order('订单编号', 'desc')
  274. // ->limit(1)
  275. // ->value('订单编号');
  276. // if ($maxOrder) {
  277. // $numericPart = substr($maxOrder, 2);
  278. // $newNumericPart = str_pad((int)$numericPart + 1, strlen($numericPart), '0', STR_PAD_LEFT);
  279. // $param['订单编号'] = $prefix . $newNumericPart;
  280. // } else {
  281. // $param['订单编号'] = $param['订单编号'];
  282. // }
  283. // if ($maxOrder) {
  284. // $numericPart = substr($maxOrder, 2);
  285. // $newNumericPart = str_pad((int)$numericPart + 1, strlen($numericPart), '0', STR_PAD_LEFT);
  286. // $param['订单编号'] = $prefix . $newNumericPart;
  287. // } else {
  288. // $param['订单编号'] = $param['订单编号'];
  289. // }
  290. $data = $param;
  291. unset($data['关联订单']);
  292. unset($data['关联面料ID']);
  293. //新增订单插入至工单基本资料
  294. $sql = \db('工单_基本资料')->fetchSql(true)->insert($data);
  295. \db()->query($sql);
  296. if (!empty($param['关联订单']) && !empty($param['关联面料ID'])){
  297. //关联订单编号
  298. $OrderId = $param['关联订单'];
  299. $OrderNumber = explode(',',$OrderId);
  300. //关联面料ID
  301. $RelevanceId = $param['关联面料ID'];
  302. //查询订单BOM资料,面料资料
  303. $RelevanceList = explode(',',$RelevanceId);
  304. $FabricList = $BomList = $MaterielList = [];
  305. foreach ($RelevanceList as $item){
  306. //工单面料信息
  307. $Fabric = \db('工单_面料资料')
  308. ->where('UNIQID',$item)
  309. ->where('Mod_rq',null)
  310. ->field('BOM_工单编号,BOM_颜色,BOM_物料编码,BOM_物料名称,BOM_投料单位,BOM_计划门幅,BOM_定额门幅')
  311. ->find();
  312. $OrderData = $Fabric;
  313. $OrderData['BOM_工单编号'] = $param['订单编号'];
  314. $OrderData['Sys_ID'] = $param['Sys_id'];
  315. $OrderData['Sys_rq'] = date('Y-m-d H:i:s',time());
  316. $OrderData['BOM_desc'] = $param['要求'];
  317. array_push($FabricList,$OrderData);
  318. //关联订单
  319. $AssociatedNumber = \db('工单关联表')
  320. ->where('订单编号',$Fabric['BOM_工单编号'])
  321. ->where('颜色',$Fabric['BOM_颜色'])
  322. ->where('物料编号',$Fabric['BOM_物料编码'])
  323. ->value('关联编号');
  324. $materiel = [
  325. '关联编号' => $AssociatedNumber,
  326. '订单编号' => $Fabric['BOM_工单编号'],
  327. '生产款号' => $param['生产款号'],
  328. '颜色' => $Fabric['BOM_颜色'],
  329. '物料编号' => $Fabric['BOM_物料编码'],
  330. '物料名称' => $Fabric['BOM_物料名称'],
  331. '备注' => $param['要求'],
  332. 'Sys_id' => $param['Sys_id'],
  333. 'Sys_rq' => date('Y-m-d H:i:s',time()),
  334. ];
  335. array_push($MaterielList,$materiel);
  336. }
  337. foreach ($MaterielList as $index => $item){
  338. $MaterielList[$index]['订单编号'] = $param['订单编号'];
  339. //工单BOM信息
  340. $Bom = \db('工单_bom资料')
  341. ->where('BOM_工单编号',$item['订单编号'])
  342. ->where('BOM_物料名称',$item['物料名称'])
  343. ->where('Mod_rq',null)
  344. ->find();
  345. unset($Bom['UNIQID']);
  346. unset($Bom['Mod_rq']);
  347. $Bom['Sys_ID'] = $param['Sys_id'];
  348. $Bom['Sys_rq'] = date('Y-m-d H:i:s',time());
  349. if (empty($BomList)){
  350. array_push($BomList,$Bom);
  351. }else{
  352. foreach ($BomList as $value){
  353. if ($value['BOM_工单编号'] !== $Bom['BOM_工单编号'] && $value['BOM_物料名称'] !== $Bom['BOM_物料名称']){
  354. array_push($BomList,$Bom);
  355. }
  356. }
  357. }
  358. }
  359. foreach ($BomList as $key => $value){
  360. $BomList[$key]['BOM_工单编号'] = $param['订单编号'];
  361. }
  362. //插入数据
  363. Db::startTrans();
  364. try {
  365. //BOM表数据插入
  366. $BomSql = \db('工单_bom资料')->fetchSql(true)->insertAll($BomList);
  367. $BomRes = \db()->query($BomSql);
  368. //面料表数据插入
  369. $FabricSql = \db('工单_面料资料')->fetchSql(true)->insertAll($FabricList);
  370. $FabricRes = \db()->query($FabricSql);
  371. //工单关联表数据插入
  372. $materielSql = \db('工单关联表')->fetchSql(true)->insertAll($MaterielList);
  373. $materielRes = \db()->query($materielSql);
  374. //提交数据
  375. Db::commit();
  376. }catch (\Exception $e){
  377. //回滚事务
  378. Db::rollback();
  379. }
  380. }else{
  381. //判断新增时面料是否存在,如果有调用gtp自动生成BOM资料
  382. if (!empty($param['面料'])) {
  383. // 只有面料不为空时,才调用 GdGtpAiOrder 方法
  384. $this->GdGtpAiOrder($param['订单编号']);
  385. }
  386. }
  387. $this->success('成功');
  388. }
  389. /**
  390. * 新增印件资料->印件资料添加
  391. * @return void
  392. * @throws \think\db\exception\BindParamException
  393. * @throws \think\exception\PDOException
  394. */
  395. public function PrintDetailAdd()
  396. {
  397. if (Request::instance()->isPost() === false){
  398. $this->error('请求错误');
  399. }
  400. $param = Request::instance()->post();
  401. if (empty($param)){
  402. $this->error('参数错误');
  403. }
  404. $param['Sys_rq'] = date('Y-m-d H:i:s',time());
  405. $process = [
  406. ['1','仓库出库'],['2','裁剪'],['3','车缝'],['4','后道收样'],['5','大烫'],['6','总检'],['7','包装']
  407. ];
  408. $processDetail = [];
  409. foreach ($process as $key=>$value){
  410. $total = null;
  411. if ($key !== 0){
  412. $total = $param['zdtotal'];
  413. }
  414. $processDetail[$key] = [
  415. '订单编号' => $param['订单编号'],
  416. '子订单编号' => $param['子订单编号'],
  417. '款号' => $param['款号'],
  418. '颜色' => $param['颜色'],
  419. '颜色备注' => $param['颜色备注'],
  420. '工序编号' => $value[0],
  421. '工序名称' => $value[1],
  422. '计划产量' => $total,
  423. 'Sys_id' => $param['Sys_id'],
  424. 'Sys_rq' => $param['Sys_rq']
  425. ];
  426. }
  427. $color = \db('工单_面料资料')
  428. ->where('Bom_工单编号',$param['订单编号'])
  429. ->where('BOM_颜色',$param['颜色备注'])
  430. ->where('Mod_rq',null)
  431. ->select();
  432. $colorList = [];
  433. if (empty($color)){
  434. $BomList = \db('工单_bom资料')
  435. ->where('BOM_工单编号',$param['订单编号'])
  436. ->where('Mod_rq',null)
  437. ->select();
  438. foreach ($BomList as $key=>$value){
  439. $colorList[$key] = [
  440. 'BOM_工单编号' => $param['订单编号'],
  441. 'BOM_颜色' => $param['颜色备注'],
  442. 'BOM_物料编码' => $param['款号'].'-'.$param['颜色备注'].($key+1),
  443. 'BOM_物料名称' => $value['BOM_物料名称'],
  444. 'U8UID' => $value['UNIQID'],
  445. 'BOM_投料单位' => '',
  446. 'Sys_ID' => $param['Sys_id'],
  447. 'Sys_rq' => date('Y-m-d H:i:s',time()),
  448. 'BOM_desc' => $value['BOM_desc']
  449. ];
  450. }
  451. }
  452. //获取最新的关联编号
  453. $AssociatedNumber = \db('工单关联表')->order('关联编号 desc')->column('关联编号');
  454. if (empty($AssociatedNumber)){
  455. $number = 0;
  456. }else{
  457. $number = (int)substr($AssociatedNumber[0],3);
  458. }
  459. $MaterielList = [];
  460. //插入工单关联数据表
  461. foreach ($colorList as $key=>$value){
  462. $MaterielList[$key] = [
  463. '关联编号' => 'GDGL'.($number + $key + 1),
  464. '订单编号' => $value['BOM_工单编号'],
  465. '生产款号' => $param['款号'],
  466. '颜色' => $param['颜色备注'],
  467. '物料编号' => $value['BOM_物料编码'],
  468. '物料名称' => $value['BOM_物料名称'],
  469. '备注' => $value['BOM_desc'],
  470. 'Sys_id' => $param['Sys_id'],
  471. 'Sys_rq' => date('Y-m-d H:i:s',time())
  472. ];
  473. }
  474. //开启事务
  475. db()->startTrans();
  476. try{
  477. //工单颜色录入
  478. $priSql = \db('工单_印件资料')->fetchSql(true)->insert($param);
  479. $priRes = \db()->query($priSql);
  480. //工单工艺录入
  481. $proSql = \db('工单_工艺资料')->fetchSql(true)->insertAll($processDetail);
  482. $proRes = \db()->query($proSql);
  483. if (!empty($colorList)){
  484. //工单面料录入
  485. $fabricSql = \db('工单_面料资料')->fetchSql(true)->insertAll($colorList);
  486. $fabricRes = \db()->query($fabricSql);
  487. }
  488. if (!empty($MaterielList)){
  489. //工单关联表录入
  490. $meterieSql = \db('工单关联表')->fetchSql(true)->insertAll($MaterielList);
  491. $meterieRes = \db()->query($meterieSql);
  492. }
  493. // 提交事务
  494. db()->commit();
  495. } catch (\Exception $e) {
  496. // 回滚事务
  497. db()->rollback();
  498. $this->error($e->getMessage());
  499. }
  500. if ($priRes !== false && $proRes !== false){
  501. $this->success('成功');
  502. }else{
  503. $this->error('失败');
  504. }
  505. }
  506. /**
  507. * 子订单列表
  508. * @return null
  509. * @throws \think\db\exception\DataNotFoundException
  510. * @throws \think\db\exception\ModelNotFoundException
  511. * @throws \think\exception\DbException
  512. */
  513. public function PrintListData()
  514. {
  515. // 检查请求方式
  516. if ($this->request->isGet() === false) {
  517. $this->error('请求错误');
  518. }
  519. $param = $this->request->param();
  520. // 检查参数是否存在
  521. if (isset($param) === false) {
  522. $this->error('参数错误');
  523. }
  524. // 查询型号
  525. $where['Mod_rq'] = null;
  526. $xhdata = \db('工单_印件资料')
  527. ->where('订单编号', $param['order'])
  528. ->where($where)
  529. ->field('cm1,cm2,cm3,cm4,cm5,cm6,cm7,cm8,cm9,cm10,cm11,cm12,cm13,cm14')
  530. ->select();
  531. $arr = [];
  532. foreach ($xhdata as $key => $value) {
  533. for ($i = 1; $i <= 14; $i++) {
  534. if ($value['cm' . $i] !== '' && $value['cm' . $i] !== null) {
  535. array_push($arr, $value['cm' . $i]);
  536. }
  537. }
  538. }
  539. $arr = array_unique($arr);
  540. sort($arr);
  541. // 查询详细列表
  542. $list = \db('工单_印件资料')
  543. ->where('订单编号', $param['order'])
  544. ->where($where)
  545. ->field('订单编号,子订单编号,款号,颜色,船样,zdtotal,Sys_id,Sys_rq,ck_rq,sc_rq,updatatime as 更新时间,Uniqid,颜色备注,
  546. cm1,cm2,cm3,cm4,cm5,cm6,cm7,cm8,cm9,cm10,cm11,cm12,cm13,cm14,
  547. cmsl1,cmsl2,cmsl3,cmsl4,cmsl5,cmsl6,cmsl7,cmsl8,cmsl9,cmsl10,cmsl11,cmsl12,cmsl13,cmsl14')
  548. ->select();
  549. // 遍历列表并处理cm和cmsl字段
  550. foreach ($list as $key => $value) {
  551. for ($i = 1; $i <= 14; $i++) {
  552. if ($value['cm' . $i] !== '') {
  553. // 如果 cmsl 的值为 0,则设置为空字符串
  554. $list[$key][$value['cm' . $i]] = ($value['cmsl' . $i] === 0) ? '' : $value['cmsl' . $i];
  555. }
  556. // 删除原有的 cm 和 cmsl 字段
  557. // unset($list[$key]['cm' . $i], $list[$key]['cmsl' . $i]);
  558. }
  559. }
  560. // 自定义型号排序
  561. $customOrder = array('XXS', 'XS', 'S', 'M', 'L', 'XL','2XL','XXL','3XL', 'XXXL','4XL','XXXXL','5XL','XXXXL');
  562. usort($arr, function ($a, $b) use ($customOrder) {
  563. $posA = array_search($a, $customOrder);
  564. $posB = array_search($b, $customOrder);
  565. return $posA - $posB;
  566. });
  567. $data['型号'] = $arr;
  568. $data['列表'] = $list;
  569. $this->success('成功', $data);
  570. }
  571. /**
  572. * 工单资料管理->印件资料删除
  573. * @return void
  574. * @throws \think\Exception
  575. * @throws \think\exception\PDOException
  576. */
  577. public function PrintDetailDel()
  578. {
  579. if ($this->request->isGet() === false){
  580. $this->error('请求错误');
  581. }
  582. $param = $this->request->param();
  583. if (isset($param['UniqId']) === false){
  584. $this->error('参数错误');
  585. }
  586. $printId = explode(',',$param['UniqId']);
  587. $i = 0;
  588. foreach ($printId as $value){
  589. $res = \db('工单_印件资料')
  590. ->where('Uniqid',$value)
  591. ->update(['Mod_rq'=>date('Y-m-d H:i:s',time())]);
  592. if ($res === false){
  593. $i++;
  594. }
  595. }
  596. if ($i === 0){
  597. $this->success('删除成功');
  598. }else{
  599. $this->error('删除失败');
  600. }
  601. }
  602. /**
  603. * 月度车间报工汇总->报工删除记录
  604. */
  605. public function ProcessDetailDel()
  606. {
  607. if ($this->request->isGet() === false){
  608. $this->error('请求错误');
  609. }
  610. $param = $this->request->param();
  611. if (empty($param)) {
  612. $this->error('参数错误');
  613. }
  614. $where['a.mod_rq'] = ['neq', ''];
  615. $list = \db('设备_产量计酬')->alias('a')
  616. ->join('工单_印件资料 b', 'b.订单编号 = a.订单编号 AND a.子订单编号 = a.子订单编号')
  617. ->join('工单_基本资料 j', 'b.订单编号 = j.订单编号', 'LEFT')
  618. ->field('
  619. b.订单编号, b.子订单编号, b.款号, b.颜色, b.船样, a.尺码, b.zdtotal as 制单数,b.颜色备注,
  620. a.数量, a.sys_rq as 上报时间,a.UniqId,a.mod_rq,a.delsys_id,a.sczl_bh,
  621. j.客户编号,j.生产款号,j.款式
  622. ')
  623. ->where($where)
  624. ->order('a.mod_rq desc')
  625. ->limit($param['page'],$param['limit'])
  626. ->group('a.UniqId')
  627. ->select();
  628. $count = \db('设备_产量计酬')->alias('a')
  629. ->join('工单_印件资料 b', 'b.订单编号 = a.订单编号 AND a.子订单编号 = a.子订单编号')
  630. ->join('工单_基本资料 j', 'b.订单编号 = j.订单编号', 'LEFT')
  631. ->field('
  632. b.订单编号, b.子订单编号, b.款号, b.颜色, b.船样, a.尺码, b.zdtotal as 制单数,b.颜色备注,
  633. a.数量, a.sys_rq as 上报时间,a.UniqId,a.mod_rq,a.delsys_id,a.sczl_bh,
  634. j.客户编号,j.生产款号,j.款式
  635. ')
  636. ->where($where)
  637. ->order('a.mod_rq desc')
  638. ->group('a.UniqId')
  639. ->select();
  640. // 提取所有的尺码,并去重
  641. $sizeList = array_values(array_unique(array_column($list, '尺码')));
  642. // 动态将尺码的数量添加到每个订单中,并替换已完成字段
  643. foreach ($list as &$item) {
  644. $size = $item['尺码'];
  645. $item[$size] = $item['数量']; // 动态添加尺码字段,值为数量
  646. // unset($item['数量']); // 移除原来的已完成字段
  647. }
  648. $data['total'] = count($count);
  649. $data['table'] = $list;
  650. $this->success('成功',$data);
  651. }
  652. /**
  653. * 订单附件上传新增
  654. * 1.前端进行上传xlsx文件表格
  655. * 2.接口接受数据文件进行保存xlsx文件以及pdf转换
  656. * 3.前端进行预览pdf图片显示文件中的内容再页面上
  657. */
  658. public function gdAnnexAdd() {
  659. ini_set('display_errors', 'On');
  660. ini_set('error_reporting', E_ALL);
  661. if (!$this->request->isPost()) {
  662. $this->error('请求方式错误');
  663. }
  664. // 获取请求参数
  665. $req = $this->request->param();
  666. $relateId = $req['关联编号'];
  667. if(empty($req['关联编号'])){
  668. $this->error('网络异常,请重新上传');
  669. }
  670. if($req['关联编号'] == 'undefined'){
  671. $this->error('网络异常,请重新上传');
  672. }
  673. $attachmentContent = $req['附件内容'];
  674. $attachmentType = $req['附件类型'];
  675. $prefixDir = ROOT_PATH . '/public/';
  676. $uploadDir = ''.'uploads/' . date('Ymd') . '/' . $relateId;
  677. // //技术附件上传代表订单开始生产
  678. // if($req['附件备注'] == '技术附件'){
  679. // DB::name('工单_基本资料')
  680. // ->where('订单编号', $relateId)
  681. // ->update(['gd_statu' => '2-生产中']);
  682. // }
  683. // 检查并创建目录
  684. if (!is_dir($prefixDir . $uploadDir)) {
  685. mkdir($prefixDir . $uploadDir, 0777, true);
  686. }
  687. // 处理 Base64 附件内容
  688. if (strpos($attachmentContent, 'base64,') !== false) {
  689. $attachmentContent = explode('base64,', $attachmentContent)[1];
  690. }
  691. $fileContent = base64_decode($attachmentContent);
  692. $filename = time();
  693. // 初始化文件路径变量
  694. $xlsxFilePath = '';
  695. $pdfFilePath = '';
  696. if ($attachmentType === 'pdf') {
  697. // 保存 PDF 文件
  698. $pdfFilePath = $uploadDir . '/' . $filename . '.pdf';
  699. file_put_contents($prefixDir . $pdfFilePath, $fileContent);
  700. } elseif ($attachmentType === 'xlsx') {
  701. // 保存 Excel 文件
  702. $xlsxFilePath = $uploadDir . '/' . $filename . '.xlsx';
  703. file_put_contents($prefixDir . $xlsxFilePath, $fileContent);
  704. // 转换为 PDF 文件
  705. $pdfFilePath = $uploadDir . '/' . $filename . '.pdf';
  706. $cmd = sprintf(
  707. 'libreoffice --headless --convert-to pdf --outdir %s %s',
  708. escapeshellarg($prefixDir . $uploadDir),
  709. escapeshellarg($prefixDir . $xlsxFilePath)
  710. );
  711. exec($cmd, $out, $retval);
  712. if ($retval !== 0) {
  713. $this->error('Excel 转 PDF 失败');
  714. }
  715. } else {
  716. $this->error('不支持的附件类型');
  717. }
  718. // 获取最新的记录,按 sys_rq 降序排列
  719. $latestItems = \db('工单_相关附件')
  720. ->where('关联编号', $relateId) // 根据关联编号筛选
  721. ->where('附件备注', $req['附件备注']) // 根据附件备注筛选
  722. ->whereNull('mod_rq')
  723. ->order('sys_rq desc') // 按照 sys_rq 降序排列
  724. ->group('关联编号') // 按关联编号分组,获取每个订单的最新记录
  725. ->find();
  726. // 如果查询为空,设置默认的版本号为 'v1.0'
  727. if (!$latestItems) {
  728. $currentVersion = 'v1.0';
  729. } else {
  730. $currentVersion = $latestItems['version']; // 当前记录的 version
  731. }
  732. // 解析当前版本号
  733. if (preg_match('/v(\d+)\.(\d+)/', $currentVersion, $matches)) {
  734. $majorVersion = (int)$matches[1]; // 主版本号
  735. $minorVersion = (int)$matches[2]; // 次版本号
  736. // 递增次版本号,若次版本号为 9,则主版本号加 1,次版本号置为 0
  737. if ($minorVersion < 9) {
  738. $minorVersion++;
  739. } else {
  740. $majorVersion++;
  741. $minorVersion = 0;
  742. }
  743. // 生成新的版本号
  744. $newVersion = 'v' . $majorVersion . '.' . $minorVersion;
  745. } else {
  746. // 如果没有匹配到版本号(例如没有 `v`),可以默认从 `v1.0` 开始
  747. $newVersion = 'v1.0';
  748. }
  749. if ($req['附件备注'] == '发货单附件'){
  750. $data = [
  751. 'rand_number' => date('YmdHis'),
  752. 'version' => $newVersion,
  753. '关联编号' => $relateId,
  754. 'sys_id' => $req['sys_id'],
  755. '附件备注' => $req['附件备注'],
  756. '附件类型' => $attachmentType,
  757. 'sys_rq' => date('Y-m-d H:i:s'),
  758. 'url' => $xlsxFilePath, // 保存 xlsx 文件路径(如果存在)
  759. 'pdf' => $pdfFilePath // 保存 pdf 文件路径
  760. ];
  761. }else{
  762. $data = [
  763. 'version' => $newVersion,
  764. '关联编号' => $relateId,
  765. 'sys_id' => $req['sys_id'],
  766. '附件备注' => $req['附件备注'],
  767. '附件类型' => $attachmentType,
  768. 'sys_rq' => date('Y-m-d H:i:s'),
  769. 'url' => $xlsxFilePath, // 保存 xlsx 文件路径(如果存在)
  770. 'pdf' => $pdfFilePath // 保存 pdf 文件路径
  771. ];
  772. }
  773. // 数据库事务处理
  774. db()->startTrans();
  775. try {
  776. // 插入数据
  777. $sql = db('工单_相关附件')->fetchSql(true)->insert($data);
  778. $result = db()->query($sql);
  779. db()->commit();
  780. } catch (\Exception $e) {
  781. // 回滚事务
  782. db()->rollback();
  783. $this->error($e->getMessage());
  784. }
  785. if ($result === false) {
  786. $this->error('失败');
  787. }
  788. $this->success('成功');
  789. }
  790. function fixPdfText($text) {
  791. // 修复数字间的空格丢失问题
  792. $patterns = [
  793. '/(\d{3})(\d{3})/' => '$1 $2', // 将6位数字分成3+3
  794. '/(\d{2})(\d{4})/' => '$1 $2', // 将6位数字分成2+4
  795. ];
  796. foreach ($patterns as $pattern => $replacement) {
  797. $text = preg_replace($pattern, $replacement, $text);
  798. }
  799. return $text;
  800. }
  801. //识别PDF文件内容
  802. public function Read_File(){
  803. if ($this->request->isGet() === false) {
  804. $this->error('请求错误');
  805. }
  806. $param = $this->request->param();
  807. //查询相关订单数据信息
  808. $order_list = Db::name('工单_基本资料')
  809. ->where('订单编号',$param['order'])
  810. ->whereNull('Mod_rq')
  811. ->find();
  812. if (!$order_list) {
  813. return json(['code' => 0, 'msg' => '未找到订单数据记录']);
  814. }
  815. //查询相关订单子订单数据
  816. $orderids_list = Db::name('工单_印件资料')
  817. ->where('订单编号',$param['order'])
  818. ->whereNull('Mod_rq')
  819. ->select();
  820. if (!$orderids_list) {
  821. return json(['code' => 0, 'msg' => '未找到相关子订单数据记录']);
  822. }
  823. //查询PDF文件数据信息
  824. $where = [];
  825. $where['UniqId'] = $param['UniqId'];
  826. $where['附件备注'] = "发货单附件";
  827. $res = Db::name('工单_相关附件')
  828. ->whereNull('mod_rq')
  829. ->where($where)
  830. ->order('sys_rq desc')
  831. ->find();
  832. if (!$res) {
  833. return json(['code' => 0, 'msg' => '未找到相关文件记录']);
  834. }
  835. $pdfPath = $res['pdf'];
  836. try {
  837. if (!class_exists('Smalot\PdfParser\Parser')) {
  838. return json(['code' => 0, 'msg' => '请先安装PDF解析库: composer require smalot/pdfparser']);
  839. }
  840. // $pdfUrl = $param['url']. $pdfPath;
  841. // $pdfContent = file_get_contents($pdfUrl);
  842. // if ($pdfContent === false) {
  843. // throw new Exception("无法下载PDF文件: " . $pdfUrl);
  844. // }
  845. // $parser = new \Smalot\PdfParser\Parser();
  846. // $pdf = $parser->parseContent($pdfContent);
  847. // $text = $pdf->getText();
  848. // echo "<pre>";
  849. // print_r($text);
  850. // echo "<pre>";die;
  851. //通过pdf提取内容
  852. $pdfUrl = $param['url'] .'/'. $pdfPath;
  853. $pdfContent = file_get_contents($pdfUrl);
  854. if ($pdfContent === false) {
  855. throw new Exception("无法下载PDF文件: " . $pdfUrl);
  856. }
  857. $parser = new \Smalot\PdfParser\Parser();
  858. $pdf = $parser->parseContent($pdfContent);
  859. $text = $pdf->getText();
  860. $text = $this->fixPdfText($text);
  861. $apiKey = 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss';
  862. // 构建订单数据字符串
  863. $order_data_str = "工单_基本资料:\n";
  864. $order_data_str .= "订单编号:{$order_list['订单编号']}\n";
  865. $order_data_str .= "生产款号:{$order_list['生产款号']}\n";
  866. $order_data_str .= "客户编号:{$order_list['客户编号']}\n";
  867. $order_data_str .= "款式:{$order_list['款式']}\n";
  868. $order_data_str .= "订单数量:{$order_list['订单数量']}\n";
  869. // 构建子订单数据字符串
  870. $suborder_data_str = "工单_印件资料:\n";
  871. foreach ($orderids_list as $index => $suborder) {
  872. $suborder_data_str .= "子订单" . ($index + 1) . ":\n";
  873. $suborder_data_str .= " 子订单编号:{$suborder['子订单编号']}\n";
  874. $suborder_data_str .= " 款号:{$suborder['款号']}\n";
  875. $suborder_data_str .= " 颜色:{$suborder['颜色']}\n";
  876. $suborder_data_str .= " 颜色备注:{$suborder['颜色备注']}\n";
  877. $suborder_data_str .= " 子订单数量:{$suborder['zdtotal']}\n";
  878. // 添加尺码信息
  879. for ($i = 1; $i <= 14; $i++) {
  880. $cm_field = "cm{$i}";
  881. $cmsl_field = "cmsl{$i}";
  882. if (!empty($suborder[$cm_field]) && !empty($suborder[$cmsl_field])) {
  883. $suborder_data_str .= " cm{$i}:{$suborder[$cm_field]}码, cmsl{$i}:{$suborder[$cmsl_field]}件\n";
  884. }
  885. }
  886. $suborder_data_str .= "\n";
  887. }
  888. $messages = [
  889. [
  890. 'role' => 'user',
  891. 'content' =>
  892. "需求说明:
  893. 从发货单中提取所有颜色和尺码的发货数量以及发货数量汇总信息,确保不遗漏任何一行数据。
  894. 特别注意:
  895. - 要提取全部数据,包括零头箱和单独行
  896. - 颜色代码,尺码
  897. - 发货数量按实际数量统计
  898. - 发货箱数按实际箱数统计
  899. - 每箱件数按标准箱规计算
  900. 数据格式要求,不需要其他任何解释:
  901. [
  902. {'颜色': '01', '尺码': 'M', '发货数量': '400', '发货箱数': '16', '每箱件数': '25'},
  903. {'颜色': '01', '尺码': 'L', '发货数量': '375', '发货箱数': '15', '每箱件数': '25'},
  904. {'颜色': '02', '尺码': 'M', '发货数量': '425', '发货箱数': '17', '每箱件数': '25'},
  905. {'颜色': '02', '尺码': 'L', '发货数量': '425', '发货箱数': '17', '每箱件数': '25'},
  906. {'颜色': '02', '尺码': 'L', '发货数量': '17', '发货箱数': '1', '每箱件数': '17'},
  907. {'颜色': '01', '尺码': 'M', '发货数量': '20', '发货箱数': '1', '每箱件数': '20'},
  908. {'颜色': '01', '尺码': 'L', '发货数量': '4', '发货箱数': '1', '每箱件数': '4'},
  909. {'颜色': '02', '尺码': 'M', '发货数量': '15', '发货箱数': '1', '每箱件数': '15'},
  910. ]
  911. 发货单内容:{$text}"
  912. ]
  913. ];
  914. // $result = [
  915. // [
  916. // "订单编号" => "DC2503217",
  917. // "子订单编号" => "DC2503217-0200",
  918. // "颜色" => "01",
  919. // "尺码" => "M",
  920. // "数量" => 450,
  921. // "发货数量" => "420",
  922. // "箱数" => "16"
  923. // ],
  924. // [
  925. // "订单编号" => "DC2503217",
  926. // "子订单编号" => "DC2503217-0200",
  927. // "颜色" => "01",
  928. // "尺码" => "L",
  929. // "数量" => 450,
  930. // "发货数量" => "379",
  931. // "箱数" => "15"
  932. // ],
  933. // [
  934. // "订单编号" => "DC2503217",
  935. // "子订单编号" => "DC2503217-0800",
  936. // "颜色" => "02",
  937. // "尺码" => "M",
  938. // "数量" => 450,
  939. // "发货数量" => "440",
  940. // "箱数" => "17"
  941. // ],
  942. // [
  943. // "订单编号" => "DC2503217",
  944. // "子订单编号" => "DC2503217-0800",
  945. // "颜色" => "02",
  946. // "尺码" => "L",
  947. // "数量" => 450,
  948. // "发货数量" => "442",
  949. // "箱数" => "17"
  950. // ]
  951. // ];
  952. //
  953. // $this->success('成功', $result);
  954. //die;
  955. $data = [
  956. 'model' => 'gpt-3.5-turbo',
  957. 'messages' => $messages,
  958. 'max_tokens' => 2048,
  959. 'temperature' => 0.3,
  960. ];
  961. $ch = curl_init('https://chatapi.onechats.top/v1/chat/completions');
  962. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  963. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  964. 'Content-Type: application/json',
  965. 'Authorization: Bearer ' . $apiKey,
  966. ]);
  967. curl_setopt($ch, CURLOPT_POST, true);
  968. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  969. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  970. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  971. $response = curl_exec($ch);
  972. if (curl_errno($ch)) {
  973. return json(['code' => 0, 'msg' => '请求失败: ' . curl_error($ch)]);
  974. }
  975. curl_close($ch);
  976. $responseData = json_decode($response, true);
  977. if (isset($responseData['error'])) {
  978. return json(['code' => 0, 'msg' => 'API错误: ' . $responseData['error']['message'], 'data' => $responseData]);
  979. }
  980. if (isset($responseData['choices'][0]['message']['content'])) {
  981. $content = $responseData['choices'][0]['message']['content'];
  982. // 提取JSON部分
  983. $json_start = strpos($content, '[');
  984. $json_end = strrpos($content, ']');
  985. if ($json_start !== false && $json_end !== false) {
  986. $json_str = substr($content, $json_start, $json_end - $json_start + 1);
  987. // 将单引号替换为双引号
  988. $json_str = str_replace("'", '"', $json_str);
  989. // 解析JSON
  990. $sql_data = json_decode($json_str, true);
  991. if (json_last_error() === JSON_ERROR_NONE && is_array($sql_data)) {
  992. $result = [];
  993. // 将API数据与订单信息结合
  994. $has_unmatched = false;
  995. foreach ($sql_data as $api_item) {
  996. $matched = false;
  997. // 在订单列表中查找匹配的颜色和尺码
  998. foreach ($orderids_list as $order) {
  999. $color_id = isset($order['颜色备注']) ? $order['颜色备注'] : '';
  1000. // 检查所有尺码
  1001. for ($i = 1; $i <= 14; $i++) {
  1002. $cm_key = 'cm' . $i;
  1003. $cmsl_key = 'cmsl' . $i;
  1004. if (!empty($order[$cm_key]) &&
  1005. $order[$cm_key] == $api_item['尺码'] &&
  1006. $color_id == $api_item['颜色']) {
  1007. $result[] = [
  1008. '订单编号' => isset($order['订单编号']) ? $order['订单编号'] : '',
  1009. '子订单编号' => isset($order['子订单编号']) ? $order['子订单编号'] : '',
  1010. '颜色' => isset($order['颜色']) ? $order['颜色'] : $api_item['颜色'],
  1011. '尺码' => $api_item['尺码'],
  1012. '制单数量' => isset($order[$cmsl_key]) ? $order[$cmsl_key] : 0,
  1013. '发货数量' => $api_item['发货数量'],
  1014. '发货箱数' => $api_item['发货箱数'],
  1015. '每箱件数' => $api_item['每箱件数'],
  1016. '匹配状态' => '匹配成功'
  1017. ];
  1018. $matched = true;
  1019. }
  1020. }
  1021. }
  1022. if (!$matched) {
  1023. $has_unmatched = true;
  1024. break; // 只要有一个未匹配,就直接返回提示
  1025. }
  1026. }
  1027. if ($has_unmatched) {
  1028. $this->success('颜色未匹配上');
  1029. } else {
  1030. $this->success('成功', $result);
  1031. }
  1032. } else {
  1033. return json(['code' => 0, 'msg' => 'JSON解析错误: ' . json_last_error_msg(), 'data' => $json_str]);
  1034. }
  1035. } else {
  1036. return json(['code' => 0, 'msg' => '未找到有效的JSON数据', 'data' => $content]);
  1037. }
  1038. } else {
  1039. return json(['code' => 0, 'msg' => 'API响应格式错误', 'data' => $responseData]);
  1040. }
  1041. } catch (Exception $e) {
  1042. return json(['code' => 0, 'msg' => '解析PDF时出错: ' . $e->getMessage()]);
  1043. }
  1044. }
  1045. public function Read_Add(){
  1046. if (Request::instance()->isPost() === false){
  1047. $this->error('请求错误');
  1048. }
  1049. $param = Request::instance()->post();
  1050. foreach ($param as $item) {
  1051. $Data = [
  1052. '订单编号' => $item['订单编号'],
  1053. '子订单编号' => $item['子订单编号'],
  1054. '尺码' => $item['尺码'],
  1055. '制单数量' => $item['制单数量'],
  1056. '发货箱数' => $item['发货箱数'],
  1057. '每箱件数' => $item['每箱件数'],
  1058. '发货数量' => $item['发货数量'],
  1059. 'sys_id' => $item['sys_id'],
  1060. 'sys_rq' => date('Y-m-d H:i:s'),
  1061. ];
  1062. $sql = \db('工单_发货基本资料')->fetchSql(true)->insert($Data);
  1063. \db()->query($sql);
  1064. }
  1065. $this->success('成功');
  1066. }
  1067. //按订单统计发货总数
  1068. public function Read_List(){
  1069. if ($this->request->isGet() === false) {
  1070. $this->error('请求错误');
  1071. }
  1072. $param = $this->request->param();
  1073. $Orders = \db('工单_基本资料')
  1074. ->where('客户编号', $param['khbh'])
  1075. ->whereNull('Mod_rq')
  1076. ->select();
  1077. if (empty($Orders)) {
  1078. $this->success('查询成功', []);
  1079. }
  1080. // 将订单数据转换为以订单编号为键的数组,方便查找
  1081. $orderMap = [];
  1082. foreach ($Orders as $order) {
  1083. $orderMap[$order['订单编号']] = $order;
  1084. }
  1085. $orderNumbers = array_column($Orders, '订单编号');
  1086. $shipmentData = \db('工单_发货基本资料')->alias('a')
  1087. ->field('j.客户编号, j.款式, j.生产款号, a.*')
  1088. ->join('工单_基本资料 j', 'a.订单编号 = j.订单编号', 'left')
  1089. ->whereNull('a.mod_rq')
  1090. ->where('a.订单编号', 'in', $orderNumbers)
  1091. ->select();
  1092. if (empty($shipmentData)) {
  1093. $this->success('查询成功', []);
  1094. }
  1095. // 修正的汇总统计(不包含明细)
  1096. $result = [];
  1097. foreach ($shipmentData as $item) {
  1098. $orderNo = $item['订单编号'];
  1099. // 如果该订单还没有在结果数组中,先初始化
  1100. if (!isset($result[$orderNo])) {
  1101. $orderInfo = $orderMap[$orderNo];
  1102. $result[$orderNo] = [
  1103. '订单编号' => $orderNo,
  1104. '客户编号' => $item['客户编号'],
  1105. '款式' => $item['款式'],
  1106. '生产款号' => $item['生产款号'],
  1107. '总发货箱数' => 0,
  1108. '总发货数量' => 0,
  1109. '制单数量' => $orderInfo['订单数量']
  1110. ];
  1111. }
  1112. // 累加发货箱数和发货数量
  1113. $result[$orderNo]['总发货箱数'] += intval($item['发货箱数'] ?? 0);
  1114. $result[$orderNo]['总发货数量'] += intval($item['发货数量'] ?? 0);
  1115. }
  1116. $finalResult = array_values($result);
  1117. $this->success('查询成功', $finalResult);
  1118. }
  1119. //按照子订单统计发货明细
  1120. public function Read_ListsData(){
  1121. if ($this->request->isGet() === false) {
  1122. $this->error('请求错误');
  1123. }
  1124. $param = $this->request->param();
  1125. $sql = \db('工单_发货基本资料')->alias('a')
  1126. ->field('j.客户编号,j.款式,j.生产款号,a.*')
  1127. ->join('工单_基本资料 j', 'a.订单编号 = j.订单编号', 'left')
  1128. ->whereNull('a.mod_rq')
  1129. ->where('a.订单编号', $param['order'])
  1130. ->select();
  1131. $this->success('查询成功',$sql);
  1132. }
  1133. /**
  1134. * 订单打印接口
  1135. * order:订单编号
  1136. * 通过订单编号获取订单表数据以及子订单数据
  1137. */
  1138. public function orderPrint(){
  1139. if ($this->request->isGet() === false){$this->error('请求错误');}
  1140. $param = $this->request->param();
  1141. if (empty($param['order'])){$this->error('参数错误');}
  1142. $where['Mod_rq'] = null;
  1143. //订单信息
  1144. $list = \db('工单_基本资料')
  1145. ->where('订单编号',$param['order'])
  1146. ->where($where)
  1147. ->field('订单编号,img,生产款号,客户编号,款式,落货日期,箱唛要求,面料,船样描述,船样合计,粘衬,订单数量,审核,审核日期,要求,water,Sys_id')
  1148. ->find();
  1149. //尺码表格表头
  1150. $xhdata = \db('工单_印件资料')->where('订单编号', $param['order'])->where($where)->select();
  1151. $arr = [];
  1152. foreach ($xhdata as $key => $value) {
  1153. for ($i = 1; $i <= 14; $i++) {
  1154. if ($value['cm' . $i] !== '' && $value['cm' . $i] !== null) {
  1155. array_push($arr, $value['cm' . $i]);
  1156. }
  1157. }
  1158. }
  1159. // 去重并重新索引
  1160. $arr = array_unique($arr);
  1161. $arr = array_values($arr);
  1162. // 自定义排序函数
  1163. usort($arr, function($a, $b) {
  1164. // 判断是否为数字
  1165. $isNumericA = is_numeric($a);
  1166. $isNumericB = is_numeric($b);
  1167. if ($isNumericA && $isNumericB) {
  1168. // 如果都是数字,按从小到大排序
  1169. return $a - $b;
  1170. } elseif (!$isNumericA && !$isNumericB) {
  1171. // 如果都是字母,按字母顺序排序(可以自定义顺序)
  1172. $sizeOrder = ['XXS', 'XS', 'S', 'M', 'L', 'XL','2XL','XXL','3XL', 'XXXL','4XL','XXXXL','5XL','XXXXL'];
  1173. $posA = array_search($a, $sizeOrder);
  1174. $posB = array_search($b, $sizeOrder);
  1175. return $posA - $posB;
  1176. } else {
  1177. // 如果一个是数字一个是字母,数字排在前
  1178. return $isNumericA ? -1 : 1;
  1179. }
  1180. });
  1181. //打印table数据表格
  1182. $porlis = \db('工单_印件资料')
  1183. ->where('订单编号',$param['order'])
  1184. ->where('船样',0)
  1185. ->where($where)
  1186. ->field('子订单编号')
  1187. ->select();
  1188. //合并后的子订单条码数据
  1189. $subOrder = $porlis[0]['子订单编号'];
  1190. // 找到子订单编号中的 '-' 位置
  1191. $dashPos = strpos($subOrder, '-');
  1192. if ($dashPos !== false) {
  1193. // 提取 '-' 后面的部分
  1194. $afterDash = substr($subOrder, $dashPos + 1);
  1195. // 判断长度是否等于2或等于4
  1196. if (strlen($afterDash) == 2) {
  1197. // 查询船样为0的数据
  1198. $processlist = \db('工单_印件资料')
  1199. ->where('订单编号', $param['order'])
  1200. ->where($where)
  1201. ->where('船样', 0)
  1202. ->field('子订单编号,颜色,款号,zdtotal,颜色备注,color_id,Uniqid,
  1203. cm1,cm2,cm3,cm4,cm5,cm6,cm7,cm8,cm9,cm10,cm11,cm12,cm13,cm14,
  1204. cmsl1,cmsl2,cmsl3,cmsl4,cmsl5,cmsl6,cmsl7,cmsl8,cmsl9,cmsl10,cmsl11,cmsl12,cmsl13,cmsl14')
  1205. ->select();
  1206. // 初始化汇总数组
  1207. $scslTotals = [
  1208. "cmsl1" => 0,
  1209. "cmsl2" => 0,
  1210. "cmsl3" => 0,
  1211. "cmsl4" => 0,
  1212. "cmsl5" => 0,
  1213. "cmsl6" => 0,
  1214. "cmsl7" => 0,
  1215. "cmsl8" => 0,
  1216. "cmsl9" => 0,
  1217. "cmsl10" => 0,
  1218. "cmsl11" => 0,
  1219. "cmsl12" => 0,
  1220. "cmsl13" => 0,
  1221. "cmsl14" => 0,
  1222. "zdtotal" => 0, // 总计数量
  1223. ];
  1224. // 遍历数据集进行汇总
  1225. foreach ($processlist as $item) {
  1226. for ($i = 1; $i <= 14; $i++) {
  1227. // 获取当前字段的数量
  1228. $sizeQty = $item['cmsl' . $i];
  1229. // 判断数量是否有效(非空且大于0)
  1230. if (!empty($sizeQty)) {
  1231. // 累加当前字段的数量
  1232. $scslTotals['cmsl' . $i] += $sizeQty;
  1233. // 累加到总计字段
  1234. $scslTotals['zdtotal'] += $sizeQty;
  1235. }
  1236. }
  1237. }
  1238. $data['scslTotals'] = $scslTotals;
  1239. foreach ($processlist as $key => $value) {
  1240. for ($i = 1; $i <= 14; $i++) {
  1241. if ($value['cm' . $i] !== '' && $value['cm' . $i] !== null) {
  1242. $processlist[$key][$value['cm' . $i]] = $value['cmsl' . $i];
  1243. }
  1244. // 移除原始的 cm 和 cmsl 字段
  1245. unset($processlist[$key]['cm' . $i], $processlist[$key]['cmsl' . $i]);
  1246. }
  1247. }
  1248. // 用于存储合并后的数据
  1249. $mergedData = [];
  1250. // 按颜色备注进行合并
  1251. foreach ($processlist as $item) {
  1252. $key = $item['颜色备注'];
  1253. if (!isset($mergedData[$key])) {
  1254. $mergedData[$key] = $item;
  1255. // 添加条码字段,值为子订单编号
  1256. $mergedData[$key]['条码'] = $item['子订单编号'];
  1257. } else {
  1258. // 合并尺码对应的数量
  1259. foreach ($item as $size => $quantity) {
  1260. if (is_numeric($size)) {
  1261. if (!isset($mergedData[$key][$size])) {
  1262. $mergedData[$key][$size] = 0;
  1263. }
  1264. $mergedData[$key][$size] += $quantity;
  1265. }
  1266. }
  1267. // 合并 zdtotal
  1268. $mergedData[$key]['zdtotal'] += $item['zdtotal'];
  1269. }
  1270. }
  1271. // 查询船样为1的数据
  1272. $chuanyang = \db('工单_印件资料')
  1273. ->where('订单编号', $param['order'])
  1274. ->where($where)
  1275. ->where('船样', 1)
  1276. ->field('子订单编号,颜色,款号,zdtotal,颜色备注,color_id,
  1277. cm1,cm2,cm3,cm4,cm5,cm6,cm7,cm8,cm9,cm10,cm11,cm12,cm13,cm14,
  1278. cmsl1,cmsl2,cmsl3,cmsl4,cmsl5,cmsl6,cmsl7,cmsl8,cmsl9,cmsl10,cmsl11,cmsl12,cmsl13,cmsl14,Uniqid')
  1279. ->select();
  1280. foreach ($chuanyang as $key => $value) {
  1281. for ($i = 1; $i <= 14; $i++) {
  1282. if ($value['cm' . $i] !== '' && $value['cm' . $i] !== null) {
  1283. $chuanyang[$key][$value['cm' . $i]] = $value['cmsl' . $i];
  1284. }
  1285. // 移除原始的 cm 和 cmsl 字段
  1286. unset($chuanyang[$key]['cm' . $i], $chuanyang[$key]['cmsl' . $i]);
  1287. }
  1288. // 添加条码字段,值为子订单编号
  1289. $chuanyang[$key]['条码'] = $value['子订单编号'];
  1290. }
  1291. // 将合并后的数据插入到相应颜色备注的原始数据尾部
  1292. $finalList = [];
  1293. $groupedData = [];
  1294. // 将原始数据按颜色备注分组
  1295. foreach ($processlist as $item) {
  1296. $key = $item['颜色备注'];
  1297. if (!isset($groupedData[$key])) {
  1298. $groupedData[$key] = [];
  1299. }
  1300. $groupedData[$key][] = $item;
  1301. }
  1302. // 将合并后的数据插入到对应的颜色备注组的尾部
  1303. foreach ($groupedData as $key => $items) {
  1304. $finalList = array_merge($finalList, $items); // 先添加原始数据
  1305. if (isset($mergedData[$key])) {
  1306. $finalList[] = $mergedData[$key]; // 在组的尾部添加合并数据
  1307. }
  1308. }
  1309. // 将船样为1的数据添加到最终列表中
  1310. $finalList = array_merge($finalList, $chuanyang);
  1311. $data['process'] = $finalList;
  1312. $data['order'] = $list;
  1313. $data['xhdata'] = $arr;
  1314. $this->success('成功',$data);
  1315. } elseif (strlen($afterDash) == 4) {
  1316. //一条子订单编号一个条码,统计颜色
  1317. $processlist = \db('工单_印件资料')
  1318. ->where('订单编号', $param['order'])
  1319. ->whereNull('Mod_rq') // 查询未删除数据
  1320. ->select();
  1321. $table = [];
  1322. foreach ($processlist as $item) {
  1323. // 当前子订单编号的数据
  1324. $subOrder = [
  1325. '颜色备注' => $item['颜色备注'],
  1326. '色系名称' => $item['颜色'],
  1327. '订单编号' => $item['订单编号'],
  1328. '子订单编号' => $item['子订单编号'],
  1329. '条码' => $item['子订单编号'],
  1330. '款号' => $item['款号'],
  1331. 'Sys_id' => $item['Sys_id'],
  1332. ];
  1333. // 当前子订单编号的合计
  1334. $subOrderTotal = 0;
  1335. for ($i = 1; $i <= 14; $i++) {
  1336. // 判断 cm 和 cmsl 是否有值,空值不显示,0 则显示
  1337. if (isset($item['cm' . $i]) && $item['cm' . $i] !== '') {
  1338. $subOrder[$item['cm' . $i]] = $item['cmsl' . $i] ?? 0; // 默认数量为 0
  1339. // 累加每个尺码的数量
  1340. $subOrderTotal += (int)$item['cmsl' . $i]; // 确保是数值类型
  1341. }
  1342. // 清理字段
  1343. unset($item['cm' . $i], $item['cmsl' . $i]);
  1344. }
  1345. $subOrder['合计'] = $subOrderTotal; // 添加合计
  1346. $table[] = $subOrder; // 将当前子订单的数据添加到 $table 中
  1347. }
  1348. // 初始化汇总数组
  1349. $scslTotals = [
  1350. "cmsl1" => 0,
  1351. "cmsl2" => 0,
  1352. "cmsl3" => 0,
  1353. "cmsl4" => 0,
  1354. "cmsl5" => 0,
  1355. "cmsl6" => 0,
  1356. "cmsl7" => 0,
  1357. "cmsl8" => 0,
  1358. "cmsl9" => 0,
  1359. "cmsl10" => 0,
  1360. "cmsl11" => 0,
  1361. "cmsl12" => 0,
  1362. "cmsl13" => 0,
  1363. "cmsl14" => 0,
  1364. "zdtotal" => 0, // 总计数量
  1365. ];
  1366. // 遍历数据集进行汇总
  1367. foreach ($processlist as $item) {
  1368. // 遍历每个尺码字段(cmsl1 到 cmsl10)
  1369. for ($i = 1; $i <= 14; $i++) {
  1370. // 获取当前字段的数量
  1371. $sizeQty = $item['cmsl' . $i];
  1372. // 判断数量是否有效(非空且大于0)
  1373. if (!empty($sizeQty)) {
  1374. // 累加当前字段的数量
  1375. $scslTotals['cmsl' . $i] += $sizeQty;
  1376. // 累加到总计字段
  1377. $scslTotals['zdtotal'] += $sizeQty;
  1378. }
  1379. }
  1380. }
  1381. $data['scslTotals'] = $scslTotals;
  1382. $data['process'] = $table;//汇总数据集
  1383. $data['order'] = $list;//表格数据
  1384. $data['xhdata'] = $arr;//尺码表头
  1385. $this->success('成功', $data);
  1386. // }
  1387. } else {
  1388. echo "子订单编号 - 后不是2位也不是4位:$afterDash";
  1389. }
  1390. } else {
  1391. echo "子订单编号中没有找到'-'";
  1392. }
  1393. }
  1394. /**
  1395. * 订单编号自动获取
  1396. * @return void
  1397. * @throws \think\db\exception\DataNotFoundException
  1398. * @throws \think\db\exception\ModelNotFoundException
  1399. * @throws \think\exception\DbException
  1400. */
  1401. public function getWorkOrder()
  1402. {
  1403. if ($this->request->isGet() === false){
  1404. $this->error('请求错误');
  1405. }
  1406. $time =substr( date('Ym',time()),2);
  1407. $lastOrder = \db('工单_基本资料')
  1408. ->where('订单编号','like','%'.$time.'%')
  1409. ->order('Uniqid desc')
  1410. ->whereNull('Mod_rq')
  1411. ->find();
  1412. if (empty($lastOrder)){
  1413. $newNumber = 1;
  1414. }else{
  1415. $lastNumber = substr($lastOrder['订单编号'],6);
  1416. $newNumber = (int)$lastNumber + 1;
  1417. }
  1418. if ($newNumber<10){
  1419. $newOrder = 'DC'.$time.'00'.$newNumber;
  1420. }elseif ($newNumber>=10 && $newNumber<100){
  1421. $newOrder = 'DC'.$time.'0'.$newNumber;
  1422. }else{
  1423. $newOrder = 'DC'.$time.$newNumber;
  1424. }
  1425. $this->success('成功',$newOrder);
  1426. }
  1427. /**
  1428. * 获取子订单编号
  1429. * @return void
  1430. * @throws \think\db\exception\DataNotFoundException
  1431. * @throws \think\db\exception\ModelNotFoundException
  1432. * @throws \think\exception\DbException
  1433. */
  1434. public function getSuborder(){
  1435. // 确保是GET请求
  1436. if ($this->request->isGet() === false) {
  1437. $this->error('请求错误');
  1438. }
  1439. $param = $this->request->param();
  1440. if (empty($param) || !isset($param['cy']) || !isset($param['order'])) {
  1441. $this->error('参数错误');
  1442. }
  1443. // 判断是否“船样”获取对应的子订单编号
  1444. if ($param['cy'] == '否') {
  1445. //1.通过色系名称查询对应的编号
  1446. $colorlist = \db('工单_颜色编号')
  1447. ->field('colorcode, colorname')
  1448. ->where('colorname', $param['colorname'] ?? '')
  1449. ->find();
  1450. if (empty($colorlist)) {
  1451. $this->error('未找到对应的颜色编号');
  1452. }
  1453. $num = $param['order'] . '-' . $colorlist['colorcode'];
  1454. // 查询子订单编号
  1455. $data = \db('工单_印件资料')
  1456. ->field('子订单编号,cm1,cm2,cm3,cm4,cm5,cm6,cm7,cm8,cm9,cm10,cm11,cm12,cm13,cm14')
  1457. ->where('子订单编号', 'like', '%' . $num . '%')
  1458. ->where('船样', '=', 0)
  1459. ->whereNull('Mod_rq')
  1460. ->order('子订单编号', 'desc')
  1461. ->find();
  1462. if (empty($data)) {
  1463. // 如果没有找到数据,生成默认的订单编号,后两位从00开始
  1464. $order = $param['order'] . '-' . $colorlist['colorcode'] . '00';
  1465. } else {
  1466. if (strlen($data['子订单编号']) == 12) {
  1467. $data = \db('工单_印件资料')
  1468. ->where('订单编号',$param['order'])
  1469. ->where('船样',0)
  1470. ->whereNull('Mod_rq')
  1471. ->order('子订单编号 desc')
  1472. ->find();
  1473. if(empty($data)){
  1474. $order = $param['order'].'-01';
  1475. }else{
  1476. $num = (int)substr($data['子订单编号'],10) + 1;
  1477. if ($num<10){
  1478. $order = $param['order'].'-0'.$num;
  1479. }else{
  1480. $order = $param['order'].'-'.$num;
  1481. }
  1482. }
  1483. }else{
  1484. // 如果找到数据,提取子订单编号并递增
  1485. $order = $data['子订单编号'];
  1486. if (preg_match('/(.*-' . $colorlist['colorcode'] . ')(\d{2})$/', $order, $matches)) {
  1487. $prefix = $matches[1]; // 前缀部分(包括订单编号和颜色代码)
  1488. $number = $matches[2]; // 数字部分(后两位)
  1489. // 循环生成子订单编号并检查数据库中是否存在相同编号
  1490. do {
  1491. $incrementedNumber = (int)$number + 1;
  1492. // 将数字部分补充为两位数,例如 1 -> 01,2 -> 02
  1493. $order = $prefix . str_pad($incrementedNumber, 2, '0', STR_PAD_LEFT);
  1494. $exists = \db('工单_印件资料')->whereNull('Mod_rq')->where('子订单编号', '=', $order)->find();
  1495. $number = $incrementedNumber; // 更新 number 用于下一次循环
  1496. } while ($exists); // 如果存在相同编号则继续循环递增
  1497. } else {
  1498. $this->error('订单编号格式错误');
  1499. }
  1500. }
  1501. }
  1502. //2.获取色系名称信息
  1503. $colorlist = \db('工单_颜色编号')->select();
  1504. //3.获取历史尺码数据
  1505. $cm_list = \db('工单_印件资料')
  1506. ->where('订单编号', $param['order'])
  1507. ->group('订单编号')
  1508. ->find();
  1509. $cm_data = [];
  1510. if ($cm_list) {
  1511. // 精准筛选字段名以 "cm" 开头并跟1到2位数字的字段
  1512. foreach ($cm_list as $key => $value) {
  1513. if (preg_match('/^cm\d{1,2}$/', $key)) {
  1514. $cm_data[$key] = $value ?? ''; // 如果值为 null,设为空字符串
  1515. }
  1516. }
  1517. } else {
  1518. // 如果查询结果为空,将都设置为空
  1519. for ($i = 1; $i <= 14; $i++) {
  1520. $cm_data["cm$i"] = '';
  1521. }
  1522. }
  1523. $result = ['order' => $order,'colorlist' => $colorlist,'cm' => $cm_data];
  1524. $this->success('成功', $result);
  1525. } else if ($param['cy'] == '是') {
  1526. //1.获取船样子订单编号
  1527. $data = \db('工单_印件资料')
  1528. ->where('订单编号', $param['order'])
  1529. ->where('船样', '=', 1)
  1530. ->order('子订单编号 asc')
  1531. ->find();
  1532. if (empty($data)) {
  1533. // 如果没有数据,初始子订单编号为 '99'
  1534. $order = $param['order'] . '-99';
  1535. } else {
  1536. // 提取子订单编号中的数字部分
  1537. $subOrder = $data['子订单编号']; // 例如 "DC2410006-99"
  1538. if (preg_match('/-(\d+)$/', $subOrder, $matches)) {
  1539. $numberPart = (int)$matches[1]; // 提取到的数字部分
  1540. $newNumber = $numberPart - 1; // 减 1
  1541. // 将新的数字拼接回订单编号
  1542. $order = preg_replace('/-\d+$/', '-' . $newNumber, $subOrder);
  1543. } else {
  1544. $this->error('订单编号格式错误');
  1545. }
  1546. }
  1547. $this->success('成功', $order);
  1548. }
  1549. }
  1550. /**
  1551. * 获取PO号 【代码展示未用到】
  1552. */
  1553. public function getPonumber() {
  1554. if ($this->request->isGet() === false){
  1555. $this->error('请求错误');
  1556. }
  1557. $param = $this->request->param();
  1558. if (empty($param)){
  1559. $this->error('参数错误');
  1560. }
  1561. // $num = substr($param['child_order'], 0, 12); // 如果需要,可以用这个方式截取子订单编号
  1562. // $sql = "SELECT * FROM `工单_印件资料` WHERE `子订单编号` LIKE '{$num}%' ORDER BY `子订单编号` DESC LIMIT 1";
  1563. // $data = \db()->query($sql);
  1564. $colorlist = \db('工单_颜色编号')
  1565. ->field('colorcode,colorname')
  1566. ->where('colorname',$param['child_order'])
  1567. ->find();
  1568. $num = $param['order'] . '-' . $colorlist['colorcode']; // 生成 num,用于模糊查询
  1569. $data = \db('工单_印件资料')
  1570. ->where('子订单编号', 'like', '%' . $num . '%')
  1571. ->order('子订单编号', 'desc')
  1572. ->find();
  1573. if(count($data) === 1){
  1574. $order = $num.'01';
  1575. }else{
  1576. $number = (int)substr($data['子订单编号'],12,14) + 1;
  1577. if ($num<10){
  1578. $order = $num.'0'.$number;
  1579. }else{
  1580. $order = $num.$number;
  1581. }
  1582. }
  1583. $this->success('成功',$order);
  1584. }
  1585. /**
  1586. * 订单资料修改
  1587. * @return void
  1588. * @throws \think\Exception
  1589. * @throws \think\db\exception\BindParamException
  1590. * @throws \think\exception\PDOException
  1591. */
  1592. public function WorkOrderEdit()
  1593. {
  1594. if (Request::instance()->isPost() === false){
  1595. $this->error('请求错误');
  1596. }
  1597. $param = Request::instance()->post();
  1598. if (empty($param)){
  1599. $this->error('参数错误');
  1600. }
  1601. $id = $param['id'];
  1602. unset($param['id']);
  1603. $sql = \db('工单_基本资料')
  1604. ->where('Uniqid',$id)
  1605. ->fetchSql(true)
  1606. ->update($param);
  1607. $res = \db()->query($sql);
  1608. if ($res === false){
  1609. $this->error('失败');
  1610. }else{
  1611. $this->success('成功');
  1612. }
  1613. }
  1614. /**
  1615. * 颜色资料修改
  1616. */
  1617. public function PrintDataEdit()
  1618. {
  1619. if(Request::instance()->post() === false){
  1620. $this->error('请求错误');
  1621. }
  1622. $param = Request::instance()->post();
  1623. if (empty($param)){
  1624. $this->error('参数错误');
  1625. }
  1626. $updata = [
  1627. '订单编号' => $param['订单编号'],
  1628. '子订单编号' => $param['子订单编号'],
  1629. '款号' => $param['款号'],
  1630. '船样' => $param['船样'],
  1631. '颜色' => $param['颜色'],
  1632. 'color_id' => $param['color_id'],
  1633. '颜色备注' => $param['颜色备注'],
  1634. 'zdtotal' => $param['zdtotal'],
  1635. 'updatatime' => date('Y-m-d H:i:s')
  1636. ];
  1637. for ($i = 1; $i <= 14; $i++) {
  1638. $updata["cmsl{$i}"] = isset($param["cmsl{$i}"]) ? $param["cmsl{$i}"] : '';
  1639. }
  1640. $sql = \db('工单_印件资料')
  1641. ->where('Uniqid', $param['id'])
  1642. ->fetchSql(true)
  1643. ->update($updata);
  1644. $res = \db()->query($sql);
  1645. if ($res !== false) {
  1646. $this->success('修改成功');
  1647. } else {
  1648. $this->error('修改失败');
  1649. }
  1650. }
  1651. /**
  1652. * 图片上传
  1653. * @return void
  1654. */
  1655. public function ImgUpload(){
  1656. $file = request()->file('image');
  1657. if($file){
  1658. $info = $file->validate(['size'=>10485760,'ext'=>'jpg,png'])->move(ROOT_PATH . 'public' . DS . 'uploads');
  1659. if($info){
  1660. $fileName = $info->getSaveName();
  1661. // $ymd = date('Ymd');
  1662. // $imageUrl = '/uploads/' . $ymd.'/'.$fileName;
  1663. $imageUrl = '/uploads/' . str_replace('\\', '/', $fileName);
  1664. return json(['code' => 0, 'msg' => '成功', 'data' => ['url' => $imageUrl]]);
  1665. }else{
  1666. $res = $file->getError();
  1667. return json(['code' => 1, 'msg' => '失败', 'data' => $res]);
  1668. }
  1669. }
  1670. return json(['code' => 1, 'msg' => '没有文件上传', 'data' => null]);
  1671. }
  1672. /**
  1673. * 附件资料左侧菜单(日期格式)
  1674. */
  1675. public function OrderMenuList()
  1676. {
  1677. $list = \db('工单_相关附件')
  1678. ->field('sys_rq')
  1679. ->whereNull('mod_rq')
  1680. ->group('sys_rq')
  1681. ->select();
  1682. $result = [];
  1683. foreach ($list as $item) {
  1684. $dateTime = $item['sys_rq'];
  1685. $dateOnly = date('Y-m-d', strtotime($dateTime)); // 提取日期
  1686. $year = date('Y', strtotime($dateTime));
  1687. // 加上(int)date('m', strtotime($sys_rq))转成数字去掉前导 01 => 1
  1688. $month = date('m', strtotime($dateTime));
  1689. // 初始化结构
  1690. if (!isset($result[$year])) {
  1691. $result[$year] = [];
  1692. }
  1693. if (!isset($result[$year][$month])) {
  1694. $result[$year][$month] = [];
  1695. }
  1696. // 避免重复添加相同日期
  1697. if (!in_array($dateOnly, $result[$year][$month])) {
  1698. $result[$year][$month][] = $dateOnly;
  1699. }
  1700. }
  1701. // 按年月日进行倒序排序
  1702. foreach ($result as $year => &$months) {
  1703. krsort($months); // 月份倒序
  1704. foreach ($months as &$dates) {
  1705. rsort($dates); // 日期倒序
  1706. }
  1707. }
  1708. $this->success('成功', $result);
  1709. }
  1710. /**
  1711. * 订单附件技术附件
  1712. */
  1713. /**
  1714. * 订单附件技术附件
  1715. */
  1716. public function OrderAttachments()
  1717. {
  1718. if ($this->request->isGet() === false) {
  1719. $this->error('请求错误');
  1720. }
  1721. $param = $this->request->param();
  1722. $sys_rq = isset($param['sys_rq']) ? trim($param['sys_rq']) : ''; // yyyy-mm-dd
  1723. $order = $param['order'];
  1724. $desc = $param['desc'];
  1725. $page = max(1, intval(input('page', 1)));
  1726. $limit = max(1, intval(input('limit', 10)));
  1727. $where = [];
  1728. if ($order !== '') {
  1729. $where['关联编号'] = $order;
  1730. }
  1731. // 附件类型筛选(如技术附件)
  1732. if ($desc !== '') {
  1733. $where['附件备注'] = $desc;
  1734. }
  1735. // 日期筛选
  1736. if ($sys_rq !== '') {
  1737. $where['sys_rq'] = ['like', '%' . $sys_rq . '%'];
  1738. }
  1739. // 基础查询条件
  1740. $query = \db('工单_相关附件')
  1741. ->field('UniqId, mod_rq, pdf, sys_id, sys_rq, updatetime, url, version, 关联编号, 附件内容, 附件备注, 附件类型, rand_number')
  1742. ->where($where)
  1743. ->where('version', '<>', '')
  1744. ->whereNull('mod_rq')
  1745. ->order('sys_rq desc');
  1746. // 统一分页逻辑
  1747. if ($order === '') {
  1748. // 订单为空时分页查询
  1749. $list = $query->limit(($page - 1) * $limit, $limit)->select();
  1750. } else {
  1751. // 订单不为空时也需要分页
  1752. $list = $query->limit(($page - 1) * $limit, $limit)->select();
  1753. }
  1754. $count = $query->count();
  1755. $data = [
  1756. 'total' => $count,
  1757. 'list' => $list
  1758. ];
  1759. $this->success('成功', $data);
  1760. }
  1761. /**
  1762. * 工单附件删除
  1763. */
  1764. public function delfujian(){
  1765. if (!$this->request->isPost()) {
  1766. $this->error('非法请求');
  1767. }
  1768. $params = $this->request->param();
  1769. $updateData = [
  1770. 'mod_rq' => date('Y-m-d H:i:s'),
  1771. 'mod_id' => $params['登录用户'],
  1772. ];
  1773. $res = \db('工单_相关附件')->where('UniqId', $params['UniqId'])->update($updateData);
  1774. if ($res) {
  1775. $this->success('删除成功');
  1776. } else {
  1777. $this->error('删除失败');
  1778. }
  1779. }
  1780. /**
  1781. * 订单BOM资料显示
  1782. */
  1783. public function OrderBomList()
  1784. {
  1785. if ($this->request->isGet() === false) {
  1786. $this->error('请求错误');
  1787. }
  1788. $param = $this->request->param();
  1789. if (empty($param) || !isset($param['order'])) {
  1790. $this->error('参数错误');
  1791. }
  1792. $where = ['a.BOM_工单编号' => $param['order']];
  1793. // 仅入库:按工单+物料名称汇总 number;多条入库时 rq 取最大(最后入库日)
  1794. $inboundSub = \db('库存_出入库明细')
  1795. ->where('name', '入库')
  1796. ->whereNull('Mod_rq')
  1797. ->field('order_id, 物料名称, SUM(`number`) as 入库数量, MAX(rq) as 实际入库时间')
  1798. ->group('order_id, 物料名称')
  1799. ->buildSql();
  1800. $list = \db('工单_bom资料')
  1801. ->alias('a')
  1802. ->join('工单_基本资料 b', 'b.订单编号 = a.BOM_工单编号')
  1803. ->join([$inboundSub => 'c'], 'a.BOM_工单编号 = c.order_id AND a.BOM_物料名称 = c.物料名称', 'LEFT')
  1804. ->field('a.BOM_工单编号 as 订单编号,b.生产款号 as 生产款号,b.客户编号 as 客户编号,b.款式 as 款式,
  1805. a.BOM_物料名称 as 物料名称,a.BOM_投料单位 as 投料单位,a.BOM_计划用量 as 计划用料,a.BOM_标准用量 as 定额用料,
  1806. a.计划入库时间,
  1807. a.计划入库操作人,
  1808. b.审核日期 as 核批日期,
  1809. b.审核 as 核批人,
  1810. a.BOM_实际用量 as 裁床实际用料,a.BOM_desc as 备注,a.UNIQID,a.物料分类,
  1811. a.BOM_计划门幅 as 计划门幅, a.BOM_定额门幅 as 定额门幅,a.Sys_ID as ID,a.Sys_rq as 日期,
  1812. c.实际入库时间,c.入库数量')
  1813. ->where($where)
  1814. ->whereNull('b.Mod_rq')
  1815. ->whereNull('a.Mod_rq')
  1816. ->order('a.UNIQID desc')
  1817. ->select();
  1818. if (!empty($list)) {
  1819. // 获取去重后的物料名称
  1820. $materialNames = array_column($list, '物料名称');
  1821. $materialNames = array_unique($materialNames);
  1822. // 根据去重后的物料名称查询工单_面料资料表,并获取BOM_desc
  1823. $materialDetails = \db('工单_面料资料')
  1824. ->field('BOM_物料名称 as 物料名称,BOM_desc')
  1825. ->whereIn('BOM_物料名称', $materialNames)
  1826. ->select();
  1827. // 将物料名称与BOM_desc对应起来
  1828. $materialDescMap = [];
  1829. foreach ($materialDetails as $detail) {
  1830. $materialDescMap[$detail['物料名称']] = $detail['BOM_desc'];
  1831. }
  1832. // 在list中添加对应的BOM_desc
  1833. foreach ($list as &$item) {
  1834. if (isset($materialDescMap[$item['物料名称']])) {
  1835. $item['BOM_desc'] = $materialDescMap[$item['物料名称']];
  1836. } else {
  1837. $item['BOM_desc'] = '';
  1838. }
  1839. }
  1840. $this->success('成功', $list);
  1841. } else {
  1842. $this->GdGtpAiOrder($param['order']);
  1843. $this->success('没有找到相关数据',[]);
  1844. // return $this->success('没有找到相关数据', []);
  1845. }
  1846. }
  1847. /**
  1848. * Bom资料删除
  1849. * */
  1850. public function Bomdel(){
  1851. if ($this->request->isGet() === false) {
  1852. $this->error('请求错误');
  1853. }
  1854. $param = $this->request->param();
  1855. if (empty($param) || !isset($param['UNIQID'])) {
  1856. $this->error('参数错误');
  1857. }
  1858. $uniqids = strpos($param['UNIQID'], ',') !== false ? explode(',', $param['UNIQID']) : [$param['UNIQID']];
  1859. $where = [];
  1860. $where['Mod_rq'] = date('Y-m-d H:i:s', time());
  1861. $allUpdated = true;
  1862. $failedUniqids = [];
  1863. // 遍历所有UNIQID并更新数据库
  1864. foreach ($uniqids as $uniqid) {
  1865. $list = \db('工单_bom资料')
  1866. ->where('UNIQID', $uniqid)
  1867. ->find();
  1868. $cangku = Db::name('库存_出入库明细')
  1869. ->where('order_id',$list['BOM_工单编号'])
  1870. ->where('物料名称',$list['BOM_物料名称'])
  1871. ->whereNull('Mod_rq')
  1872. ->find();
  1873. if ($cangku) {
  1874. return json([
  1875. 'code' => 1,
  1876. 'msg' => '【物料名称】:' . $list['BOM_物料名称'] . '。该物料仓库已录入,暂无法删除。如需删除,请联系仓库人员清除相关明细数据后再进行操作。'
  1877. ])->options(['json_encode_param' => JSON_UNESCAPED_UNICODE]);
  1878. }
  1879. $result = \db('工单_bom资料')
  1880. ->where('UNIQID', $uniqid)
  1881. ->update($where);
  1882. $arr = \db('工单_面料资料')
  1883. ->where('BOM_工单编号', $list['BOM_工单编号'])
  1884. ->where('BOM_物料名称', $list['BOM_物料名称'])
  1885. ->update($where);
  1886. $arr = \db('工单关联表')
  1887. ->where('订单编号', $list['BOM_工单编号'])
  1888. ->where('物料名称', $list['BOM_物料名称'])
  1889. ->update($where);
  1890. if (!$result) {
  1891. // 如果某个UNIQID更新失败,记录失败的ID
  1892. $allUpdated = false;
  1893. $failedUniqids[] = $uniqid;
  1894. }
  1895. }
  1896. if ($allUpdated) {
  1897. $list = \db('工单_bom资料')
  1898. ->whereIn('UNIQID', $uniqids)
  1899. ->select();
  1900. if (!empty($list)) {
  1901. $this->success('删除成功');
  1902. } else {
  1903. $this->GdGtpAiOrder($param['order']);
  1904. return $this->success('没有找到相关数据', []);
  1905. }
  1906. } else {
  1907. $this->error('部分更新失败,无法更新以下UNIQID: ' . implode(', ', $failedUniqids));
  1908. }
  1909. }
  1910. /**
  1911. * 前端选择订单时如果BOM资料数据为空则单独调用,重新生成最新
  1912. */
  1913. public function GdGtpAiOrder($order){
  1914. // 判断是否有指定的订单号
  1915. if (!empty($order)) {
  1916. // 查询单个订单的最大编号
  1917. $maxOrder = \db('工单_基本资料')
  1918. ->where('订单编号', 'like', "{$order}%")
  1919. ->order('订单编号', 'desc')
  1920. ->limit(1)
  1921. ->value('订单编号');
  1922. // 查询该订单的基本资料
  1923. $list = \db('工单_基本资料')
  1924. ->where('订单编号', 'like', "{$order}%")
  1925. ->order('订单编号', 'desc')
  1926. ->limit(1)
  1927. ->find();
  1928. // 如果面料数据为空,提示错误
  1929. if (empty($list['面料'])) {
  1930. $this->error('面料数据为空无法定义BOM');
  1931. }
  1932. // 处理订单编号
  1933. $numericPart = substr($maxOrder, 2);
  1934. $newNumericPart = str_pad((int)$numericPart + 1, strlen($numericPart), '0', STR_PAD_LEFT);
  1935. $param['订单编号'] = $order . $newNumericPart;
  1936. // 处理物料信息
  1937. $massage = empty($list['粘衬']) || $list['粘衬'] == '无' ? $list['面料'] : $list['面料'] . ',粘衬:' . $list['粘衬'];
  1938. $materialCategories = [];
  1939. $pattern = '/(\S+?):([^,]+)/'; // 匹配 类别:物料 格式
  1940. preg_match_all($pattern, $massage, $matches, PREG_SET_ORDER);
  1941. foreach ($matches as $match) {
  1942. $category = $match[1]; // 分类名称
  1943. $materials = explode('+', $match[2]); // 如果物料名称中有‘+’,则分开处理多个物料
  1944. // 将分类和对应的物料添加到数组中
  1945. foreach ($materials as $material) {
  1946. $materialCategories[$category][] = trim($material); // 去除物料两边的空格
  1947. }
  1948. }
  1949. $mianliao = $this->Gpt($massage);
  1950. $data = [];
  1951. // if ($mianliao) {
  1952. // $this->success('成功');
  1953. // }
  1954. foreach ($mianliao as $value) {
  1955. if (!empty($value) && $value !== '粘衬') { // 排除空值和粘衬
  1956. $category = '';
  1957. // 查找物料对应的分类
  1958. foreach ($materialCategories as $cat => $materials) {
  1959. if (in_array($value, $materials)) {
  1960. $category = $cat;
  1961. break;
  1962. }
  1963. }
  1964. // 如果找到分类,将数据存入BOM
  1965. $data[] = [
  1966. 'BOM_工单编号' => $list['订单编号'],
  1967. 'BOM_物料名称' => $value,
  1968. 'BOM_desc' => '',
  1969. '物料分类' => $category ? $category : '',
  1970. 'Sys_rq' => date('Y-m-d H:i:s'),
  1971. 'Sys_ID' => $list['Sys_id']
  1972. ];
  1973. }
  1974. }
  1975. foreach ($data as &$item) {
  1976. if (empty($item['物料分类'])) {
  1977. $item['物料分类'] = '';
  1978. }
  1979. // 去除所有非汉字字符
  1980. $item['物料分类'] = preg_replace('/[^\p{Han}]/u', '', $item['物料分类']);
  1981. }
  1982. // 批量插入BOM资料
  1983. if (!empty($data)) {
  1984. \db('工单_bom资料')->insertAll($data);
  1985. }
  1986. $this->success('成功',$order);
  1987. } else {
  1988. // 如果没有指定订单号,批量查询订单号并处理
  1989. $has_bom = \db('工单_bom资料')->alias('a')->field('a.BOM_工单编号')->group('a.BOM_工单编号')->select();
  1990. $all_orders = \db('工单_基本资料')->alias('a')->field('a.订单编号')->where('a.面料', '<>', '')->group('a.订单编号')->select();
  1991. // 提取有BOM资料的订单号
  1992. $has_bom_orders = array_column($has_bom, 'BOM_工单编号');
  1993. // 筛选出没有对应BOM资料的订单号
  1994. $no_bom_orders = array_filter($all_orders, function ($order) use ($has_bom_orders) {
  1995. return !in_array($order['订单编号'], $has_bom_orders);
  1996. });
  1997. // 遍历没有BOM资料的订单
  1998. foreach ($no_bom_orders as $orderData) {
  1999. // 获取该订单号的最大订单编号
  2000. $maxOrder = \db('工单_基本资料')
  2001. ->where('订单编号', 'like', "{$orderData['订单编号']}%")
  2002. ->order('订单编号', 'desc')
  2003. ->limit(1)
  2004. ->value('订单编号');
  2005. // 获取该订单号的具体数据
  2006. $list = \db('工单_基本资料')
  2007. ->where('订单编号', 'like', "{$orderData['订单编号']}%")
  2008. ->order('订单编号', 'desc')
  2009. ->limit(1)
  2010. ->find();
  2011. if (empty($list['面料'])) {
  2012. $this->error("订单 {$orderData['订单编号']} 面料数据为空,无法定义BOM");
  2013. }
  2014. // 处理订单编号
  2015. $numericPart = substr($maxOrder, 2);
  2016. $newNumericPart = str_pad((int)$numericPart + 1, strlen($numericPart), '0', STR_PAD_LEFT);
  2017. $param['订单编号'] = $order . $newNumericPart;
  2018. // // 处理物料信息
  2019. // $massage = empty($list['粘衬']) || $list['粘衬'] == '无' ? $list['面料'] : $list['面料'] . ',粘衬:' . $list['粘衬'];
  2020. // $mianliao = $this->Gpt($massage);
  2021. // // 插入物料数据
  2022. // $data = [];
  2023. // foreach ($mianliao as $key => $value) {
  2024. // if (!empty($value) && $value !== '粘衬') { // 排除空值和粘衬
  2025. // $data[] = [
  2026. // 'BOM_工单编号' => $list['订单编号'],
  2027. // 'BOM_物料名称' => $value,
  2028. // 'BOM_desc' => '',
  2029. // '物料分类' => '',
  2030. // 'Sys_rq' => date('Y-m-d H:i:s'),
  2031. // 'Sys_ID' => '超级管理员'
  2032. // ];
  2033. // }
  2034. // }
  2035. // 假设massage是从数据库获取的数据
  2036. $massage = empty($list['粘衬']) || $list['粘衬'] == '无' ? $list['面料'] : $list['面料'] . ',粘衬:' . $list['粘衬'];
  2037. $materialCategories = [];
  2038. $pattern = '/(\S+?):([^,]+)/'; // 匹配 类别:物料 格式
  2039. preg_match_all($pattern, $massage, $matches, PREG_SET_ORDER);
  2040. foreach ($matches as $match) {
  2041. $category = $match[1]; // 分类名称
  2042. $materials = explode('+', $match[2]); // 如果物料名称中有‘+’,则分开处理多个物料
  2043. // 将分类和对应的物料添加到数组中
  2044. foreach ($materials as $material) {
  2045. $materialCategories[$category][] = trim($material); // 去除物料两边的空格
  2046. }
  2047. }
  2048. $mianliao = $this->Gpt($massage);
  2049. $data = [];
  2050. foreach ($mianliao as $value) {
  2051. if (!empty($value) && $value !== '粘衬') { // 排除空值和粘衬
  2052. $category = '';
  2053. // 查找物料对应的分类
  2054. foreach ($materialCategories as $cat => $materials) {
  2055. if (in_array($value, $materials)) {
  2056. $category = $cat;
  2057. break;
  2058. }
  2059. }
  2060. // 如果找到分类,将数据存入BOM
  2061. $data[] = [
  2062. 'BOM_工单编号' => $list['订单编号'],
  2063. 'BOM_物料名称' => $value,
  2064. 'BOM_desc' => '',
  2065. '物料分类' => $category ? $category : '',
  2066. 'Sys_rq' => date('Y-m-d H:i:s'),
  2067. 'Sys_ID' => '超级管理员'
  2068. ];
  2069. }
  2070. }
  2071. foreach ($data as &$item) {
  2072. if (empty($item['物料分类'])) {
  2073. $item['物料分类'] = '';
  2074. }
  2075. // 去除所有非汉字字符
  2076. $item['物料分类'] = preg_replace('/[^\p{Han}]/u', '', $item['物料分类']);
  2077. }
  2078. // 批量插入BOM资料
  2079. if (!empty($data)) {
  2080. \db('工单_bom资料')->insertAll($data);
  2081. }
  2082. }
  2083. $this->success('成功');
  2084. }
  2085. }
  2086. /**
  2087. * 订单面料修改接口
  2088. */
  2089. public function FabricEdit()
  2090. {
  2091. if ($this->request->isPost() === false){
  2092. $this->error('请求错误');
  2093. }
  2094. $param = Request::instance()->post();
  2095. if (empty($param)){$this->error('请求错误');}
  2096. if(empty($param[0]['BOM_工单编号'])){$this->error('请求错误,请重新打开此页面');}
  2097. foreach ($param as $key => $value){
  2098. $data = $value;
  2099. unset($data['UNIQID']);
  2100. // 更新操作
  2101. if (!empty($value['UNIQID'])) {
  2102. // 查询旧数据
  2103. $oldData = \db('工单_bom资料')
  2104. ->where('UNIQID', $value['UNIQID'])
  2105. ->find();
  2106. // 日志记录逻辑
  2107. if ($oldData) {
  2108. foreach ($data as $field => $newValue) {
  2109. $oldValue = $oldData[$field] ?? null;
  2110. if ($oldValue != $newValue) {
  2111. $bom_sql = \db('工单_bom修改日志')
  2112. ->fetchSql(true)
  2113. ->insert([
  2114. '订单编号' => $oldData['BOM_工单编号'],
  2115. '字段' => $field,
  2116. '修改前数据' => $oldValue,
  2117. '修改后数据' => $newValue,
  2118. '修改人' => $param[0]['Sys_ID'],
  2119. '修改时间' => date('Y-m-d H:i:s'),
  2120. 'UNIQID' => $value['UNIQID'],
  2121. '物料名称' => $oldData['BOM_物料名称'],
  2122. ]);
  2123. $bom_res = \db()->query($bom_sql);
  2124. if ($bom_res === false) {
  2125. $this->error('日志写入失败');
  2126. }
  2127. }
  2128. }
  2129. }
  2130. $sql = \db('工单_bom资料')
  2131. ->where('UNIQID', $value['UNIQID'])
  2132. ->fetchSql(true)
  2133. ->update($data);
  2134. $res = \db()->query($sql);
  2135. }else {
  2136. $sql = \db('工单_bom资料')
  2137. ->fetchSql(true)
  2138. ->insert($value);
  2139. $res = \db()->query($sql);
  2140. }
  2141. if ($res === false){
  2142. $this->error('修改失败');
  2143. }
  2144. }
  2145. $orderList = \db('工单_基本资料')
  2146. ->field('订单编号, 生产款号, Sys_id')
  2147. ->where('订单编号', $param[0]['BOM_工单编号'])
  2148. ->find();
  2149. if (!$orderList) {
  2150. $this->error('工单基本资料未找到');
  2151. }
  2152. $colorList = \db('工单_印件资料')
  2153. ->field('颜色备注')
  2154. ->where('订单编号', $orderList['订单编号'])
  2155. ->group('颜色备注')
  2156. ->select();
  2157. $BomList = \db('工单_bom资料')
  2158. ->where('BOM_工单编号', $orderList['订单编号'])
  2159. ->whereNull('Mod_rq')
  2160. ->select();
  2161. if (!$BomList) {
  2162. $this->error('BOM 面料数据未找到');
  2163. }
  2164. $AssociatedNumber = \db('工单关联表')->order('关联编号 desc')->value('关联编号');
  2165. $number = empty($AssociatedNumber) ? 0 : (int)substr($AssociatedNumber, 4);
  2166. $MaterielList = [];
  2167. $MaterielLists = [];
  2168. $colorCounter = [];
  2169. foreach ($colorList as $color) {
  2170. $colorName = $color['颜色备注'];
  2171. $colorCounter[$colorName] = 1;
  2172. foreach ($BomList as $bom) {
  2173. $wulbm = $orderList['生产款号'] . '-' . $colorName . $colorCounter[$colorName]++;
  2174. $existsMateriel = \db('工单_面料资料')
  2175. ->where([
  2176. 'BOM_工单编号' => $orderList['订单编号'],
  2177. 'BOM_颜色' => $colorName,
  2178. 'BOM_物料名称' => $bom['BOM_物料名称']
  2179. ])
  2180. ->find();
  2181. if (!$existsMateriel) {
  2182. $MaterielList[] = [
  2183. 'BOM_工单编号' => $orderList['订单编号'],
  2184. 'BOM_颜色' => $colorName,
  2185. 'BOM_物料名称' => $bom['BOM_物料名称'],
  2186. 'BOM_标准用量' => $bom['BOM_标准用量'],
  2187. 'BOM_计划用量' => $bom['BOM_计划用量'],
  2188. 'BOM_计划门幅' => $bom['BOM_计划门幅'],
  2189. 'BOM_定额门幅' => $bom['BOM_定额门幅'],
  2190. 'BOM_投料单位' => $bom['BOM_投料单位'],
  2191. 'BOM_desc' => $bom['BOM_desc'],
  2192. 'BOM_物料编码' => $wulbm,
  2193. 'Sys_ID' => $bom['Sys_ID'],
  2194. 'Sys_rq' => date('Y-m-d H:i:s')
  2195. ];
  2196. }
  2197. $existsRelation = \db('工单关联表')
  2198. ->where([
  2199. '订单编号' => $orderList['订单编号'],
  2200. '颜色' => $colorName,
  2201. '物料名称' => $bom['BOM_物料名称']
  2202. ])
  2203. ->find();
  2204. if (!$existsRelation) {
  2205. $MaterielLists[] = [
  2206. '关联编号' => 'GDGL' . ($number + 1),
  2207. '订单编号' => $orderList['订单编号'],
  2208. '生产款号' => $orderList['生产款号'],
  2209. '颜色' => $colorName,
  2210. '物料编号' => $wulbm,
  2211. '物料名称' => $bom['BOM_物料名称'],
  2212. '备注' => $bom['BOM_desc'],
  2213. 'Sys_id' => $bom['Sys_ID'],
  2214. 'Sys_rq' => date('Y-m-d H:i:s')
  2215. ];
  2216. $number++;
  2217. }
  2218. }
  2219. }
  2220. if (!empty($MaterielList)) {
  2221. \db('工单_面料资料')->insertAll($MaterielList);
  2222. }
  2223. if (!empty($MaterielLists)) {
  2224. \db('工单关联表')->insertAll($MaterielLists);
  2225. }
  2226. $this->success('修改成功');
  2227. }
  2228. /**
  2229. * Bom资料操作日志左侧菜单
  2230. */
  2231. public function OrderBomLog()
  2232. {
  2233. $list = \db('工单_bom修改日志')
  2234. ->field('修改时间')
  2235. ->group('修改时间')
  2236. ->select();
  2237. $result = [];
  2238. foreach ($list as $item) {
  2239. $dateTime = $item['修改时间'];
  2240. $dateOnly = date('Y-m-d', strtotime($dateTime)); // 提取日期
  2241. $year = date('Y', strtotime($dateTime));
  2242. // 加上(int)date('m', strtotime($sys_rq))转成数字去掉前导 01 => 1
  2243. $month = date('m', strtotime($dateTime));
  2244. // 初始化结构
  2245. if (!isset($result[$year])) {
  2246. $result[$year] = [];
  2247. }
  2248. if (!isset($result[$year][$month])) {
  2249. $result[$year][$month] = [];
  2250. }
  2251. // 避免重复添加相同日期
  2252. if (!in_array($dateOnly, $result[$year][$month])) {
  2253. $result[$year][$month][] = $dateOnly;
  2254. }
  2255. }
  2256. // 按年月日进行倒序排序
  2257. foreach ($result as $year => &$months) {
  2258. krsort($months); // 月份倒序
  2259. foreach ($months as &$dates) {
  2260. rsort($dates); // 日期倒序
  2261. }
  2262. }
  2263. $this->success('成功', $result);
  2264. }
  2265. /**
  2266. * Bom资料操作变更日志记录查询
  2267. */
  2268. public function GetBomEditLog(){
  2269. $param = $this->request->param();
  2270. if (empty($param)){
  2271. $this->error('参数错误');
  2272. }
  2273. $sys_rq = $param['sys_rq'];
  2274. $where= [];
  2275. if (isset($param['search'])) {
  2276. $where['物料名称|订单编号'] = ['like', $param['search'] . '%'];
  2277. }
  2278. // 日期筛选
  2279. if ($sys_rq !== '') {
  2280. $where['修改时间'] = ['like', '%' . $sys_rq . '%'];
  2281. }
  2282. $page = isset($param['page']) ? (int)$param['page'] : 1;
  2283. $limit = isset($param['limit']) ? (int)$param['limit'] : 50;
  2284. $list = \db('工单_bom修改日志')
  2285. ->where($where)
  2286. ->order('修改时间 desc')
  2287. ->limit(($page-1)*$limit,$limit)
  2288. ->select();
  2289. $count = \db('工单_bom修改日志')
  2290. ->where($where)
  2291. ->count();
  2292. $data = [
  2293. 'total' => $count,
  2294. 'list' => $list
  2295. ];
  2296. $this->success('成功', $data);
  2297. }
  2298. /**
  2299. * 入库、出库、退还详情数据
  2300. */
  2301. public function FabricDetaillist()
  2302. {
  2303. if ($this->request->isGet() === false){
  2304. $this->error('请求错误');
  2305. }
  2306. $param = $this->request->param();
  2307. $where = [];
  2308. if (isset($param['order']) && !empty($param['order'])){
  2309. $where['a.order_id'] = $param['order'];
  2310. }
  2311. if (isset($param['lotNumber']) && !empty($param['lotNumber'])){
  2312. $where['a.批次号'] = $param['lotNumber'];
  2313. }
  2314. // 定义查询字段
  2315. $fields = '
  2316. a.id,
  2317. a.receipt_number as 单号,
  2318. a.批次号,
  2319. a.order_id as 订单编号,
  2320. a.客户编号,
  2321. a.款号 as 生产款号,
  2322. a.款式,
  2323. a.物料名称,
  2324. c.BOM_颜色 as 颜色,
  2325. d.BOM_计划用量 as 计划用料,
  2326. d.BOM_计划门幅 as 计划门幅,
  2327. d.BOM_标准用量 as 定额用料,
  2328. d.BOM_定额门幅 as 定额门幅,
  2329. b.单位 as 投料单位,
  2330. d.BOM_desc as 备注,
  2331. b.入仓总量 as 入仓总量,
  2332. b.库存数量 as 面料结余,
  2333. a.departname as 来料部门,
  2334. a.rq as 操作时间,
  2335. a.sys_id as 操作人员
  2336. ';
  2337. $list['入库记录'] = \db('库存_出入库明细')
  2338. ->alias('a')
  2339. ->join('物料_库存 b', 'a.批次号 = b.批次号 AND a.物料编码 = b.物料编号', 'left')
  2340. ->join('工单_面料资料 c','a.order_id = c.BOM_工单编号 AND a.物料编码 = c.BOM_物料编码','left')
  2341. ->join('工单_bom资料 d','a.order_id = d.BOM_工单编号 AND a.物料名称 = d.BOM_物料名称','left')
  2342. ->where($where)
  2343. ->where('a.name', '入库')
  2344. ->field($fields)
  2345. ->field('a.number as 入库数量')
  2346. ->order('a.rq desc')
  2347. ->whereNull('a.Mod_rq')
  2348. ->select();
  2349. //出库记录查询
  2350. $list['出库记录'] = \db('库存_出入库明细')->alias('a')
  2351. ->join('物料_库存 b', 'a.批次号 = b.批次号 AND a.物料编码 = b.物料编号', 'left')
  2352. ->join('工单_面料资料 c','a.order_id = c.BOM_工单编号 AND a.物料编码 = c.BOM_物料编码','left')
  2353. ->join('工单_bom资料 d','a.order_id = d.BOM_工单编号 AND a.物料名称 = d.BOM_物料名称','left')
  2354. ->where($where)
  2355. ->where('a.name', '出库')
  2356. ->field($fields)
  2357. ->field('b.领用数量 as 领用数量,a.number as 出库数量')
  2358. ->order('a.rq desc')
  2359. ->whereNull('a.Mod_rq')
  2360. ->select();
  2361. //退还记录查询
  2362. $list['退还记录'] = \db('库存_出入库明细')->alias('a')
  2363. ->join('物料_库存 b', 'a.批次号 = b.批次号 AND a.物料编码 = b.物料编号', 'left')
  2364. ->join('工单_面料资料 c','a.order_id = c.BOM_工单编号 AND a.物料编码 = c.BOM_物料编码','left')
  2365. ->join('工单_bom资料 d','a.order_id = d.BOM_工单编号 AND a.物料名称 = d.BOM_物料名称','left')
  2366. ->where($where)
  2367. ->where('a.name', '退还')
  2368. ->field($fields)
  2369. ->field('a.type as 退还类型,a.number as 退还数量')
  2370. ->order('a.rq desc')
  2371. ->whereNull('a.Mod_rq')
  2372. ->select();
  2373. $this->success('成功',$list);
  2374. }
  2375. /**
  2376. * 入库、出库、退还删除
  2377. */
  2378. public function FabricDetaildel()
  2379. {
  2380. if ($this->request->isPost() === false) {
  2381. $this->error('请求错误');
  2382. }
  2383. $param = $this->request->param();
  2384. if (empty($param) || !isset($param['id'])) {
  2385. $this->error('请求参数错误');
  2386. }
  2387. $id = $param['id'];
  2388. $where = [
  2389. 'Mod_id' => $param['Mod_id'],
  2390. 'Mod_rq' => date('Y-m-d H:i:s')
  2391. ];
  2392. // 获取出入库记录
  2393. $res = db('库存_出入库明细')->where('id', $id)->find();
  2394. if (!$res) {
  2395. $this->error('ID: ' . $id . ' 的出入库记录不存在');
  2396. }
  2397. // 获取库存信息
  2398. $res_list = db('物料_库存')->where('批次号', $res['批次号'])->find();
  2399. if (!$res_list) {
  2400. $this->error('批次号 ' . $res['批次号'] . ' 的库存记录不存在');
  2401. }
  2402. $updateData = [];
  2403. // 根据出入库类型处理逻辑
  2404. switch ($res['name']) {
  2405. case '入库':
  2406. $updateData['入仓总量'] = $res_list['入仓总量'] - $res['number'];
  2407. $updateData['库存数量'] = $res_list['库存数量'] - $res['number'];
  2408. break;
  2409. case '出库':
  2410. $updateData['领用数量'] = $res_list['领用数量'] - $res['number'];
  2411. $updateData['库存数量'] = $res_list['库存数量'] + $res['number'];
  2412. break;
  2413. case '退还':
  2414. if ($res['type'] == '退仓') {
  2415. $updateData['退还数量'] = $res_list['退还数量'] - $res['number'];
  2416. $updateData['库存数量'] = $res_list['库存数量'] + $res['number'];
  2417. }
  2418. if ($res['type'] == '退客户') {
  2419. $updateData['退还数量'] = $res_list['退还数量'] - $res['number'];
  2420. $updateData['库存数量'] = $res_list['库存数量'] + $res['number'];
  2421. }
  2422. break;
  2423. default:
  2424. $this->error('未知的出入库类型: ' . $res['name']);
  2425. }
  2426. // 安全性校验(防止负数)
  2427. foreach ($updateData as $field => $value) {
  2428. if ($value < 0) {
  2429. $this->error('删除失败,' . $field . ' 更新后为负数');
  2430. }
  2431. }
  2432. // 更新库存表
  2433. $updateResult = db('物料_库存')
  2434. ->where('批次号', $res['批次号'])
  2435. ->fetchSql(true)
  2436. ->update($updateData);
  2437. \db()->query($updateResult);
  2438. if ($updateResult === false) {
  2439. throw new \Exception('更新库存表失败');
  2440. }
  2441. // 更新出入库明细表(软删除)
  2442. $deleteResult = db('库存_出入库明细')
  2443. ->where('id', $id)
  2444. ->fetchSql(true)
  2445. ->update($where);
  2446. \db()->query($deleteResult);
  2447. if ($deleteResult === false) {
  2448. throw new \Exception('更新出入库明细表失败');
  2449. }
  2450. $this->success('删除成功');
  2451. }
  2452. public function Gpt($massage)
  2453. {
  2454. // $apiKey = 'sk-e0JuPjMntkbgi1BoMjrqyyzMKzAxILkQzyGMSy3xiMupuoWY';
  2455. // $apiKey = 'sk-Bhos1lXTRpZiAAmN06624a219a874eCd91Dc068b902a3e73';
  2456. $apiKey = 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss';
  2457. $messages = [
  2458. [
  2459. 'role' => 'user',
  2460. 'content' => '你好,帮我按照:面料1、面料2、面料3……来整理归纳下面的面料信息,我只需要面料信息,不需要其他:'.$massage
  2461. ]
  2462. ];
  2463. $data = [
  2464. 'model' => 'gpt-4',
  2465. 'messages' => $messages,
  2466. 'max_tokens' => 1024,
  2467. 'temperature' => 0.7,
  2468. ];
  2469. // 初始化 cURL 请求
  2470. // $ch = curl_init('https://niubi.zeabur.app/v1/chat/completions');
  2471. // $ch = curl_init('https://one.opengptgod.com/v1/chat/completions');
  2472. $ch = curl_init('https://chatapi.onechats.top/v1/chat/completions');
  2473. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2474. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  2475. 'Content-Type: application/json',
  2476. 'Authorization: Bearer ' . $apiKey,
  2477. ]);
  2478. curl_setopt($ch, CURLOPT_POST, true);
  2479. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  2480. // 跳过证书检查可暂时避免 pem 文件配置失败(测试用)
  2481. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2482. // 执行请求
  2483. $response = curl_exec($ch);
  2484. // 错误处理
  2485. if (curl_errno($ch)) {
  2486. return '请求失败: ' . curl_error($ch);
  2487. }
  2488. curl_close($ch);
  2489. // 解析响应
  2490. $responseData = json_decode($response, true);
  2491. if (isset($responseData['choices'][0]['message']['content'])) {
  2492. $gptReply = $responseData['choices'][0]['message']['content'];
  2493. // 使用正则提取“面料X:XXX”的内容
  2494. preg_match_all('/面料\d+[::](.+)/u', $gptReply, $matches);
  2495. return $matches[1] ?? [];
  2496. } else {
  2497. return '未能获取 GPT 回复';
  2498. }
  2499. }
  2500. /**
  2501. * 面料库存月份查询
  2502. */
  2503. public function fabricListmonth()
  2504. {
  2505. $data = \db('库存_出入库明细')
  2506. ->whereNull('Mod_rq')
  2507. ->field('DISTINCT DATE_FORMAT(rq, "%Y-%m") as month, DATE_FORMAT(rq, "%Y-%m-%d") as date')
  2508. ->whereNull('Mod_rq')
  2509. ->order('rq desc')
  2510. ->select();
  2511. // 按月份分组数据
  2512. $groupedData = [];
  2513. foreach ($data as $entry) {
  2514. $groupedData[$entry['month']][] = $entry['date'];
  2515. }
  2516. // 去重处理,防止重复
  2517. foreach ($groupedData as $month => $dates) {
  2518. $groupedData[$month] = array_values(array_unique($dates));
  2519. }
  2520. $this->success('成功', $groupedData);
  2521. }
  2522. /**
  2523. * 获取每月的面料记录\库存_出入库明细
  2524. * 入库出库退还日期
  2525. */
  2526. public function fetchMonthlyFabricRecords() {
  2527. $types = ['入库', '出库', '退还'];
  2528. $list = [];
  2529. foreach ($types as $type) {
  2530. $data = \db('库存_出入库明细')
  2531. ->where('name', $type)
  2532. ->whereNull('Mod_rq')
  2533. ->field('DISTINCT DATE_FORMAT(rq, "%Y-%m") as month, DATE_FORMAT(rq, "%Y-%m-%d") as date')
  2534. ->order('rq desc')
  2535. ->select();
  2536. // 按照月份分组数据
  2537. $groupedData = [];
  2538. foreach ($data as $entry) {
  2539. $groupedData[$entry['month']][] = $entry['date'];
  2540. }
  2541. // 进一步去重,避免意外重复
  2542. foreach ($groupedData as $month => $dates) {
  2543. $groupedData[$month] = array_values(array_unique($dates));
  2544. }
  2545. // 添加到返回列表
  2546. $list[$type] = $groupedData;
  2547. }
  2548. $this->success('成功', $list);
  2549. }
  2550. /**
  2551. * 面料库存列表
  2552. */
  2553. public function fabricList()
  2554. {
  2555. if ($this->request->isGet() === false) {
  2556. $this->error('请求错误');
  2557. }
  2558. $param = $this->request->param();
  2559. $where = [];
  2560. // 根据传入的参数构造查询条件
  2561. if (isset($param['order'])) {
  2562. $where['b.BOM_工单编号|a.生产款号|b.BOM_物料名称'] = ['like', $param['order'] . '%'];
  2563. }
  2564. if (isset($param['mouth'])) {
  2565. $where['a.Sys_rq'] = ['like', $param['mouth'] . '%'];
  2566. }
  2567. // 分页参数,防止未传递时出错
  2568. $page = isset($param['page']) ? (int)$param['page'] : 1; // 默认第1页
  2569. $limit = isset($param['limit']) ? (int)$param['limit'] : 50; // 默认每页50条
  2570. $excludeOrder = $param['order'];
  2571. // 获取其他订单中相同物料名称的订单编号组合
  2572. $subQuery = \db('工单关联表')
  2573. ->field("物料名称, GROUP_CONCAT(DISTINCT 订单编号 SEPARATOR ',') as 关联订单")
  2574. ->where('订单编号', '<>', $excludeOrder)
  2575. ->group('物料名称')
  2576. ->buildSql();
  2577. $data = \db('工单_基本资料')->alias('a')
  2578. ->field('
  2579. b.BOM_工单编号 as 订单编号,
  2580. a.生产款号,
  2581. a.款式,
  2582. b.BOM_颜色 as 颜色,
  2583. b.BOM_物料编码 as 物料编码,
  2584. b.BOM_物料名称 as 物料名称,
  2585. b.Sys_ID,
  2586. b.Sys_rq,
  2587. c.单位,
  2588. c.入仓总量,
  2589. c.库存数量,
  2590. c.领用数量,
  2591. d.BOM_desc as 备注,
  2592. d.BOM_标准用量 as 定额用料,
  2593. d.BOM_定额门幅 as 定额门幅,
  2594. e.批次号,f.关联订单
  2595. ')
  2596. ->join('工单_面料资料 b', 'a.订单编号 = b.BOM_工单编号')
  2597. ->join('库存_出入库明细 e', 'a.订单编号 = e.order_id')
  2598. ->join('物料_库存 c', 'b.BOM_物料编码 = c.物料编号 AND b.BOM_物料名称 = c.物料名称 AND e.批次号 = c.批次号')
  2599. ->join('工单_bom资料 d', 'a.订单编号 = d.BOM_工单编号 AND b.BOM_物料名称 = d.BOM_物料名称')
  2600. ->join([$subQuery => 'f'], 'f.物料名称 = d.BOM_物料名称','LEFT')
  2601. ->whereNull('a.Mod_rq')
  2602. ->whereNull('b.Mod_rq')
  2603. ->whereNull('c.Mod_rq')
  2604. ->whereNull('d.Mod_rq')
  2605. ->whereNull('e.Mod_rq')
  2606. ->group('e.批次号, b.BOM_物料编码')
  2607. ->where($where)
  2608. ->select();
  2609. // 统计条数进行分页
  2610. $count = \db('工单_面料资料')->where('BOM_工单编号',$param['order'])->count();
  2611. // 确保返回的格式固定
  2612. $list = [
  2613. 'total' => $count,
  2614. 'table' => $data ?: []
  2615. ];
  2616. $this->success('成功', $list);
  2617. }
  2618. /**
  2619. * 单条面料详情
  2620. */
  2621. public function oneFabricDetail()
  2622. {
  2623. if ($this->request->isGet() === false){
  2624. $this->error('请求错误');
  2625. }
  2626. $param = $this->request->param();
  2627. if (empty($param)){
  2628. $this->error('参数错误');
  2629. }
  2630. //面料入库记录
  2631. $list['入库'] = \db('库存_出入库明细')
  2632. ->where('',$param['order'])
  2633. ->where('物料名称',$param['fabricName'])
  2634. ->where('name','入库')
  2635. ->where('Mod_rq',null)
  2636. ->field('order_id as 订单编号,款号,物料编码,物料名称,number as 数量,rq as 日期,sys_id as 操作机台,recipient as 入仓人员')
  2637. ->select();
  2638. //面料出库记录
  2639. $list['出库'] = \db('库存_出入库明细')
  2640. ->where('order_id',$param['order'])
  2641. ->where('物料名称',$param['fabricName'])
  2642. ->where('name','出库')
  2643. ->where('Mod_rq',null)
  2644. ->field('order_id as 订单编号,款号,物料名称,number as 数量,rq as 日期,sys_id as 操作机台,receipt_number as 出库单据编号,recipient as 领用人员')
  2645. ->select();
  2646. //面料退还记录
  2647. $list['退还'] = \db('库存_出入库明细')
  2648. ->where('order_id',$param['order'])
  2649. ->where('物料名称',$param['fabricName'])
  2650. ->where('name','退还')
  2651. ->where('Mod_rq',null)
  2652. ->field('order_id as 订单编号,款号,物料名称,number as 数量,rq as 日期,sys_id as 操作机台,recipient as 退还人员')
  2653. ->select();
  2654. $this->success('成功',$list);
  2655. }
  2656. /**
  2657. * 单据号查询数据
  2658. * @return void
  2659. * @throws \think\db\exception\DataNotFoundException
  2660. * @throws \think\db\exception\ModelNotFoundException
  2661. * @throws \think\exception\DbException
  2662. */
  2663. public function ReceiptDetail()
  2664. {
  2665. if ($this->request->isGet() === false){
  2666. $this->error('请求错误');
  2667. }
  2668. $param = $this->request->param();
  2669. if (empty($param)){
  2670. $this->error('单据编号参数错误');
  2671. }
  2672. $list = \db('库存_出入库明细')
  2673. ->alias('a')
  2674. ->join('工单_面料资料 b','a.order_id = b.BOM_工单编号 AND b.BOM_物料编码 = a.物料编码')
  2675. ->join('物料_库存 c','a.物料编码 = c.物料编号 AND a.批次号 = c.批次号')
  2676. ->where('a.receipt_number',$param['receipt'])
  2677. ->field('a.id,a.order_id as 订单编号,a.款号,a.物料名称,a.number as 数量,a.rq as 日期,a.sys_rq as 创建日期,a.sys_id as 操作机台,
  2678. a.departname,a.remark,a.type as 退还类型,
  2679. a.receipt_number as 出库单据编号,a.recipient as 领用人员,b.BOM_颜色,c.单位,
  2680. b.BOM_计划用量 as 计划用料,
  2681. b.BOM_计划门幅 as 计划门幅,
  2682. b.BOM_标准用量 as 定额用料,
  2683. b.BOM_定额门幅 as 定额门幅,
  2684. c.实际门幅,c.状态,c.库存数量,c.入仓总量
  2685. ')
  2686. ->whereNull('a.Mod_rq')
  2687. ->whereNull('b.Mod_rq')
  2688. ->whereNull('c.Mod_rq')
  2689. ->select();
  2690. if (empty($list)){
  2691. $this->error('未找到该出库单');
  2692. }else{
  2693. $this->success('成功',$list);
  2694. }
  2695. }
  2696. /**
  2697. * 入库、出库、退还单号列表
  2698. */
  2699. public function ReceiptList(){
  2700. if ($this->request->isGet() === false){
  2701. $this->error('请求错误');
  2702. }
  2703. $param = $this->request->param();
  2704. if (empty($param)){
  2705. $this->error('参数错误');
  2706. }
  2707. $where= [];
  2708. if (isset($param['search'])) {
  2709. $where['物料名称|款号|order_id|receipt_number|款式|物料编码'] = ['like', $param['search'] . '%'];
  2710. }
  2711. if (isset($param['mouth'])) {
  2712. $where['rq'] = ['like', $param['mouth'] . '%'];
  2713. }
  2714. $page = isset($param['page']) ? (int)$param['page'] : 1; // 默认第1页
  2715. $limit = isset($param['limit']) ? (int)$param['limit'] : 50; // 默认每页50条
  2716. $list = \db('库存_出入库明细')
  2717. ->where('Mod_rq', null)
  2718. ->where($where)
  2719. ->where('name',$param['code'])
  2720. ->order('sys_rq desc')
  2721. ->limit(($page-1)*$limit,$limit)
  2722. ->select();
  2723. // 初始化一个合并后的数组
  2724. $merged = [];
  2725. foreach ($list as $item) {
  2726. $key = $item['receipt_number'];
  2727. if (!isset($merged[$key])) {
  2728. // 首次出现,初始化
  2729. $merged[$key] = [
  2730. '单号类型' => $item['name'],
  2731. '出库单' => $item['receipt_number'],
  2732. '订单编号' => $item['order_id'],
  2733. '款号' => $item['款号'],
  2734. '款式' => $item['款式'],
  2735. '物料编码' => $item['物料编码'],
  2736. '物料名称' => $item['物料名称'],
  2737. '总数' => floatval($item['number']),
  2738. '日期' => $item['rq'],
  2739. '创建日期' => $item['sys_rq'],
  2740. '操作机台' => $item['sys_id'],
  2741. '领料人员' => $item['recipient'],
  2742. ];
  2743. } else {
  2744. // 合并相同 receipt_number 的记录
  2745. $merged[$key]['订单编号'] .= ',' . $item['order_id'];
  2746. $merged[$key]['款号'] .= ',' . $item['款号'];
  2747. $merged[$key]['款式'] .= ',' . $item['款式'];
  2748. $merged[$key]['物料编码'] .= ',' . $item['物料编码'];
  2749. $merged[$key]['物料名称'] .= ',' . $item['物料名称'];
  2750. $merged[$key]['总数'] += floatval($item['number']);
  2751. }
  2752. }
  2753. // 对需要的字段进行逗号分隔后的去重
  2754. foreach ($merged as &$item) {
  2755. $item['订单编号'] = implode(',', array_unique(explode(',', $item['订单编号'])));
  2756. $item['款号'] = implode(',', array_unique(explode(',', $item['款号'])));
  2757. $item['款式'] = implode(',', array_unique(explode(',', $item['款式'])));
  2758. $item['物料编码'] = implode(',', array_unique(explode(',', $item['物料编码'])));
  2759. $item['物料名称'] = implode(',', array_unique(explode(',', $item['物料名称'])));
  2760. // 格式化总数
  2761. $item['总数'] = round($item['总数'], 2); // 保留2位小数,防止长尾
  2762. }
  2763. unset($item); // 避免引用问题
  2764. //统计数量
  2765. $count = \db('库存_出入库明细')
  2766. ->where($where)
  2767. ->where('name',$param['code'])
  2768. ->field('receipt_number as 出库单')
  2769. ->group('出库单')
  2770. ->where('Mod_rq',null)
  2771. ->order('rq desc')
  2772. ->select();
  2773. if (empty($merged)){
  2774. $this->success('未找到数据', '');
  2775. } else {
  2776. $data['total'] = count($count);
  2777. $data['table'] = array_values($merged);
  2778. $this->success('成功', $data);
  2779. }
  2780. }
  2781. /**
  2782. * 出库单左侧菜单
  2783. */
  2784. public function getReceiptTab()
  2785. {
  2786. if ($this->request->isGet() === false){
  2787. $this->error('请求错误');
  2788. }
  2789. $list = \db('库存_出入库明细')
  2790. ->field([
  2791. "DATE_FORMAT(rq, '%Y-%m') AS month",
  2792. ])
  2793. ->group('month')
  2794. ->order('month DESC')
  2795. ->select();
  2796. if (empty($list)){
  2797. $this->error('未查询到入库、出库、退还数据');
  2798. }else{
  2799. $this->success('成功',$list);
  2800. }
  2801. }
  2802. /**
  2803. * 获取入库单号、出库单号
  2804. * @return void
  2805. */
  2806. public function gitReceiptNumber()
  2807. {
  2808. if ($this->request->isGet() === false) {
  2809. $this->error('请求错误');
  2810. }
  2811. $param = $this->request->param();
  2812. if (empty($param)) {
  2813. $this->error('参数错误');
  2814. }
  2815. // 获取最新单号(按日期和序号排序)
  2816. $lastNumber = \db('库存_出入库明细')
  2817. ->where('receipt_number', 'like', $param['number'] . date('Ymd') . '-%')
  2818. ->order('receipt_number desc')
  2819. ->whereNull('Mod_rq')
  2820. ->limit(1)
  2821. ->value('receipt_number');
  2822. if (empty($lastNumber)) {
  2823. $num = 1;
  2824. } else {
  2825. // 提取最后3位并转为整数
  2826. $lastSeq = substr($lastNumber, -3);
  2827. $num = (int)$lastSeq + 1;
  2828. }
  2829. // 格式化为3位数字(001, 010, 100, 101...)
  2830. $seq = str_pad($num, 3, '0', STR_PAD_LEFT);
  2831. // 生成完整单号(如 BG20240615-101)
  2832. $number = $param['number'] . date('Ymd') . '-' . $seq;
  2833. // 获取最新出库人员
  2834. $lastUser = \db('库存_出入库明细')
  2835. ->where('name', '出库')
  2836. ->order('recipient desc')
  2837. ->group('recipient')
  2838. ->whereNull('Mod_rq')
  2839. ->limit(1)
  2840. ->value('recipient');
  2841. $data = [
  2842. 'number' => $number,
  2843. 'username' => $lastUser
  2844. ];
  2845. $this->success('成功', $data);
  2846. }
  2847. /**
  2848. * 面料批次列表
  2849. */
  2850. public function FabricLotList()
  2851. {
  2852. if ($this->request->isGet() === false){
  2853. $this->error('请求错误');
  2854. }
  2855. $param = $this->request->param();
  2856. if (empty($param)){
  2857. $this->error('参数错误');
  2858. }
  2859. $where= [];
  2860. if (isset($param['search'])) {
  2861. $where['c.物料编号|c.物料名称|a.生产款号|a.订单编号|b.BOM_颜色'] = ['like', '%' . $param['search'] . '%'];
  2862. }
  2863. if (isset($param['date'])) {
  2864. $where['e.rq'] = ['like', $param['date'] . '%'];
  2865. }
  2866. $subQuery = \db('工单关联表')
  2867. ->field("物料名称, GROUP_CONCAT(DISTINCT 订单编号 SEPARATOR ',') as 关联订单")
  2868. ->group('物料名称')
  2869. ->buildSql();
  2870. $list = \db('工单_基本资料')->alias('a')
  2871. ->field('
  2872. c.批次号,
  2873. c.关联号,
  2874. c.物料编号,
  2875. c.物料名称,
  2876. c.入仓总量,
  2877. c.库存数量,
  2878. c.领用数量,
  2879. c.退还数量 as 裁切退还,
  2880. c.单位,
  2881. c.实际门幅,
  2882. c.状态,
  2883. e.sys_id as 入仓人员,
  2884. e.sys_rq as 入仓日期,
  2885. b.BOM_颜色 as 颜色,
  2886. a.生产款号 as 款号,
  2887. d.BOM_计划用量 as 计划用料,
  2888. d.BOM_标准用量 as 定额用料,
  2889. d.BOM_计划门幅 as 计划门幅,
  2890. d.BOM_定额门幅 as 定额门幅,
  2891. f.关联订单
  2892. ')
  2893. ->join('工单_面料资料 b', 'a.订单编号 = b.BOM_工单编号')
  2894. ->join('库存_出入库明细 e', 'a.订单编号 = e.order_id')
  2895. ->join('物料_库存 c', 'b.BOM_物料编码 = c.物料编号 AND b.BOM_物料名称 = c.物料名称 AND e.批次号 = c.批次号')
  2896. ->join('工单_bom资料 d', 'a.订单编号 = d.BOM_工单编号 AND b.BOM_物料名称 = d.BOM_物料名称')
  2897. ->join([$subQuery => 'f'], 'f.物料名称 = d.BOM_物料名称')
  2898. ->whereNull('a.Mod_rq')
  2899. // ->whereNull('b.Mod_rq')
  2900. ->whereNull('c.Mod_rq')
  2901. // ->whereNull('d.Mod_rq')
  2902. ->whereNull('e.Mod_rq')
  2903. ->group('c.物料编号')
  2904. ->where($where)
  2905. ->select();
  2906. if (empty($list)){
  2907. $this->error('未找到面料数据');
  2908. }else{
  2909. $this->success('成功',$list);
  2910. }
  2911. }
  2912. public function SubOrderProgress()
  2913. {
  2914. if (!$this->request->isGet()) {
  2915. $this->error('请求错误');
  2916. }
  2917. $params = $this->request->param();
  2918. if (empty($params['order'])) {
  2919. $this->error('缺少订单编号');
  2920. }
  2921. $orderNo = $params['order'];
  2922. // ▶ 获取该主订单下的全部子订单(印件资料为主)
  2923. $styleData = Db::name('工单_印件资料')
  2924. ->where('订单编号', $orderNo)
  2925. ->field('子订单编号, 款号, 颜色, 颜色备注')
  2926. ->whereNull('Mod_rq')
  2927. ->select();
  2928. if (empty($styleData)) {
  2929. $this->success('未找到子订单资料', ['result' => [], 'list' => []]);
  2930. }
  2931. $subOrderNos = array_column($styleData, '子订单编号');
  2932. // 子订单 → 款号/颜色
  2933. $styleMap = [];
  2934. foreach ($styleData as $row) {
  2935. $styleMap[$row['子订单编号']] = [
  2936. '款号' => $row['款号'],
  2937. '颜色' => $row['颜色'],
  2938. '颜色备注' => $row['颜色备注'],
  2939. ];
  2940. }
  2941. // ▶ 入仓数量统计
  2942. $warehouseData = Db::name('成品入仓')
  2943. ->alias('a')
  2944. ->field('a.order_id as 子订单编号, SUM(a.sl) as 入仓数量')
  2945. ->where('a.order', $orderNo)
  2946. ->whereNull('a.mod_rq')
  2947. ->group('a.order_id')
  2948. ->select();
  2949. $warehouseMap = [];
  2950. foreach ($warehouseData as $row) {
  2951. $warehouseMap[$row['子订单编号']] = (int)$row['入仓数量'];
  2952. }
  2953. // ▶ 裁剪数量统计
  2954. $prodData = Db::name('设备_产量计酬')
  2955. ->field('子订单编号, SUM(数量) as 裁剪数量')
  2956. ->whereIn('子订单编号', $subOrderNos)
  2957. ->where('工序名称', '裁剪')
  2958. ->group('子订单编号')
  2959. ->select();
  2960. $cutMap = [];
  2961. foreach ($prodData as $row) {
  2962. $cutMap[$row['子订单编号']] = (int)$row['裁剪数量'];
  2963. }
  2964. // ▶ 合并结果(子订单明细)
  2965. $result = [];
  2966. $totalCut = 0;
  2967. $totalIn = 0;
  2968. foreach ($subOrderNos as $subOrderNo) {
  2969. $inQty = $warehouseMap[$subOrderNo] ?? 0;
  2970. $cutQty = $cutMap[$subOrderNo] ?? 0;
  2971. $rate = $cutQty > 0 ? round($inQty / $cutQty * 100, 2) . '%' : '0%';
  2972. $styleInfo = $styleMap[$subOrderNo] ?? ['款号'=>'','颜色'=>'','颜色备注'=>''];
  2973. $result[] = [
  2974. '子订单编号' => $subOrderNo,
  2975. '生产款号' => $styleInfo['款号'],
  2976. '颜色' => $styleInfo['颜色'],
  2977. '颜色备注' => $styleInfo['颜色备注'],
  2978. '裁剪数量' => $cutQty,
  2979. '入仓数量' => $inQty,
  2980. '完成率' => $rate,
  2981. ];
  2982. $totalCut += $cutQty;
  2983. $totalIn += $inQty;
  2984. }
  2985. // ▶ 汇总 list 字段(整张订单)
  2986. $list = [[
  2987. '订单编号' => $orderNo,
  2988. '订单总裁剪数量' => $totalCut,
  2989. '订单总入仓数量' => $totalIn,
  2990. '订单完成率' => $totalCut > 0 ? round($totalIn / $totalCut * 100, 2) . '%' : '0%'
  2991. ]];
  2992. // ▶ 返回数据
  2993. $this->success('请求成功', [
  2994. 'result' => $result,
  2995. 'list' => $list
  2996. ]);
  2997. }
  2998. /**
  2999. * 仓库管理
  3000. * 入库、出库、退还更新
  3001. */
  3002. public function rApictedit()
  3003. {
  3004. if (!$this->request->isPost()) {
  3005. $this->error('请求错误');
  3006. }
  3007. $param = Request::instance()->post();
  3008. if (empty($param)) {
  3009. $this->error('参数错误');
  3010. }
  3011. $logData = []; // 日志记录数组
  3012. $now = date('Y-m-d H:i:s');
  3013. foreach ($param as $item) {
  3014. $id = $item['id'];
  3015. $newQty = floatval($item['数量'] ?? 0);
  3016. $name = $item['name'];
  3017. $returnType = $item['退还类型'];
  3018. $sysId = $item['sys_id'];
  3019. $rq = $item['rq'];
  3020. $remark = $item['remark'];
  3021. if (!$id || !$name) {
  3022. $this->error('缺少必要参数');
  3023. }
  3024. // 获取库存_出入库明细 原记录
  3025. $record = \db('库存_出入库明细')
  3026. ->field('id, 批次号, number, type')
  3027. ->where('name', $name)
  3028. ->whereNull('Mod_rq')
  3029. ->where('id', $id)
  3030. ->find();
  3031. if (!$record) {
  3032. $this->error("未找到 ID 为 {$id} 的记录");
  3033. }
  3034. $batchNo = $record['批次号'];
  3035. $oldQty = floatval($record['number']);
  3036. $diff = $newQty - $oldQty;
  3037. //修改库存_出入库明细
  3038. $updateSql = \db('库存_出入库明细')
  3039. ->where('id', $id)
  3040. ->where('name', $name)
  3041. ->whereNull('Mod_rq')
  3042. ->fetchSql(true)
  3043. ->update(
  3044. [
  3045. 'number' => $newQty,
  3046. 'remark' => $remark,
  3047. 'rq' => $rq
  3048. ]
  3049. );
  3050. \db()->query($updateSql); // 执行 SQL
  3051. // 写入日志,增加 ids 字段
  3052. $logData[] = [
  3053. '批次号' => $batchNo,
  3054. '操作字段' => 'number',
  3055. '原值' => $oldQty,
  3056. '新值' => $newQty,
  3057. '操作人' => $sysId,
  3058. '操作类型' => $name,
  3059. '操作时间' => $now,
  3060. '修改表' => '库存_出入库明细',
  3061. 'ids' => $id
  3062. ];
  3063. // === 获取同批次的记录以统计新合计 ===
  3064. $sameBatchList = \db('库存_出入库明细')
  3065. ->field('number')
  3066. ->where('name', $name)
  3067. ->whereNull('Mod_rq')
  3068. ->where('批次号', $batchNo)
  3069. ->select();
  3070. $newTotal = array_sum(array_column($sameBatchList, 'number'));
  3071. // === 获取物料_库存信息(加上 id 字段) ===
  3072. $inventory = \db('物料_库存')
  3073. ->field('id, 入仓总量, 领用数量, 库存数量, 退还数量')
  3074. ->where('批次号', $batchNo)
  3075. ->find();
  3076. if ($inventory) {
  3077. $stockId = $inventory['id']; // 记录当前库存表的 id
  3078. $inQty = floatval($inventory['入仓总量']);
  3079. $stockQty = floatval($inventory['库存数量']);
  3080. $useQty = floatval($inventory['领用数量']);
  3081. $returnQty = floatval($inventory['退还数量']);
  3082. if ($name == '入库') {
  3083. $newIn = $inQty + $diff;
  3084. $newStock = $stockQty + $diff;
  3085. $updateFields = [];
  3086. if ($newIn != $inQty) {
  3087. $updateFields['入仓总量'] = $newIn;
  3088. $logData[] = [
  3089. '批次号' => $batchNo,
  3090. '操作字段' => '入仓总量',
  3091. '原值' => $inQty,
  3092. '新值' => $newIn,
  3093. '操作人' => $sysId,
  3094. '操作类型' => '入库',
  3095. '操作时间' => $now,
  3096. '修改表' => '物料_库存',
  3097. 'ids' => $stockId
  3098. ];
  3099. }
  3100. if ($newStock != $stockQty) {
  3101. $updateFields['库存数量'] = $newStock;
  3102. $logData[] = [
  3103. '批次号' => $batchNo,
  3104. '操作字段' => '库存数量',
  3105. '原值' => $stockQty,
  3106. '新值' => $newStock,
  3107. '操作人' => $sysId,
  3108. '操作类型' => '入库',
  3109. '操作时间' => $now,
  3110. '修改表' => '物料_库存',
  3111. 'ids' => $stockId
  3112. ];
  3113. }
  3114. if (!empty($updateFields)) {
  3115. $updateStockSql = \db('物料_库存')
  3116. ->where('id', $stockId)
  3117. ->fetchSql(true)
  3118. ->update($updateFields);
  3119. \db()->query($updateStockSql);
  3120. }
  3121. }elseif ($name == '出库') {
  3122. if ($newTotal != $useQty) {
  3123. // 计算新的库存数量
  3124. $newStock = $inQty - $newTotal - $returnQty;
  3125. $updateFields = [
  3126. '领用数量' => $newTotal,
  3127. '库存数量' => $newStock
  3128. ];
  3129. $updateStockSql = \db('物料_库存')
  3130. ->where('id', $stockId)
  3131. ->fetchSql(true)
  3132. ->update($updateFields);
  3133. \db()->query($updateStockSql);
  3134. $logData[] = [
  3135. '批次号' => $batchNo,
  3136. '操作字段' => '领用数量',
  3137. '原值' => $useQty,
  3138. '新值' => $newTotal,
  3139. '操作人' => $sysId,
  3140. '操作类型' => '出库',
  3141. '操作时间' => $now,
  3142. '修改表' => '物料_库存',
  3143. 'ids' => $stockId
  3144. ];
  3145. $logData[] = [
  3146. '批次号' => $batchNo,
  3147. '操作字段' => '库存数量',
  3148. '原值' => $stockQty,
  3149. '新值' => $newStock,
  3150. '操作人' => $sysId,
  3151. '操作类型' => '出库',
  3152. '操作时间' => $now,
  3153. '修改表' => '物料_库存',
  3154. 'ids' => $stockId
  3155. ];
  3156. }
  3157. }elseif ($name == '退还') {
  3158. if ($returnType == '退面料' && $newTotal != $returnQty) {
  3159. $newStock = $inQty - $useQty - $newTotal;
  3160. $updateFields = [
  3161. '退还数量' => $newTotal,
  3162. '库存数量' => $newStock
  3163. ];
  3164. $updateStockSql = \db('物料_库存')
  3165. ->where('id', $stockId)
  3166. ->fetchSql(true)
  3167. ->update($updateFields);
  3168. \db()->query($updateStockSql);
  3169. $logData[] = [
  3170. '批次号' => $batchNo,
  3171. '操作字段' => '退还数量',
  3172. '原值' => $returnQty,
  3173. '新值' => $newTotal,
  3174. '操作人' => $sysId,
  3175. '操作类型' => '退还',
  3176. '操作时间' => $now,
  3177. '修改表' => '物料_库存',
  3178. 'ids' => $stockId
  3179. ];
  3180. // 添加库存数量变更日志
  3181. $logData[] = [
  3182. '批次号' => $batchNo,
  3183. '操作字段' => '库存数量',
  3184. '原值' => $stockQty,
  3185. '新值' => $newStock,
  3186. '操作人' => $sysId,
  3187. '操作类型' => '退还',
  3188. '操作时间' => $now,
  3189. '修改表' => '物料_库存',
  3190. 'ids' => $stockId
  3191. ];
  3192. }
  3193. }
  3194. }
  3195. }
  3196. // 批量写入日志
  3197. if (!empty($logData)) {
  3198. \db('物料_库存日志')->insertAll($logData);
  3199. }
  3200. $this->success('更新成功');
  3201. }
  3202. /**
  3203. * 成品入仓合格率左侧菜单
  3204. */
  3205. public function GetWfpDataLeft()
  3206. {
  3207. // $countData = Db::name('设备_产量计酬')->alias('a')
  3208. // ->field('COUNT(DISTINCT a.订单编号) as total_count,
  3209. // DATE_FORMAT(a.sys_rq, "%Y%m") as 年月,
  3210. // b.客户编号')
  3211. // ->where('工序编号',6)
  3212. // ->join('工单_基本资料 b', 'a.订单编号 = b.订单编号', 'left')
  3213. // ->group('DATE_FORMAT(b.Sys_rq, "%Y%m"), b.客户编号')
  3214. // ->whereNull('a.mod_rq')
  3215. // ->whereNull('b.Mod_rq')
  3216. // ->select();
  3217. // 统计每个客户每月的去重订单数
  3218. $countData = Db::name('成品入仓')
  3219. ->alias('a')
  3220. ->field('COUNT(DISTINCT a.order) as total_count,
  3221. DATE_FORMAT(a.sys_rq, "%Y%m") as 年月,
  3222. b.客户编号')
  3223. ->join('工单_基本资料 b', 'a.order = b.订单编号', 'left')
  3224. ->group('DATE_FORMAT(a.sys_rq, "%Y%m"), b.客户编号')
  3225. ->whereNull('a.mod_rq')
  3226. ->whereNull('b.Mod_rq')
  3227. ->select();
  3228. // 整理结果:按年月分组
  3229. $result = [];
  3230. foreach ($countData as $item) {
  3231. $yearMonth = $item['年月'];
  3232. if (!isset($result[$yearMonth])) {
  3233. $result[$yearMonth] = [];
  3234. }
  3235. $result[$yearMonth][] = [
  3236. '客户编号' => $item['客户编号'],
  3237. 'total' => '订单数:'.(int)$item['total_count']
  3238. ];
  3239. }
  3240. krsort($result);
  3241. $this->success('请求成功', $result);
  3242. }
  3243. /**
  3244. 成品入仓订单列表
  3245. */
  3246. public function GetWfpList()
  3247. {
  3248. if (!$this->request->isGet()) {
  3249. $this->error('请求失败');
  3250. }
  3251. $params = $this->request->get();
  3252. // 判断是否有日期参数
  3253. $hasDate = !empty($params['sys_rq']);
  3254. // 时间范围处理
  3255. if ($hasDate) {
  3256. $startDate = date('Y-m-01', strtotime($params['sys_rq'] . '01'));
  3257. $endDate = date('Y-m-d', strtotime("$startDate +1 month"));
  3258. }
  3259. // 获取订单列表(支持搜索)
  3260. $gdQuery = Db::name('工单_基本资料')
  3261. ->field('订单编号, 生产款号, 款式, 订单数量, 客户编号')
  3262. ->whereNull('mod_rq');
  3263. if (!empty($params['search'])) {
  3264. $gdQuery->where('订单编号|生产款号|款式', 'like', '%' . $params['search'] . '%');
  3265. }
  3266. $gdlist = $gdQuery->select();
  3267. if (empty($gdlist)) {
  3268. $this->success('无匹配订单', ['result' => []]);
  3269. }
  3270. // 提取订单编号列表
  3271. $filteredOrderNos = array_column($gdlist, '订单编号');
  3272. $where = [];
  3273. if (!empty($params['customer'])) {
  3274. $where['a.customer'] = $params['customer'];
  3275. }
  3276. // 入仓数据查询
  3277. // 确保参数存在且格式正确
  3278. $yearMonth = !empty($params['sys_rq']) ? $params['sys_rq'] : '';
  3279. // 构建查询
  3280. $warehouseQuery = Db::name('成品入仓')
  3281. ->alias('a')
  3282. ->field('a.order as 订单编号, SUM(a.sl) as 入仓数量,a.sys_rq,a.customer')
  3283. ->where($where)
  3284. ->whereIn('a.order', $filteredOrderNos)
  3285. ->whereNull('a.mod_rq');
  3286. // 只当有有效年月参数时添加日期筛选
  3287. if ($yearMonth && strlen($yearMonth) == 6) {
  3288. // 使用字符串拼接的方式确保SQL函数正确执行
  3289. $warehouseQuery->where("DATE_FORMAT(a.sys_rq, '%Y%m') = '{$yearMonth}'");
  3290. }
  3291. $warehouseData = $warehouseQuery->group('a.order')->select();
  3292. // 提取入仓涉及的订单编号
  3293. $orderNos = array_column($warehouseData, '订单编号');
  3294. if (empty($orderNos)) {
  3295. $this->success('无数据', ['result' => []]);
  3296. }
  3297. // 入仓 map
  3298. $warehouseMap = [];
  3299. foreach ($warehouseData as $row) {
  3300. $warehouseMap[$row['订单编号']] = (int)$row['入仓数量'];
  3301. }
  3302. // 累计入仓处理
  3303. $cumulativeMap = [];
  3304. if ($hasDate) {
  3305. // 有日期时,累计入仓是所有时间的总和
  3306. $cumulativeData = Db::name('成品入仓')
  3307. ->alias('a')
  3308. ->field('a.order as 订单编号, SUM(a.sl) as 累计入仓数量')
  3309. ->where($where)
  3310. ->whereIn('a.order', $orderNos)
  3311. ->whereNull('a.mod_rq')
  3312. ->group('a.order')
  3313. ->select();
  3314. foreach ($cumulativeData as $row) {
  3315. $cumulativeMap[$row['订单编号']] = (int)$row['累计入仓数量'];
  3316. }
  3317. } else {
  3318. // 没有日期时,累计入仓就是当前入仓数量
  3319. foreach ($warehouseData as $row) {
  3320. $cumulativeMap[$row['订单编号']] = (int)$row['入仓数量'];
  3321. }
  3322. }
  3323. // 裁剪产量
  3324. $prodRecords = Db::name('设备_产量计酬')
  3325. ->whereIn('订单编号', $orderNos)
  3326. ->where('工序名称', '裁剪')
  3327. ->select();
  3328. $cutMap = [];
  3329. foreach ($prodRecords as $record) {
  3330. $orderNo = $record['订单编号'];
  3331. $styleCode = $record['款号'] ?? '';
  3332. $qty = (int)$record['数量'];
  3333. if (!isset($cutMap[$orderNo])) {
  3334. $cutMap[$orderNo] = [
  3335. '生产款号' => $styleCode,
  3336. '裁剪总产量' => 0
  3337. ];
  3338. }
  3339. $cutMap[$orderNo]['裁剪总产量'] += $qty;
  3340. }
  3341. // 质量数据(返工/次片)
  3342. $qualityData = Db::name('设备_质量汇总')
  3343. ->field('订单编号, 状态, SUM(数量) as 数量')
  3344. ->whereIn('订单编号', $orderNos)
  3345. ->group('订单编号, 状态')
  3346. ->select();
  3347. $qualityMap = [];
  3348. foreach ($qualityData as $item) {
  3349. $orderNo = $item['订单编号'];
  3350. $status = $item['状态'];
  3351. $qty = (int)$item['数量'];
  3352. if (!isset($qualityMap[$orderNo])) {
  3353. $qualityMap[$orderNo] = [
  3354. '返工总数' => 0,
  3355. '次片总数' => 0
  3356. ];
  3357. }
  3358. if ($status === '返工') {
  3359. $qualityMap[$orderNo]['返工总数'] += $qty;
  3360. } elseif ($status === '次片') {
  3361. $qualityMap[$orderNo]['次片总数'] += $qty;
  3362. }
  3363. }
  3364. // 获取订单信息映射
  3365. $orderInfoList = Db::name('工单_基本资料')
  3366. ->field('订单编号, 款式, 订单数量, 客户编号')
  3367. ->whereIn('订单编号', $orderNos)
  3368. ->select();
  3369. $orderInfoMap = [];
  3370. foreach ($orderInfoList as $orderInfo) {
  3371. $orderNo = $orderInfo['订单编号'];
  3372. $orderInfoMap[$orderNo] = [
  3373. '款式' => $orderInfo['款式'] ?? '',
  3374. '订单数量' => $orderInfo['订单数量'] ?? 0,
  3375. '客户编号' => $orderInfo['客户编号'] ?? ''
  3376. ];
  3377. }
  3378. // 汇总数据
  3379. $result = [];
  3380. foreach ($orderNos as $orderNo) {
  3381. $cutQty = $cutMap[$orderNo]['裁剪总产量'] ?? 0;
  3382. $warehouseQty = $warehouseMap[$orderNo] ?? 0;
  3383. $cumulativeQty = $cumulativeMap[$orderNo] ?? 0;
  3384. $styleCode = $cutMap[$orderNo]['生产款号'] ?? '';
  3385. $orderInfo = $orderInfoMap[$orderNo] ?? [];
  3386. $khName = $orderInfo['客户编号'] ?? '';
  3387. $styleName = $orderInfo['款式'] ?? '';
  3388. $orderQty = $orderInfo['订单数量'] ?? 0;
  3389. $actualPassRate = $cutQty > 0 ? round($cumulativeQty / $cutQty * 100, 2) . '%' : '0%';
  3390. $reworkQty = $qualityMap[$orderNo]['返工总数'] ?? 0;
  3391. $secondQty = $qualityMap[$orderNo]['次片总数'] ?? 0;
  3392. $result[] = [
  3393. '订单编号' => $orderNo,
  3394. '生产款号' => $styleCode,
  3395. '客户编号' => $khName,
  3396. '款式' => $styleName,
  3397. '订单数量' => $orderQty,
  3398. '裁剪总产量' => $cutQty,
  3399. '入仓数量' => $warehouseQty,
  3400. '累计入仓数量' => $cumulativeQty,
  3401. '裁剪合格率' => $actualPassRate,
  3402. '返工总数' => $reworkQty,
  3403. '次片总数' => $secondQty,
  3404. '统计类型' => $hasDate ? '月度统计' : '总计'
  3405. ];
  3406. }
  3407. $this->success('请求成功', ['result' => $result]);
  3408. }
  3409. /**
  3410. * 成品入仓子订单列表
  3411. */
  3412. public function GetSubOrderStats()
  3413. {
  3414. if (!$this->request->isGet()) {
  3415. $this->error('请求失败');
  3416. }
  3417. $params = $this->request->get();
  3418. $startDate = date('Y-m-01', strtotime($params['sys_rq'] . '01'));
  3419. $endDate = date('Y-m-d', strtotime("$startDate +1 month"));
  3420. //获取该订单的所有子订单
  3421. $styleData = Db::name('工单_印件资料')
  3422. ->where('订单编号', $params['order'])
  3423. ->field('子订单编号, 款号, 颜色备注, 颜色,zdtotal')
  3424. ->whereNull('Mod_rq')
  3425. ->select();
  3426. $subOrderNos = array_column($styleData, '子订单编号');
  3427. if (empty($subOrderNos)) {
  3428. $this->success('未找到该订单下的子订单资料', ['result' => [], 'list' => []]);
  3429. }
  3430. $styleMap = [];
  3431. foreach ($styleData as $row) {
  3432. $styleMap[$row['子订单编号']] = [
  3433. 'zdtotal' => $row['zdtotal'],
  3434. '款号' => $row['款号'],
  3435. '颜色' => $row['颜色'],
  3436. '颜色备注' => $row['颜色备注']
  3437. ];
  3438. }
  3439. // 子订单入仓数据(当前月)
  3440. $warehouseData = Db::name('设备_产量计酬')
  3441. ->field('子订单编号, SUM(s_num) as 入仓数量')
  3442. // ->where('customer', $params['customer'])
  3443. ->where('订单编号', $params['order'])
  3444. ->whereNull('mod_rq')
  3445. ->where('工序名称', '总检')
  3446. ->whereBetween('sys_rq', [$startDate, $endDate])
  3447. ->group('子订单编号')
  3448. ->select();
  3449. $warehouseMap = [];
  3450. foreach ($warehouseData as $row) {
  3451. $warehouseMap[$row['子订单编号']] = (int)$row['入仓数量'];
  3452. }
  3453. //累计入仓(不限时间)
  3454. $cumulativeData = Db::name('设备_产量计酬')
  3455. ->field('子订单编号, SUM(s_num) as 累计入仓数量')
  3456. // ->where('customer', $params['customer'])
  3457. ->where('子订单编号', $params['order'])
  3458. ->where('工序名称', '总检')
  3459. ->whereNull('mod_rq')
  3460. ->group('子订单编号')
  3461. ->select();
  3462. $cumulativeMap = [];
  3463. foreach ($cumulativeData as $row) {
  3464. $cumulativeMap[$row['子订单编号']] = (int)$row['累计入仓数量'];
  3465. }
  3466. // 裁剪产量(不限时间)
  3467. $prodRecords = Db::name('设备_产量计酬')
  3468. ->whereIn('子订单编号', $subOrderNos)
  3469. ->where('工序名称', '裁剪')
  3470. ->select();
  3471. $cutMap = [];
  3472. foreach ($prodRecords as $row) {
  3473. $subOrder = $row['子订单编号'];
  3474. $qty = (int)$row['数量'];
  3475. if (!isset($cutMap[$subOrder])) {
  3476. $cutMap[$subOrder] = 0;
  3477. }
  3478. $cutMap[$subOrder] += $qty;
  3479. }
  3480. $result = [];
  3481. $totalCut = 0;
  3482. $totalIn = 0;
  3483. $orderNo = $params['order'];
  3484. foreach ($subOrderNos as $subOrderNo) {
  3485. $inQty = $warehouseMap[$subOrderNo] ?? 0;
  3486. $totalInQty = $cumulativeMap[$subOrderNo] ?? 0;
  3487. $cutQty = $cutMap[$subOrderNo] ?? 0;
  3488. $styleInfo = $styleMap[$subOrderNo] ?? ['zdtotal' => '','款号' => '', '颜色' => '', '颜色备注' => ''];
  3489. $monthlyRate = $cutQty > 0 ? round($inQty / $cutQty * 100, 2) . '%' : '0%';
  3490. $cumulativeRate = $cutQty > 0 ? round($totalInQty / $cutQty * 100, 2) . '%' : '0%';
  3491. $result[] = [
  3492. '订单编号' => $orderNo,
  3493. '子订单编号' => $subOrderNo,
  3494. '生产款号' => $styleInfo['款号'],
  3495. '颜色' => $styleInfo['颜色'],
  3496. 'zdtotal' => $styleInfo['zdtotal'],
  3497. '颜色备注' => $styleInfo['颜色备注'],
  3498. '裁剪数量' => $cutQty,
  3499. '入仓数量' => $inQty,
  3500. '累计入仓数量' => $totalInQty,
  3501. '月度合格率' => $monthlyRate,
  3502. '实际合格率' => $cumulativeRate
  3503. ];
  3504. $totalCut += $cutQty;
  3505. $totalIn += $totalInQty;
  3506. }
  3507. $list = [[
  3508. '订单编号' => $orderNo,
  3509. '订单累计裁剪数量' => $totalCut,
  3510. '订单累计入仓数量' => $totalIn,
  3511. '订单合格率' => $totalCut > 0 ? round($totalIn / $totalCut * 100, 2) . '%' : '0%'
  3512. ]];
  3513. $this->success('请求成功', [
  3514. 'list' => $list,
  3515. 'result' => $result
  3516. ]);
  3517. }
  3518. /**
  3519. * 电表管理
  3520. */
  3521. private function httpGetRequest($url, $params = [])
  3522. {
  3523. if (!empty($params)) {
  3524. $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
  3525. }
  3526. $ch = curl_init();
  3527. curl_setopt($ch, CURLOPT_URL, $url);
  3528. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3529. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  3530. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  3531. 'Content-Type: application/json',
  3532. ]);
  3533. $response = curl_exec($ch);
  3534. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  3535. if (curl_errno($ch)) {
  3536. $errorMsg = curl_error($ch);
  3537. curl_close($ch);
  3538. throw new Exception('cURL错误: ' . $errorMsg);
  3539. }
  3540. curl_close($ch);
  3541. if ($httpCode !== 200) {
  3542. throw new Exception('API请求失败,HTTP状态码: ' . $httpCode);
  3543. }
  3544. $resultData = json_decode($response, true);
  3545. if (json_last_error() !== JSON_ERROR_NONE) {
  3546. throw new Exception('JSON解析错误: ' . json_last_error_msg());
  3547. }
  3548. return $resultData;
  3549. }
  3550. /**
  3551. * 接口api说明:设备数据/设备状态
  3552. * 接口说明:查询设备列表和当前状态-左侧菜单
  3553. */
  3554. public function Meter()
  3555. {
  3556. $res = Db::name('电表设备列表')->select();
  3557. $this->success('请求成功', $res);
  3558. }
  3559. /**
  3560. * 查询电表能耗数据日数据
  3561. */
  3562. public function StatisticEleDay()
  3563. {
  3564. if (!$this->request->isGet()) {
  3565. $this->error('非法请求');
  3566. }
  3567. $params = $this->request->get();
  3568. // 检查 mid 参数是否为空
  3569. if (empty($params['mid'])) {
  3570. $this->error('mid参数不能为空');
  3571. }
  3572. $mid = (int)$params['mid'];
  3573. $riqi = $params['riqi'] ?? date('Ym');
  3574. $where = [];
  3575. $where['电表ID'] = $mid;
  3576. // 通过日期查询
  3577. if (!empty($params['riqi'])) {
  3578. if (preg_match('/^\d{6}$/', $params['riqi'])) {
  3579. // 年月格式:YYYYMM,查询该月份所有数据
  3580. $startDate = $params['riqi'] . '01';
  3581. $endDate = date('Ymd', strtotime("last day of {$params['riqi']}01"));
  3582. $where['日期'] = ['between', [$startDate, $endDate]];
  3583. } else {
  3584. $this->error('日期参数格式错误,应为 YYYYMM');
  3585. }
  3586. } else {
  3587. // 默认查询当前月份
  3588. $currentMonth = date('Ym');
  3589. $startDate = $currentMonth . '01';
  3590. $endDate = date('Ymd');
  3591. $where['日期'] = ['between', [$startDate, $endDate]];
  3592. }
  3593. $res = Db::name('电表能耗日数据')
  3594. ->where($where)->order('日期 DESC')->select();
  3595. $this->success('查询成功', $res);
  3596. }
  3597. /**
  3598. * 导出电表月数据
  3599. */
  3600. public function Excel_StatisticEle(){
  3601. if (!$this->request->isGet()) {
  3602. $this->error('非法请求');
  3603. }
  3604. $params = $this->request->get();
  3605. $res = Db::name('电表能耗月数据')->alias('a')
  3606. ->field('
  3607. a.id,
  3608. a.电表ID,
  3609. a.总电量,
  3610. a.尖电量,
  3611. a.峰电量,
  3612. a.平电量,
  3613. a.谷电量,
  3614. a.起始总电量,
  3615. a.结束总电量,
  3616. a.开始时间,
  3617. a.结束时间,
  3618. a.日期,
  3619. b.description as 小组
  3620. ')
  3621. ->join('电表设备列表 b', 'a.电表ID = b.mid', 'LEFT')
  3622. ->where('日期',$params['sys_rq'])
  3623. ->where('b.description', '<>', '')
  3624. ->where('b.description', 'not null')
  3625. ->order('b.id asc')
  3626. ->select();
  3627. $this->success('请求成功', $res);
  3628. }
  3629. /**
  3630. * 同步电表序号列表数据
  3631. * 查询设备列表和当前状态-左侧菜单
  3632. */
  3633. public function saveToDatabase()
  3634. {
  3635. $url = "http://api1.tqdianbiao.com/Api/Meter?type=json&auth=a15dbee8d66bf1b4149637e3912bf631";
  3636. $resultData = $this->httpGetRequest($url);
  3637. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3638. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3639. }
  3640. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3641. throw new Exception('API返回数据格式不正确');
  3642. }
  3643. $result = [];
  3644. foreach ($resultData['data'] as $meter) {
  3645. $result[] = [
  3646. 'mid' => $meter['id'],
  3647. 'collectorid' => $meter['collectorid'],
  3648. 'description' => $meter['description']
  3649. ];
  3650. }
  3651. // 批量处理数据
  3652. foreach ($result as $item) {
  3653. $dbData = [
  3654. 'mid' => (int)$item['mid'],
  3655. 'collectorid' => (int)$item['collectorid'],
  3656. 'description' => $item['description']
  3657. ];
  3658. $exists = Db::name('电表设备列表')->where('mid', $dbData['mid'])->find();
  3659. if ($exists) {
  3660. Db::name('电表设备列表')
  3661. ->where('mid', $dbData['mid'])
  3662. ->update($dbData);
  3663. } else {
  3664. Db::name('电表设备列表')->insert($dbData);
  3665. }
  3666. }
  3667. }
  3668. /**
  3669. * 同步电表能耗数据小时数据
  3670. * 查询指定月份的电表能耗小时数据
  3671. */
  3672. public function StatisticEle_Hour()
  3673. {
  3674. if (!$this->request->isGet()) {
  3675. $this->error('非法请求');
  3676. }
  3677. $params = $this->request->get();
  3678. $filterMid = $params['mid'] ?? null;
  3679. // // 默认当天
  3680. $startDate = $params['riqi'] ?? date('Ymd');
  3681. $endDate = $params['riqi'] ?? date('Ymd');
  3682. // 验证日期格式
  3683. if (!preg_match('/^\d{8}$/', $startDate) || !preg_match('/^\d{8}$/', $endDate)) {
  3684. $this->error('参数格式错误');
  3685. }
  3686. // 确保开始日期不大于结束日期
  3687. if ($startDate > $endDate) {
  3688. $this->error('开始日期不能大于结束日期');
  3689. }
  3690. $startTime = $startDate . '00'; // 从开始日期的00点开始
  3691. $endTime = $endDate . '23'; // 到结束日期的23点结束
  3692. $url = "http://api1.tqdianbiao.com/Api/StatisticEle/hour?auth=a15dbee8d66bf1b4149637e3912bf631&type=json&ignore_radio=0&start_time={$startTime}&end_time={$endTime}";
  3693. try {
  3694. $resultData = $this->httpGetRequest($url);
  3695. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3696. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3697. }
  3698. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3699. throw new Exception('API返回数据格式不正确');
  3700. }
  3701. $rawData = $resultData['data'];
  3702. $result = [];
  3703. foreach ($rawData as $date => $records) {
  3704. foreach ($records as $row) {
  3705. $result[] = [
  3706. '日期' => $date,
  3707. '电表ID' => $row['mid'] ?? '',
  3708. '开始时间' => $row['st'] ?? '',
  3709. '结束时间' => $row['et'] ?? '',
  3710. '互感器变比' => $row['r'] ?? 1,
  3711. '总电量' => $row['d'][0] ?? 0,
  3712. '尖电量' => $row['d'][1] ?? 0,
  3713. '峰电量' => $row['d'][2] ?? 0,
  3714. '平电量' => $row['d'][3] ?? 0,
  3715. '谷电量' => $row['d'][4] ?? 0,
  3716. '起始总电量' => $row['s'][0] ?? 0,
  3717. '结束总电量' => $row['e'][0] ?? 0
  3718. ];
  3719. }
  3720. }
  3721. // 按日期时间倒序排序
  3722. usort($result, function ($a, $b) {
  3723. $timeA = strtotime($a['开始时间']);
  3724. $timeB = strtotime($b['开始时间']);
  3725. return $timeB - $timeA;
  3726. });
  3727. // 直接保存到数据库
  3728. $insertCount = 0;
  3729. $updateCount = 0;
  3730. $errorCount = 0;
  3731. if (!empty($result)) {
  3732. foreach ($result as $index => $item) {
  3733. $sql = '';
  3734. try {
  3735. Log::info("=== 处理第 {$index} 条数据 ===");
  3736. // 准备数据库数据
  3737. $dbData = [
  3738. '电表ID' => (string)$item['电表ID'],
  3739. '互感器变比' => (string)$item['互感器变比'],
  3740. '总电量' => (string)$item['总电量'],
  3741. '尖电量' => (string)$item['尖电量'],
  3742. '峰电量' => (string)$item['峰电量'],
  3743. '平电量' => (string)$item['平电量'],
  3744. '谷电量' => (string)$item['谷电量'],
  3745. '起始总电量' => (string)$item['起始总电量'],
  3746. '结束总电量' => (string)$item['结束总电量'],
  3747. '开始时间' => $item['开始时间'],
  3748. '结束时间' => $item['结束时间'],
  3749. '日期' => (string)$item['日期']
  3750. ];
  3751. Log::info('处理数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3752. // 检查记录是否已存在 - 使用电表ID、开始时间和结束时间作为唯一标识
  3753. $exists = Db::name('电表能耗小时数据')
  3754. ->where('电表ID', $dbData['电表ID'])
  3755. ->where('开始时间', $dbData['开始时间'])
  3756. ->where('结束时间', $dbData['结束时间'])
  3757. ->find();
  3758. Log::info('查询条件: 电表ID=' . $dbData['电表ID'] . ', 开始时间=' . $dbData['开始时间'] . ', 结束时间=' . $dbData['结束时间']);
  3759. Log::info('查询结果: ' . ($exists ? '记录存在, ID=' . $exists['id'] : '记录不存在'));
  3760. if ($exists) {
  3761. // 检查数据是否有变化,有变化才更新
  3762. $needUpdate = false;
  3763. $updateFields = [];
  3764. $fieldsToCompare = [
  3765. '互感器变比', '总电量', '尖电量', '峰电量', '平电量', '谷电量',
  3766. '起始总电量', '结束总电量', '日期'
  3767. ];
  3768. foreach ($fieldsToCompare as $field) {
  3769. $oldValue = $exists[$field] ?? '';
  3770. $newValue = $dbData[$field] ?? '';
  3771. if ($oldValue != $newValue) {
  3772. $needUpdate = true;
  3773. $updateFields[$field] = $newValue;
  3774. Log::info("字段 {$field} 有变化: '{$oldValue}' -> '{$newValue}'");
  3775. }
  3776. }
  3777. if ($needUpdate) {
  3778. $sql = Db::name('电表能耗小时数据')
  3779. ->where('id', $exists['id'])
  3780. ->fetchSql(true)
  3781. ->update($updateFields);
  3782. Log::info('执行更新SQL: ' . $sql);
  3783. $updateResult = \db()->query($sql);
  3784. Log::info('更新结果: ' . ($updateResult !== false ? '成功' : '失败'));
  3785. $updateCount++;
  3786. } else {
  3787. Log::info('数据无变化,跳过更新');
  3788. }
  3789. } else {
  3790. // 插入新记录
  3791. $sql = Db::name('电表能耗小时数据')->fetchSql(true)->insert($dbData);
  3792. Log::info('执行插入SQL: ' . $sql);
  3793. $insertResult = \db()->query($sql);
  3794. Log::info('插入结果: ' . ($insertResult !== false ? '成功' : '失败'));
  3795. if ($insertResult !== false) {
  3796. $insertCount++;
  3797. } else {
  3798. throw new Exception('插入操作返回false');
  3799. }
  3800. }
  3801. Log::info("=== 第 {$index} 条数据处理完成 ===\n");
  3802. } catch (Exception $e) {
  3803. $errorCount++;
  3804. Log::error("=== 第 {$index} 条数据处理失败 ===");
  3805. Log::error('错误信息: ' . $e->getMessage());
  3806. Log::error('失败数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3807. Log::error('执行SQL: ' . $sql);
  3808. Log::error('错误位置: ' . $e->getFile() . ':' . $e->getLine());
  3809. Log::error("=== 第 {$index} 条数据处理结束 ===\n");
  3810. }
  3811. }
  3812. }
  3813. $saveMessage = "数据保存完成 - 新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条";
  3814. $this->success($saveMessage, [
  3815. 'data' => $result,
  3816. ]);
  3817. } catch (Exception $e) {
  3818. $this->error('请求失败: ' . $e->getMessage());
  3819. }
  3820. }
  3821. /**
  3822. * 同步电表能耗数据小时数据
  3823. * 查询指定月份的电表能耗日数据
  3824. */
  3825. public function StatisticEle_Day()
  3826. {
  3827. if (!$this->request->isGet()) {
  3828. $this->error('非法请求');
  3829. }
  3830. $params = $this->request->get();
  3831. $filterMid = $params['mid'] ?? null;
  3832. $riqi = $params['riqi'] ?? date('Ym'); // 默认当前年月
  3833. if (!preg_match('/^\d{6}$/', $riqi)) {
  3834. $this->error('参数 riqi 格式错误,应为 YYYYMM');
  3835. }
  3836. // 构造 start_time
  3837. $startTime = $riqi . '01';
  3838. // 判断是当前月还是历史月
  3839. $currentMonth = date('Ym');
  3840. if ($riqi === $currentMonth) {
  3841. $endTime = date('Ymd'); // 今天
  3842. } else {
  3843. $endTime = date('Ymd', strtotime("last day of {$riqi}01")); // 历史月最后一天
  3844. }
  3845. // 构造 API 请求 URL - 查询指定月份的电表能耗日数据
  3846. $url = "http://api1.tqdianbiao.com/Api/StatisticEle/day?auth=a15dbee8d66bf1b4149637e3912bf631&type=json&ignore_radio=0&start_time={$startTime}&end_time={$endTime}";
  3847. try {
  3848. $resultData = $this->httpGetRequest($url);
  3849. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3850. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3851. }
  3852. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3853. throw new Exception('API返回数据格式不正确');
  3854. }
  3855. $rawData = $resultData['data'];
  3856. $result = [];
  3857. foreach ($rawData as $date => $records) {
  3858. foreach ($records as $row) {
  3859. $result[] = [
  3860. '日期' => $date,
  3861. '电表ID' => $row['mid'] ?? '',
  3862. '开始时间' => $row['st'] ?? '',
  3863. '结束时间' => $row['et'] ?? '',
  3864. '互感器变比' => $row['r'] ?? 1,
  3865. '总电量' => $row['d'][0] ?? 0,
  3866. '尖电量' => $row['d'][1] ?? 0,
  3867. '峰电量' => $row['d'][2] ?? 0,
  3868. '平电量' => $row['d'][3] ?? 0,
  3869. '谷电量' => $row['d'][4] ?? 0,
  3870. '起始总电量' => $row['s'][0] ?? 0,
  3871. '结束总电量' => $row['e'][0] ?? 0
  3872. ];
  3873. }
  3874. }
  3875. usort($result, function ($a, $b) {
  3876. return strcmp($b['日期'], $a['日期']);
  3877. });
  3878. // 直接保存到数据库
  3879. $insertCount = 0;
  3880. $updateCount = 0;
  3881. $errorCount = 0;
  3882. if (!empty($result)) {
  3883. foreach ($result as $index => $item) {
  3884. $sql = '';
  3885. try {
  3886. Log::info("=== 处理第 {$index} 条数据 ===");
  3887. // 准备数据库数据 - 修正字段名为大写
  3888. $dbData = [
  3889. '电表ID' => (string)$item['电表ID'], // 修正:电表ID(大写)
  3890. '互感器变比' => (string)$item['互感器变比'],
  3891. '总电量' => (string)$item['总电量'],
  3892. '尖电量' => (string)$item['尖电量'],
  3893. '峰电量' => (string)$item['峰电量'],
  3894. '平电量' => (string)$item['平电量'],
  3895. '谷电量' => (string)$item['谷电量'],
  3896. '起始总电量' => (string)$item['起始总电量'],
  3897. '结束总电量' => (string)$item['结束总电量'],
  3898. '开始时间' => $item['开始时间'],
  3899. '结束时间' => $item['结束时间'],
  3900. '日期' => (string)$item['日期']
  3901. ];
  3902. Log::info('处理数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3903. // 检查记录是否已存在 - 使用正确的字段名
  3904. $exists = Db::name('电表能耗日数据')
  3905. ->where('电表ID', $dbData['电表ID']) // 修正:电表ID(大写)
  3906. ->where('日期', $dbData['日期'])
  3907. ->find();
  3908. Log::info('查询条件: 电表ID=' . $dbData['电表ID'] . ', 日期=' . $dbData['日期']);
  3909. Log::info('查询结果: ' . ($exists ? '记录存在, ID=' . $exists['id'] : '记录不存在'));
  3910. if ($exists) {
  3911. // 检查数据是否有变化,有变化才更新
  3912. $needUpdate = false;
  3913. $updateFields = [];
  3914. $fieldsToCompare = [
  3915. '互感器变比', '总电量', '尖电量', '峰电量', '平电量', '谷电量',
  3916. '起始总电量', '结束总电量', '开始时间', '结束时间'
  3917. ];
  3918. foreach ($fieldsToCompare as $field) {
  3919. $oldValue = $exists[$field] ?? '';
  3920. $newValue = $dbData[$field] ?? '';
  3921. if ($oldValue != $newValue) {
  3922. $needUpdate = true;
  3923. $updateFields[$field] = $newValue;
  3924. Log::info("字段 {$field} 有变化: '{$oldValue}' -> '{$newValue}'");
  3925. }
  3926. }
  3927. if ($needUpdate) {
  3928. $sql = Db::name('电表能耗日数据')
  3929. ->where('id', $exists['id'])
  3930. ->fetchSql(true)
  3931. ->update($updateFields);
  3932. Log::info('执行更新SQL: ' . $sql);
  3933. $updateResult = \db()->query($sql);
  3934. Log::info('更新结果: ' . ($updateResult !== false ? '成功' : '失败'));
  3935. $updateCount++;
  3936. } else {
  3937. Log::info('数据无变化,跳过更新');
  3938. }
  3939. } else {
  3940. // 插入新记录
  3941. $sql = Db::name('电表能耗日数据')->fetchSql(true)->insert($dbData);
  3942. Log::info('执行插入SQL: ' . $sql);
  3943. $insertResult = \db()->query($sql);
  3944. Log::info('插入结果: ' . ($insertResult !== false ? '成功' : '失败'));
  3945. if ($insertResult !== false) {
  3946. $insertCount++;
  3947. } else {
  3948. throw new Exception('插入操作返回false');
  3949. }
  3950. }
  3951. Log::info("=== 第 {$index} 条数据处理完成 ===\n");
  3952. } catch (Exception $e) {
  3953. $errorCount++;
  3954. Log::error("=== 第 {$index} 条数据处理失败 ===");
  3955. Log::error('错误信息: ' . $e->getMessage());
  3956. Log::error('失败数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3957. Log::error('执行SQL: ' . $sql);
  3958. Log::error('错误位置: ' . $e->getFile() . ':' . $e->getLine());
  3959. Log::error("=== 第 {$index} 条数据处理结束 ===\n");
  3960. }
  3961. }
  3962. }
  3963. Log::info("=== 最终统计 ===");
  3964. Log::info("新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条");
  3965. $saveMessage = "数据保存完成 - 新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条";
  3966. $this->success($saveMessage, [
  3967. 'data' => $result,
  3968. ]);
  3969. } catch (Exception $e) {
  3970. $this->error('请求失败: ' . $e->getMessage());
  3971. }
  3972. }
  3973. /**
  3974. * 同步电表能耗数据月数据
  3975. * 查询指定月份的电表能耗月数据
  3976. */
  3977. public function StatisticEle_Month()
  3978. {
  3979. if (!$this->request->isGet()) {
  3980. $this->error('非法请求');
  3981. }
  3982. $params = $this->request->get();
  3983. $filterMid = $params['mid'] ?? null;
  3984. $riqi = $params['riqi'] ?? date('Ym'); // 默认当前年月
  3985. if (!preg_match('/^\d{6}$/', $riqi)) {
  3986. $this->error('参数 riqi 格式错误,应为 YYYYMM');
  3987. }
  3988. // 构造 start_time 和 end_time - 月接口通常只需要月份参数,查询指定月份的所有数据
  3989. $startTime = $riqi . '01';
  3990. $endTime = $riqi . '31'; // 月数据通常查询单个月份
  3991. // 构造 API 请求 URL - 使用 month 接口查询指定月份的电表能耗月数据
  3992. $url = "http://api1.tqdianbiao.com/Api/StatisticEle/month?auth=a15dbee8d66bf1b4149637e3912bf631&type=json&ignore_radio=0&start_time={$startTime}&end_time={$endTime}";
  3993. try {
  3994. $resultData = $this->httpGetRequest($url);
  3995. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3996. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3997. }
  3998. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3999. throw new Exception('API返回数据格式不正确');
  4000. }
  4001. $rawData = $resultData['data'];
  4002. $result = [];
  4003. foreach ($rawData as $date => $records) {
  4004. foreach ($records as $row) {
  4005. $result[] = [
  4006. '月份' => $date,
  4007. '电表ID' => $row['mid'] ?? '',
  4008. '开始时间' => $row['st'] ?? '',
  4009. '结束时间' => $row['et'] ?? '',
  4010. '互感器变比' => $row['r'] ?? 1,
  4011. '总电量' => $row['d'][0] ?? 0,
  4012. '尖电量' => $row['d'][1] ?? 0,
  4013. '峰电量' => $row['d'][2] ?? 0,
  4014. '平电量' => $row['d'][3] ?? 0,
  4015. '谷电量' => $row['d'][4] ?? 0,
  4016. '起始总电量' => $row['s'][0] ?? 0,
  4017. '结束总电量' => $row['e'][0] ?? 0
  4018. ];
  4019. }
  4020. }
  4021. usort($result, function ($a, $b) {
  4022. return strcmp($b['月份'], $a['月份']);
  4023. });
  4024. // 直接保存到数据库
  4025. $insertCount = 0;
  4026. $updateCount = 0;
  4027. $errorCount = 0;
  4028. if (!empty($result)) {
  4029. foreach ($result as $item) {
  4030. try {
  4031. $dbData = [
  4032. '电表ID' => (int)$item['电表ID'],
  4033. '互感器变比' => (string)$item['互感器变比'],
  4034. '总电量' => (string)$item['总电量'],
  4035. '尖电量' => (string)$item['尖电量'],
  4036. '峰电量' => (string)$item['峰电量'],
  4037. '平电量' => (string)$item['平电量'],
  4038. '谷电量' => (string)$item['谷电量'],
  4039. '起始总电量' => (string)$item['起始总电量'],
  4040. '结束总电量' => (string)$item['结束总电量'],
  4041. '开始时间' => $item['开始时间'],
  4042. '结束时间' => $item['结束时间'],
  4043. '日期' => $item['月份']
  4044. ];
  4045. // 查询是否已存在相同月份的记录
  4046. $exists = Db::name('电表能耗月数据')
  4047. ->where('电表ID', $dbData['电表ID'])
  4048. ->where('日期', $dbData['日期'])
  4049. ->find();
  4050. if ($exists) {
  4051. // 检查是否有字段值不同
  4052. $needUpdate = false;
  4053. $updateFields = [];
  4054. // 检查是否有字段值不同
  4055. $fieldsToCompare = [
  4056. '互感器变比', '总电量', '尖电量', '峰电量', '平电量', '谷电量',
  4057. '起始总电量', '结束总电量', '开始时间', '结束时间'
  4058. ];
  4059. foreach ($fieldsToCompare as $field) {
  4060. if (isset($exists[$field]) && isset($dbData[$field]) && $exists[$field] != $dbData[$field]) {
  4061. $needUpdate = true;
  4062. $updateFields[$field] = $dbData[$field];
  4063. }
  4064. }
  4065. if ($needUpdate) {
  4066. // 只更新有变化的字段
  4067. $sql = Db::name('电表能耗月数据')
  4068. ->where('id', $exists['id'])
  4069. ->fetchSql(true)
  4070. ->update($updateFields);
  4071. \db()->query($sql);
  4072. $updateCount++;
  4073. }
  4074. } else {
  4075. // 插入新记录
  4076. $sql = Db::name('电表能耗月数据')->fetchSql(true)->insert($dbData);
  4077. \db()->query($sql);
  4078. $insertCount++;
  4079. }
  4080. } catch (Exception $e) {
  4081. $errorCount++;
  4082. }
  4083. }
  4084. }
  4085. $saveMessage = "月数据保存完成 - 新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条";
  4086. $this->success($saveMessage, [
  4087. 'data' => $result,
  4088. ]);
  4089. } catch (Exception $e) {
  4090. $this->error('请求失败: ' . $e->getMessage());
  4091. }
  4092. }
  4093. /**
  4094. * 订单电量管理 - 左侧菜单
  4095. * 客户编号按自然顺序排序
  4096. * 返回年份分组的数据结构
  4097. */
  4098. public function CustomerMenu()
  4099. {
  4100. try {
  4101. $startDate = input('start_date', '');
  4102. $endDate = input('end_date', '');
  4103. $query = Db::name('设备_产量计酬')->alias('c')
  4104. ->field('c.订单编号, c.sys_rq, j.客户编号, DATE_FORMAT(c.sys_rq, "%Y%m") as date_group')
  4105. ->join('工单_基本资料 j', 'c.订单编号 = j.订单编号', 'LEFT')
  4106. ->whereNull('c.mod_rq')
  4107. ->whereNull('j.Mod_rq')
  4108. ->where('j.客户编号', '<>', '')
  4109. ->whereNotNull('j.客户编号');
  4110. if (!empty($startDate)) {
  4111. $query->where('c.sys_rq', '>=', $startDate);
  4112. }
  4113. if (!empty($endDate)) {
  4114. $query->where('c.sys_rq', '<=', $endDate);
  4115. }
  4116. $orderRecords = $query->select();
  4117. // 重新组织数据结构,按年份分组
  4118. $structuredData = [];
  4119. foreach ($orderRecords as $record) {
  4120. $yearMonth = $record['date_group'];
  4121. $customerNo = $record['客户编号'];
  4122. if ($yearMonth && $customerNo) {
  4123. $year = substr($yearMonth, 0, 4); // 提取年份
  4124. if (!isset($structuredData[$year])) {
  4125. $structuredData[$year] = [];
  4126. }
  4127. if (!isset($structuredData[$year][$yearMonth])) {
  4128. $structuredData[$year][$yearMonth] = [];
  4129. }
  4130. if (!in_array($customerNo, $structuredData[$year][$yearMonth])) {
  4131. $structuredData[$year][$yearMonth][] = $customerNo;
  4132. }
  4133. }
  4134. }
  4135. // 对每个月份的客户编号进行自然排序,并对月份按倒序排列
  4136. foreach ($structuredData as $year => &$months) {
  4137. foreach ($months as &$customers) {
  4138. natsort($customers);
  4139. $customers = array_values($customers);
  4140. }
  4141. // 对月份按倒序排列
  4142. krsort($months);
  4143. }
  4144. // 对年份按倒序排列
  4145. krsort($structuredData);
  4146. return json([
  4147. 'code' => 0,
  4148. 'msg' => '成功',
  4149. 'time' => time(),
  4150. 'data' => $structuredData
  4151. ]);
  4152. } catch (\Exception $e) {
  4153. return json([
  4154. 'code' => 1,
  4155. 'msg' => '查询失败: ' . $e->getMessage(),
  4156. 'time' => time(),
  4157. 'data' => []
  4158. ]);
  4159. }
  4160. }
  4161. /**
  4162. * 订单电量管理 - 汇总统计
  4163. */
  4164. public function OrderElectricitySummary(){
  4165. if (!$this->request->isGet()) {
  4166. $this->error('非法请求');
  4167. }
  4168. $params = $this->request->get();
  4169. $where = [];
  4170. if (!empty($params['order'])) {
  4171. $where['订单编号'] = $params['order'];
  4172. }
  4173. if (!empty($params['khbh'])) {
  4174. $where['客户编号'] = $params['khbh'];
  4175. }
  4176. $orders = Db::name('工单_基本资料')
  4177. ->field('订单编号,客户编号,生产款号')
  4178. ->where($where)
  4179. ->whereNull('Mod_rq')
  4180. ->select();
  4181. if (empty($orders)) {
  4182. $this->success('未查询到订单数据', []);
  4183. }
  4184. // 获取所有订单编号
  4185. $orderNumbers = array_column($orders, '订单编号');
  4186. // 首先查询每个订单的总产量和总时间范围
  4187. $orderTimeRanges = Db::name('设备_产量计酬')
  4188. ->field('订单编号,SUM(数量) as 总产量,MIN(sys_rq) as 最早报工时间,MAX(sys_rq) as 最晚报工时间,COUNT(*) as 总报工次数')
  4189. ->where('订单编号', 'in', $orderNumbers)
  4190. ->whereNull('mod_rq')
  4191. ->group('订单编号')
  4192. ->select();
  4193. // 构建订单时间范围映射
  4194. $orderTimeMap = [];
  4195. foreach ($orderTimeRanges as $timeRange) {
  4196. $orderTimeMap[$timeRange['订单编号']] = [
  4197. '总产量' => $timeRange['总产量'],
  4198. '最早报工时间' => $timeRange['最早报工时间'],
  4199. '最晚报工时间' => $timeRange['最晚报工时间'],
  4200. '总报工次数' => $timeRange['总报工次数']
  4201. ];
  4202. }
  4203. // 构建报工记录查询(按设备分组)
  4204. $orderRecordsQuery = Db::name('设备_产量计酬')
  4205. ->field('订单编号,sczl_bh,SUM(数量) as 总产量,MIN(sys_rq) as 最早报工时间,MAX(sys_rq) as 最晚报工时间,COUNT(*) as 报工次数')
  4206. ->where('订单编号', 'in', $orderNumbers)
  4207. ->whereNull('mod_rq');
  4208. // 如果有日期参数,按日期筛选报工记录
  4209. $startDate = null;
  4210. $endDate = null;
  4211. if (!empty($params['riqi'])) {
  4212. $date = $params['riqi'];
  4213. $startDate = date('Y-m-01', strtotime($date)); // 当月第一天
  4214. $endDate = date('Y-m-t 23:59:59', strtotime($date)); // 当月最后一天
  4215. $orderRecordsQuery->whereTime('sys_rq', 'between', [$startDate, $endDate]);
  4216. }
  4217. $orderRecords = $orderRecordsQuery->group('订单编号,sczl_bh')->select();
  4218. if (empty($orderRecords)) {
  4219. // 如果没有报工记录,只返回订单基本信息
  4220. $summary = [];
  4221. foreach ($orders as $order) {
  4222. $orderNumber = $order['订单编号'];
  4223. $timeInfo = $orderTimeMap[$orderNumber] ?? [
  4224. '总产量' => 0,
  4225. '最早报工时间' => null,
  4226. '最晚报工时间' => null,
  4227. '总报工次数' => 0
  4228. ];
  4229. $summary[] = [
  4230. '订单编号' => $orderNumber,
  4231. '生产款号' => $order['生产款号'],
  4232. '客户编号' => $order['客户编号'],
  4233. '累计总用电量' => 0,
  4234. '单位电量' => 0,
  4235. '生产时间段' => $timeInfo['最早报工时间'] ? ($timeInfo['最早报工时间'] . ' 至 ' . $timeInfo['最晚报工时间']) : '无生产记录'
  4236. ];
  4237. }
  4238. $this->success('成功', $summary);
  4239. }
  4240. // 获取所有涉及的设备编号
  4241. $sczlBhs = array_unique(array_column($orderRecords, 'sczl_bh'));
  4242. // 通过sczl_bh去电表设备列表表匹配对应的mid
  4243. $deviceMappings = Db::name('电表设备列表')
  4244. ->field('mid, collectorid, description')
  4245. ->where('description', 'in', $sczlBhs)
  4246. ->select();
  4247. $midMap = [];
  4248. $collectorIdMap = [];
  4249. foreach ($deviceMappings as $mapping) {
  4250. $midMap[$mapping['description']] = $mapping['mid'];
  4251. $collectorIdMap[$mapping['description']] = $mapping['collectorid'];
  4252. }
  4253. // 获取所有相关电表的能耗数据 - 使用mid来关联
  4254. $electricData = [];
  4255. if (!empty($midMap)) {
  4256. $mids = array_values($midMap);
  4257. $electricData = Db::name('电表能耗小时数据')
  4258. ->where('电表ID', 'in', $mids)
  4259. ->order('开始时间', 'asc')
  4260. ->select();
  4261. }
  4262. // 按订单编号分组统计总电量
  4263. $orderStats = [];
  4264. // 初始化订单统计
  4265. foreach ($orders as $order) {
  4266. $orderNumber = $order['订单编号'];
  4267. $timeInfo = $orderTimeMap[$orderNumber] ?? [
  4268. '总产量' => 0,
  4269. '最早报工时间' => null,
  4270. '最晚报工时间' => null,
  4271. '总报工次数' => 0
  4272. ];
  4273. $orderStats[$orderNumber] = [
  4274. '订单编号' => $orderNumber,
  4275. '生产款号' => $order['生产款号'],
  4276. '客户编号' => $order['客户编号'],
  4277. '总电量' => 0,
  4278. '总产量' => $timeInfo['总产量'],
  4279. '最早报工时间' => $timeInfo['最早报工时间'],
  4280. '最晚报工时间' => $timeInfo['最晚报工时间']
  4281. ];
  4282. }
  4283. // 统计每个订单的总电量(使用与明细查询相同的逻辑)
  4284. foreach ($orderRecords as $record) {
  4285. $orderNumber = $record['订单编号'];
  4286. $sczlBh = $record['sczl_bh'];
  4287. if (!isset($orderStats[$orderNumber])) {
  4288. continue;
  4289. }
  4290. // 获取对应的电表mid
  4291. $mid = $midMap[$sczlBh] ?? null;
  4292. if (!$mid) {
  4293. continue;
  4294. }
  4295. // 使用订单总时间范围而不是设备小组的时间范围
  4296. $orderTimeInfo = $orderTimeMap[$orderNumber] ?? null;
  4297. if (!$orderTimeInfo) {
  4298. continue;
  4299. }
  4300. $deviceStart = strtotime($orderTimeInfo['最早报工时间']);
  4301. $deviceEnd = strtotime($orderTimeInfo['最晚报工时间']);
  4302. $deviceElectricity = 0;
  4303. foreach ($electricData as $elec) {
  4304. // 正确的比较:电表能耗数据中的电表ID应该等于设备对应的mid
  4305. if ($elec['电表ID'] != $mid) {
  4306. continue;
  4307. }
  4308. $elecStart = strtotime($elec['开始时间']);
  4309. $elecEnd = strtotime($elec['结束时间']);
  4310. // 匹配电表时间段在订单总生产时间段范围内
  4311. if ($elecStart >= $deviceStart && $elecEnd <= $deviceEnd) {
  4312. $deviceElectricity += $elec['总电量'];
  4313. }
  4314. }
  4315. $orderStats[$orderNumber]['总电量'] += $deviceElectricity;
  4316. }
  4317. // 格式化输出结果,并过滤掉总电量为0的记录
  4318. $summary = [];
  4319. foreach ($orderStats as $order) {
  4320. // 只有当总电量大于0时才添加到结果中
  4321. if ($order['总电量'] > 0) {
  4322. $summary[] = [
  4323. '订单编号' => $order['订单编号'],
  4324. '生产款号' => $order['生产款号'],
  4325. '客户编号' => $order['客户编号'],
  4326. '累计总用电量' => round($order['总电量'], 2),
  4327. '单位电量' => $order['总产量'] > 0 ? round($order['总电量'] / $order['总产量'], 4) : 0,
  4328. '生产时间段' => $order['最早报工时间'] ? ($order['最早报工时间'] . ' 至 ' . $order['最晚报工时间']) : '无生产记录'
  4329. ];
  4330. }
  4331. }
  4332. $this->success('成功', $summary);
  4333. }
  4334. /**
  4335. * 订单电量管理 - 明细查询
  4336. */
  4337. public function OrderElectricityDetail(){
  4338. if (!$this->request->isGet()) {
  4339. $this->error('非法请求');
  4340. }
  4341. $params = $this->request->get();
  4342. if (empty($params['order'])) {
  4343. $this->error('订单编号不能为空');
  4344. }
  4345. // 查询订单的基本信息
  4346. $orderInfo = Db::name('工单_基本资料')
  4347. ->field('订单编号,生产款号,客户编号')
  4348. ->where('订单编号', $params['order'])
  4349. ->whereNull('Mod_rq')
  4350. ->find();
  4351. if (!$orderInfo) {
  4352. $this->error('订单不存在');
  4353. }
  4354. // 查询该订单的所有报工记录,按设备分组
  4355. $orderRecords = Db::name('设备_产量计酬')
  4356. ->field('订单编号,sczl_bh,
  4357. CASE
  4358. WHEN 工序名称 IN ("裁剪", "车缝") THEN SUM(数量)
  4359. ELSE SUM(s_num)
  4360. END as 总产量,MIN(sys_rq) as 最早报工时间,MAX(sys_rq) as 最晚报工时间,COUNT(*) as 报工次数')
  4361. ->where('订单编号', $params['order'])
  4362. ->whereNull('mod_rq')
  4363. ->group('sczl_bh')
  4364. ->select();
  4365. if (empty($orderRecords)) {
  4366. $this->success('成功', [
  4367. '订单信息' => $orderInfo,
  4368. '明细数据' => []
  4369. ]);
  4370. }
  4371. // 获取所有涉及的设备编号
  4372. $sczlBhs = array_column($orderRecords, 'sczl_bh');
  4373. // 通过sczl_bh去电表设备列表表匹配对应的mid
  4374. $deviceMappings = Db::name('电表设备列表')
  4375. ->field('mid, collectorid, description')
  4376. ->where('description', 'in', $sczlBhs)
  4377. ->select();
  4378. $midMap = [];
  4379. $collectorIdMap = [];
  4380. foreach ($deviceMappings as $mapping) {
  4381. $midMap[$mapping['description']] = $mapping['mid'];
  4382. $collectorIdMap[$mapping['description']] = $mapping['collectorid'];
  4383. }
  4384. // 获取所有相关电表的能耗数据 - 使用mid来关联
  4385. $electricData = [];
  4386. if (!empty($midMap)) {
  4387. $mids = array_values($midMap);
  4388. $electricData = Db::name('电表能耗小时数据')
  4389. ->where('电表ID', 'in', $mids) // 这里电表ID对应的是mid
  4390. ->order('开始时间', 'asc')
  4391. ->select();
  4392. }
  4393. // 组织明细数据
  4394. $details = [];
  4395. $orderTotalElectricity = 0;
  4396. $orderTotalOutput = 0;
  4397. // 定义设备小组的固定排序
  4398. $deviceOrder = [
  4399. '裁剪' => 1,
  4400. '车缝' => 2,
  4401. '手工' => 3,
  4402. '大烫' => 4,
  4403. '总检' => 5,
  4404. '包装' => 6
  4405. ];
  4406. foreach ($orderRecords as $record) {
  4407. $sczlBh = $record['sczl_bh'];
  4408. $mid = $midMap[$sczlBh] ?? null;
  4409. $collectorId = $collectorIdMap[$sczlBh] ?? null;
  4410. $deviceElectricity = 0;
  4411. $matchedHours = 0;
  4412. $hourlyDetails = [];
  4413. if ($mid && !empty($electricData)) {
  4414. $deviceStart = strtotime($record['最早报工时间']);
  4415. $deviceEnd = strtotime($record['最晚报工时间']);
  4416. // 筛选该设备在报工期间的电表数据
  4417. foreach ($electricData as $elec) {
  4418. // 正确的比较:电表能耗数据中的电表ID应该等于设备对应的mid
  4419. if ($elec['电表ID'] != $mid) {
  4420. continue;
  4421. }
  4422. $elecStart = strtotime($elec['开始时间']);
  4423. $elecEnd = strtotime($elec['结束时间']);
  4424. // 匹配电表时间段在设备生产时间段范围内
  4425. if ($elecStart >= $deviceStart && $elecEnd <= $deviceEnd) {
  4426. $deviceElectricity += $elec['总电量'];
  4427. $matchedHours++;
  4428. $hourlyDetails[] = [
  4429. '电表时间段' => $elec['开始时间'] . ' - ' . $elec['结束时间'],
  4430. '电量' => round($elec['总电量'], 2),
  4431. '日期' => $elec['日期']
  4432. ];
  4433. }
  4434. }
  4435. }
  4436. // 如果累计用电量为空或0,跳过不显示
  4437. if (empty($deviceElectricity)) {
  4438. continue;
  4439. }
  4440. $orderTotalElectricity += $deviceElectricity;
  4441. $orderTotalOutput += $record['总产量'];
  4442. // 确定设备类型和排序权重
  4443. $deviceType = '';
  4444. $sortWeight = 999; // 默认权重,排在最后
  4445. foreach ($deviceOrder as $type => $weight) {
  4446. if (strpos($sczlBh, $type) !== false) {
  4447. $deviceType = $type;
  4448. $sortWeight = $weight;
  4449. break;
  4450. }
  4451. }
  4452. // 改进的设备序号提取方法
  4453. $deviceNumber = 0;
  4454. if (preg_match('/\d+/', $sczlBh, $matches)) {
  4455. $deviceNumber = intval($matches[0]);
  4456. }
  4457. $details[] = [
  4458. '订单编号' => $record['订单编号'],
  4459. '设备小组' => $sczlBh,
  4460. '电表ID' => $mid,
  4461. '采集器ID' => $collectorId,
  4462. '生产款号' => $orderInfo['生产款号'],
  4463. '产量' => $record['总产量'],
  4464. '累计用电量' => round($deviceElectricity, 2),
  4465. '单位电量' => $record['总产量'] > 0 ? round($deviceElectricity / $record['总产量'], 4) : 0,
  4466. '生产时间段' => $record['最早报工时间'] . ' 至 ' . $record['最晚报工时间'],
  4467. '报工次数' => $record['报工次数'],
  4468. '匹配小时数' => $matchedHours,
  4469. // 用于排序的字段
  4470. '_sort_weight' => $sortWeight,
  4471. '_device_number' => $deviceNumber,
  4472. '_device_name' => $sczlBh // 添加设备名称用于调试
  4473. ];
  4474. }
  4475. // 按照设备类型和序号排序
  4476. usort($details, function($a, $b) {
  4477. // 首先按设备类型排序
  4478. if ($a['_sort_weight'] != $b['_sort_weight']) {
  4479. return $a['_sort_weight'] - $b['_sort_weight'];
  4480. }
  4481. // 然后按设备序号排序
  4482. if ($a['_device_number'] != $b['_device_number']) {
  4483. return $a['_device_number'] - $b['_device_number'];
  4484. }
  4485. // 最后按设备名称排序(确保完全一致)
  4486. return strcmp($a['_device_name'], $b['_device_name']);
  4487. });
  4488. // 移除排序用的临时字段
  4489. foreach ($details as &$item) {
  4490. unset($item['_sort_weight']);
  4491. unset($item['_device_number']);
  4492. unset($item['_device_name']);
  4493. }
  4494. $result = [
  4495. 'list' => $details
  4496. ];
  4497. $this->success('成功', $result);
  4498. }
  4499. //成品入仓左侧菜单
  4500. public function Finished_Datalist(){
  4501. // 获取成品入仓表中的所有数据
  4502. $data = Db::name('成品入仓')
  4503. ->field('sys_rq')
  4504. ->whereNull('mod_rq')
  4505. ->select();
  4506. // 按年、年月、年月日构建嵌套数据结构
  4507. $dateData = [];
  4508. foreach ($data as $item) {
  4509. if (!empty($item['sys_rq'])) {
  4510. $date = $item['sys_rq'];
  4511. $year = date('Y', strtotime($date));
  4512. $yearMonth = date('Y-m', strtotime($date));
  4513. $yearMonthDay = date('Y-m-d', strtotime($date));
  4514. // 初始化年、年月、年月日的数据结构
  4515. if (!isset($dateData[$year])) {
  4516. $dateData[$year] = [];
  4517. }
  4518. if (!isset($dateData[$year][$yearMonth])) {
  4519. $dateData[$year][$yearMonth] = [];
  4520. }
  4521. // 添加年月日到对应年月数组中,避免重复
  4522. if (!in_array($yearMonthDay, $dateData[$year][$yearMonth])) {
  4523. $dateData[$year][$yearMonth][] = $yearMonthDay;
  4524. }
  4525. }
  4526. }
  4527. // 对年月日数组进行降序排序(最近的日期在前面)
  4528. foreach ($dateData as $year => $yearMonths) {
  4529. foreach ($yearMonths as $yearMonth => $days) {
  4530. rsort($dateData[$year][$yearMonth]);
  4531. }
  4532. // 对年月进行降序排序
  4533. krsort($dateData[$year]);
  4534. }
  4535. // 对年进行降序排序
  4536. krsort($dateData);
  4537. // 构建响应
  4538. $res['code'] = 0;
  4539. $res['msg'] = '成功';
  4540. $res['time'] = time(); // 当前时间戳
  4541. $res['data'] = $dateData;
  4542. return json($res);
  4543. }
  4544. //成品入仓列表数据
  4545. public function Finished_Product(){
  4546. if (!$this->request->isGet()) {
  4547. $this->error('请求方式错误');
  4548. }
  4549. $params = $this->request->param();
  4550. $search = input('order', '');
  4551. $page = input('page', 1, 'intval');
  4552. $limit = input('limit', 10, 'intval');
  4553. $where = [];
  4554. if (!empty($search)) {
  4555. $where['a.order|j.生产款号|j.款式'] = ['like', '%' . $search . '%'];
  4556. }
  4557. if (!empty($params['date'])) {
  4558. $where['a.sys_rq'] = ['like', "%{$params['date']}%"];
  4559. }
  4560. // 计算总记录数(去重后的订单数量)
  4561. $total = Db::name('成品入仓')->alias('a')
  4562. ->join('工单_基本资料 j', 'a.order=j.订单编号', 'left')
  4563. ->where($where)
  4564. ->group('a.order')
  4565. ->count();
  4566. // 查询数据,对相同订单分组并求和成品数量
  4567. $list = Db::name('成品入仓')->alias('a')
  4568. ->field('
  4569. a.order as 订单编号,
  4570. SUM(a.sl) as 成品数量,
  4571. j.生产款号,
  4572. j.款式,
  4573. j.订单数量
  4574. ')
  4575. ->join('工单_基本资料 j', 'a.order=j.订单编号', 'left')
  4576. ->where($where)
  4577. ->group('a.order')
  4578. ->limit(($page - 1) * $limit, $limit)
  4579. ->select();
  4580. // 计算未入仓数量和入仓率
  4581. foreach ($list as &$item) {
  4582. $item['未入仓数量'] = $item['订单数量'] - $item['成品数量'];
  4583. // 计算入仓率(成品数量 / 订单数量 * 100%),保留2位小数
  4584. $item['入仓率'] = $item['订单数量'] > 0 ? round(($item['成品数量'] / $item['订单数量']) * 100, 2) . '%' : '0%';
  4585. }
  4586. $res['code'] = 0;
  4587. $res['msg'] = '成功';
  4588. $res['count'] = $total;
  4589. $res['data'] = $list;
  4590. return json($res);
  4591. }
  4592. //面料库存列表
  4593. public function GetFabric(){
  4594. if (!$this->request->isGet()) {
  4595. $this->error('请求方式错误');
  4596. }
  4597. $params = $this->request->param();
  4598. $search = input('search', '');
  4599. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4600. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4601. $where = [];
  4602. if (!empty($search)) {
  4603. $where['物料编号|物料名称'] = ['like', '%' . $search . '%'];
  4604. }
  4605. $list = Db::name('物料_库存')
  4606. ->where($where)
  4607. ->whereNull('Mod_rq')
  4608. ->limit(($page - 1) * $limit, $limit)
  4609. ->select();
  4610. $total = Db::name('物料_库存')->whereNull('Mod_rq')->where($where) ->count();
  4611. $res['code'] = 0;
  4612. $res['msg'] = '成功';
  4613. $res['count'] = $total;
  4614. $res['data'] = $list;
  4615. return json($res);
  4616. }
  4617. //面料库存分析
  4618. public function GetAPIFabric(){
  4619. // 查询所有物料库存数据
  4620. $allItems = Db::name('物料_库存')
  4621. ->field('物料名称,库存数量,入仓总量,领用数量,退还数量,单位')
  4622. ->order('Sys_rq desc')
  4623. ->whereNull('Mod_rq')
  4624. ->select();
  4625. // 按物料名称分组并累加库存数量
  4626. $groupedData = [];
  4627. foreach ($allItems as $item) {
  4628. $materialName = $item['物料名称'];
  4629. if (!isset($groupedData[$materialName])) {
  4630. // 初始化新的物料记录
  4631. $groupedData[$materialName] = [
  4632. '物料名称' => $materialName,
  4633. '库存数量' => 0,
  4634. '入仓总量' => 0,
  4635. '领用数量' => 0,
  4636. '退还数量' => 0,
  4637. '单位' => $item['单位']
  4638. ];
  4639. }
  4640. // 累加各项数量(确保转换为数字类型)
  4641. $groupedData[$materialName]['库存数量'] += floatval($item['库存数量']);
  4642. $groupedData[$materialName]['入仓总量'] += floatval($item['入仓总量']);
  4643. $groupedData[$materialName]['领用数量'] += floatval($item['领用数量']);
  4644. $groupedData[$materialName]['退还数量'] += floatval($item['退还数量'] ?? 0);
  4645. }
  4646. // 将关联数组转换为索引数组
  4647. $sortedList = array_values($groupedData);
  4648. // 按库存数量降序排序,确保库存最多的物料显示在最前面
  4649. usort($sortedList, function($a, $b) {
  4650. return $b['库存数量'] - $a['库存数量'];
  4651. });
  4652. // 格式化数值字段,保留两位小数
  4653. foreach ($sortedList as &$item) {
  4654. $item['库存数量'] = round($item['库存数量'], 2);
  4655. $item['入仓总量'] = round($item['入仓总量'], 2);
  4656. $item['领用数量'] = round($item['领用数量'], 2);
  4657. $item['退还数量'] = round($item['退还数量'], 2);
  4658. }
  4659. // 限制只返回前20个物料
  4660. $limitedList = array_slice($sortedList, 0, 20);
  4661. $res['code'] = 0;
  4662. $res['msg'] = '成功';
  4663. $res['data'] = $limitedList;
  4664. return json($res);
  4665. }
  4666. //Bom资料列表
  4667. public function Get_BomList(){
  4668. if (!$this->request->isGet()) {
  4669. $this->error('请求方式错误');
  4670. }
  4671. $params = $this->request->param();
  4672. $search = input('search', '');
  4673. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4674. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4675. $where = [];
  4676. if (!empty($search)) {
  4677. $where['a.BOM_工单编号|a.物料分类|a.BOM_desc'] = ['like', '%' . $search . '%'];
  4678. }
  4679. $list = Db::name('工单_bom资料')->alias('a')
  4680. ->field('
  4681. a.BOM_工单编号 as 订单编号,
  4682. a.物料分类,
  4683. a.BOM_物料名称 as 物料名称,
  4684. a.BOM_计划用量 as 计划用料,
  4685. a.BOM_计划门幅 as 计划门幅,
  4686. a.BOM_标准用量 as 定额用料,
  4687. a.BOM_定额门幅 as 定额门幅,
  4688. a.BOM_desc as 备注,
  4689. j.生产款号,
  4690. j.款式
  4691. ')
  4692. ->join('工单_基本资料 j', 'a.BOM_工单编号 = j.订单编号', 'left')
  4693. ->where($where)
  4694. ->limit(($page - 1) * $limit, $limit)
  4695. ->order('a.Sys_rq desc')
  4696. ->whereNull('a.Mod_rq')
  4697. ->select();
  4698. $total = Db::name('工单_bom资料')->alias('a')
  4699. ->whereNull('Mod_rq')
  4700. ->where($where)
  4701. ->count();
  4702. $res['code'] = 0;
  4703. $res['msg'] = '成功';
  4704. $res['count'] = $total;
  4705. $res['data'] = $list;
  4706. return json($res);
  4707. }
  4708. //查询订单进度情况
  4709. public function GetOrderprogress(){
  4710. if (!$this->request->isGet()) {
  4711. $this->error('请求方式错误');
  4712. }
  4713. $params = $this->request->param();
  4714. $search = input('search', '');
  4715. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4716. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4717. $where = [];
  4718. if (!empty($search)) {
  4719. $where['a.订单编号|a.客户编号|a.生产款号|a.款式'] = ['like', '%' . $search . '%'];
  4720. }
  4721. // 获取所有订单基本信息(先分页)
  4722. $orders = Db::name('工单_基本资料')->alias('a')
  4723. ->field('
  4724. a.订单编号,
  4725. a.客户编号,
  4726. a.生产款号,
  4727. a.款式,
  4728. a.img,
  4729. a.订单数量
  4730. ')
  4731. ->whereNull('a.Mod_rq')
  4732. ->where($where)
  4733. ->limit(($page - 1) * $limit, $limit)
  4734. ->order('a.Sys_rq desc')
  4735. ->select();
  4736. $total = Db::name('工单_基本资料')->alias('a')
  4737. ->whereNull('Mod_rq')
  4738. ->where($where)
  4739. ->count();
  4740. if (empty($orders)) {
  4741. $res['code'] = 0;
  4742. $res['msg'] = '成功';
  4743. $res['count'] = $total;
  4744. $res['data'] = [];
  4745. return json($res);
  4746. }
  4747. // 提取订单编号列表
  4748. $orderNumbers = array_column($orders, '订单编号');
  4749. // 获取这些订单的所有报工数据
  4750. $reportData = Db::name('设备_产量计酬')->alias('c')
  4751. ->field('
  4752. c.订单编号,
  4753. c.工序名称,
  4754. CASE
  4755. WHEN c.工序名称 IN ("裁剪", "车缝") THEN c.数量
  4756. ELSE c.s_num
  4757. END as 报工数量,
  4758. c.sczl_bh as 报工小组
  4759. ')
  4760. ->whereIn('c.订单编号', $orderNumbers)
  4761. ->whereNull('c.mod_rq')
  4762. ->select();
  4763. // 按订单编号和工序名称分组处理数据
  4764. $orderProcessReportMap = [];
  4765. foreach ($reportData as $item) {
  4766. $orderNo = $item['订单编号'];
  4767. $processName = $item['工序名称'];
  4768. if (!isset($orderProcessReportMap[$orderNo])) {
  4769. $orderProcessReportMap[$orderNo] = [
  4770. '工序列表' => [],
  4771. '工序报工数量' => [],
  4772. '工序报工小组' => [],
  4773. ];
  4774. }
  4775. // 初始化该工序的数据
  4776. if (!isset($orderProcessReportMap[$orderNo]['工序报工数量'][$processName])) {
  4777. $orderProcessReportMap[$orderNo]['工序报工数量'][$processName] = 0;
  4778. $orderProcessReportMap[$orderNo]['工序报工小组'][$processName] = [];
  4779. }
  4780. // 累加各工序的报工数量
  4781. $orderProcessReportMap[$orderNo]['工序报工数量'][$processName] += $item['报工数量'];
  4782. // 收集该工序的报工小组(去重)
  4783. if (!in_array($item['报工小组'], $orderProcessReportMap[$orderNo]['工序报工小组'][$processName])) {
  4784. $orderProcessReportMap[$orderNo]['工序报工小组'][$processName][] = $item['报工小组'];
  4785. }
  4786. }
  4787. // 将报工数据合并到订单数据中
  4788. $result = [];
  4789. foreach ($orders as $order) {
  4790. $orderNo = $order['订单编号'];
  4791. if (isset($orderProcessReportMap[$orderNo])) {
  4792. $report = $orderProcessReportMap[$orderNo];
  4793. // 将每个工序的名称和数量作为单独的字段
  4794. foreach ($report['工序报工数量'] as $process => $quantity) {
  4795. $order[$process] = $quantity;
  4796. }
  4797. // 将每个工序的报工小组作为单独的字段
  4798. foreach ($report['工序报工小组'] as $process => $groups) {
  4799. $order[$process . '小组'] = implode(',', $groups);
  4800. }
  4801. }
  4802. $result[] = $order;
  4803. }
  4804. $res['code'] = 0;
  4805. $res['msg'] = '成功';
  4806. $res['count'] = $total;
  4807. $res['data'] = $result;
  4808. return json($res);
  4809. }
  4810. public function Getvideolist(){
  4811. if (!$this->request->isGet()) {
  4812. $this->error('请求方式错误');
  4813. }
  4814. $params = $this->request->param();
  4815. $search = input('search', '');
  4816. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4817. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4818. $where = [];
  4819. if (!empty($search)) {
  4820. $where['prompt'] = ['like', '%' . $search . '%'];
  4821. }
  4822. $list = Db::name('video')->where('mod_rq', null)
  4823. ->where($where)
  4824. ->order('id desc')
  4825. ->limit(($page - 1) * $limit, $limit)
  4826. ->select();
  4827. $total = Db::name('video')->where('mod_rq', null)
  4828. ->where($where)
  4829. ->count();
  4830. $res['code'] = 0;
  4831. $res['msg'] = '成功';
  4832. $res['count'] = $total;
  4833. $res['data'] = $list;
  4834. return json($res);
  4835. }
  4836. //video_691c078dbb648190a17625bbef815ce50cbc1621ce1702d7
  4837. public function video()
  4838. {
  4839. $params = $this->request->param();
  4840. $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
  4841. $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
  4842. $postData = [
  4843. 'prompt' => $params['prompt'],
  4844. 'model' => $params['model'],
  4845. 'seconds' => $params['seconds'],
  4846. 'size' => $params['size'],
  4847. ];
  4848. // 初始化CURL
  4849. $ch = curl_init();
  4850. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  4851. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  4852. curl_setopt($ch, CURLOPT_POST, true);
  4853. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  4854. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  4855. 'Authorization: Bearer ' . $apiKey
  4856. ]);
  4857. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  4858. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  4859. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  4860. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  4861. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  4862. // 创建临时文件来捕获详细的cURL输出
  4863. $verbose = fopen('php://temp', 'w+');
  4864. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  4865. // 执行请求
  4866. $response = curl_exec($ch);
  4867. //HTTP状态码
  4868. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  4869. // 获取详细的cURL调试信息
  4870. rewind($verbose);
  4871. //CURL调试信息
  4872. $verboseLog = stream_get_contents($verbose);
  4873. fclose($verbose);
  4874. // 分离头部和主体
  4875. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  4876. //响应头部
  4877. $header = substr($response, 0, $header_size);
  4878. //响应主体
  4879. $body = substr($response, $header_size);
  4880. // 检查CURL错误
  4881. $curlError = curl_error($ch);
  4882. curl_close($ch);
  4883. $responseData = json_decode($body, true);
  4884. // 检查API是否返回了错误信息
  4885. if (isset($responseData['error'])) {
  4886. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  4887. return json([
  4888. 'code' => 1,
  4889. 'msg' => '视频生成请求失败',
  4890. 'data' => [
  4891. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  4892. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  4893. 'error_message' => $errorMessage
  4894. ]
  4895. ]);
  4896. }
  4897. // 检查是否有自定义错误格式
  4898. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  4899. return json([
  4900. 'code' => 1,
  4901. 'msg' => '视频生成请求失败',
  4902. 'data' => [
  4903. 'error_code' => $responseData['code'],
  4904. 'error_message' => $responseData['message']
  4905. ]
  4906. ]);
  4907. }
  4908. // 检查是否存在id字段
  4909. if (!isset($responseData['id'])) {
  4910. return json([
  4911. 'code' => 1,
  4912. 'msg' => '无法获取视频ID',
  4913. 'data' => [
  4914. 'response_data' => $responseData,
  4915. 'http_code' => $httpCode
  4916. ]
  4917. ]);
  4918. }
  4919. $videoData = [
  4920. 'video_id' => $responseData['id'],
  4921. 'prompt' => $postData['prompt'],
  4922. 'model' => $postData['model'],
  4923. 'seconds' => $postData['seconds'],
  4924. 'size' => $postData['size'],
  4925. 'sys_rq' => date("Y-m-d H:i:s")
  4926. ];
  4927. // 尝试插入数据
  4928. try {
  4929. $res = Db::name('video')->insert($videoData);
  4930. return json([
  4931. 'code' => 0,
  4932. 'msg' => '视频正在生成中',
  4933. 'data' => [
  4934. 'video_id' => $responseData['id'],
  4935. 'insert_result' => $res
  4936. ]
  4937. ]);
  4938. } catch (Exception $e) {
  4939. return json([
  4940. 'code' => 1,
  4941. 'msg' => '数据库操作失败',
  4942. 'data' => [
  4943. 'error_message' => $e->getMessage()
  4944. ]
  4945. ]);
  4946. }
  4947. }
  4948. /**
  4949. * 获取视频内容
  4950. * 下载已完成的视频内容
  4951. */
  4952. public function videoContent(){
  4953. // 从请求参数获取video_id,如果没有则使用默认值
  4954. $video_id = input('get.video_id');
  4955. $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
  4956. // 1. 先检查视频状态
  4957. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
  4958. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  4959. // 检查视频状态
  4960. if ($statusData['status'] !== 'completed') {
  4961. return json([
  4962. 'code' => 202,
  4963. 'msg' => '视频尚未生成完成',
  4964. 'data' => [
  4965. 'video_id' => $video_id,
  4966. 'status' => $statusData['status'],
  4967. 'progress' => $statusData['progress'],
  4968. 'created_at' => $statusData['created_at'],
  4969. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  4970. ]
  4971. ]);
  4972. }
  4973. // 2. 视频生成完成,准备下载
  4974. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
  4975. // 获取可选的variant参数
  4976. $variant = input('get.variant', '');
  4977. if (!empty($variant)) {
  4978. $apiUrl .= '?variant=' . urlencode($variant);
  4979. }
  4980. // 创建保存目录
  4981. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  4982. if (!is_dir($saveDir)) {
  4983. mkdir($saveDir, 0755, true);
  4984. }
  4985. // 生成唯一文件名
  4986. $filename = $video_id . '.mp4';
  4987. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  4988. $fullPath = $saveDir . DS . $filename;
  4989. // 3. 下载视频
  4990. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  4991. // 4. 保存视频文件
  4992. if (file_put_contents($fullPath, $videoData) === false) {
  4993. throw new Exception('视频保存失败');
  4994. }
  4995. // 确保路径使用正斜杠,并只保存相对路径部分
  4996. $localPath = str_replace('\\', '/', $localPath);
  4997. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  4998. $savePath = ltrim($localPath, '/');
  4999. // 将正确格式的文件路径存入数据库
  5000. Db::name('video')->where('video_id', $video_id)->update([
  5001. 'web_url' => $savePath
  5002. ]);
  5003. // 返回成功响应
  5004. return json([
  5005. 'code' => 0,
  5006. 'msg' => '视频下载成功',
  5007. 'data' => [
  5008. 'video_id' => $video_id,
  5009. 'local_path' => $localPath,
  5010. 'web_url' => $savePath,
  5011. 'file_size' => filesize($fullPath)
  5012. ]
  5013. ]);
  5014. }
  5015. /**
  5016. * 获取视频状态
  5017. */
  5018. private function fetchVideoStatus($url, $apiKey) {
  5019. $ch = curl_init();
  5020. curl_setopt($ch, CURLOPT_URL, $url);
  5021. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  5022. curl_setopt($ch, CURLOPT_HTTPGET, true);
  5023. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  5024. 'Authorization: Bearer ' . $apiKey,
  5025. 'Accept: application/json'
  5026. ]);
  5027. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  5028. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  5029. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  5030. $response = curl_exec($ch);
  5031. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  5032. $error = curl_error($ch);
  5033. curl_close($ch);
  5034. if ($error) {
  5035. throw new Exception('获取视频状态失败: ' . $error);
  5036. }
  5037. if ($httpCode < 200 || $httpCode >= 300) {
  5038. throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
  5039. }
  5040. $data = json_decode($response, true);
  5041. if (!is_array($data)) {
  5042. throw new Exception('视频状态数据格式错误');
  5043. }
  5044. return $data;
  5045. }
  5046. /**
  5047. * 下载视频文件
  5048. */
  5049. private function downloadVideo($url, $apiKey) {
  5050. $ch = curl_init();
  5051. curl_setopt($ch, CURLOPT_URL, $url);
  5052. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  5053. curl_setopt($ch, CURLOPT_HTTPGET, true);
  5054. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  5055. 'Authorization: Bearer ' . $apiKey
  5056. ]);
  5057. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  5058. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  5059. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  5060. $response = curl_exec($ch);
  5061. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  5062. $error = curl_error($ch);
  5063. curl_close($ch);
  5064. if ($error) {
  5065. throw new Exception('视频下载失败: ' . $error);
  5066. }
  5067. if ($httpCode < 200 || $httpCode >= 300) {
  5068. throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
  5069. }
  5070. return $response;
  5071. }
  5072. /**
  5073. * 获取产品款式列表
  5074. * @return \think\response\Json
  5075. * @throws \think\db\exception\DataNotFoundException
  5076. */
  5077. public function getProductStyleList()
  5078. {
  5079. if (!$this->request->isGet()) {
  5080. $this->error('请求方式错误');
  5081. }
  5082. $list = db('产品_基本资料')
  5083. ->whereNotNull('product_type')
  5084. ->where('product_type', '<>', '')
  5085. ->field('product_type')
  5086. ->distinct(true)
  5087. ->order('product_type asc')
  5088. ->column('product_type');
  5089. $this->success('成功', $list);
  5090. }
  5091. /**
  5092. * 修改订单备注和完工日期
  5093. * @param id 工单ID
  5094. * @param remark 备注
  5095. * @param finish_date 工单完工日期
  5096. * @param sys_id 操作人
  5097. */
  5098. public function updateOrderRemarkAndFinishDate()
  5099. {
  5100. if (!$this->request->isPost()) {
  5101. $this->error('请求方式错误');
  5102. }
  5103. $params = $this->request->post();
  5104. if (empty($params['id'])) {
  5105. $this->error('工单ID不能为空');
  5106. }
  5107. if (empty($params['sys_id'])) {
  5108. $this->error('操作人不能为空');
  5109. }
  5110. $workOrder = Db::table('工单_基本资料')
  5111. ->where('Uniqid', intval($params['id']))
  5112. ->whereNull('Mod_rq')
  5113. ->field('Uniqid,订单编号,remark,工单完工日期')
  5114. ->find();
  5115. if (empty($workOrder)) {
  5116. $this->error('工单不存在');
  5117. }
  5118. $remark = isset($params['remark']) ? $params['remark'] : '';
  5119. $finishDate = isset($params['工单完工日期']) ? $params['工单完工日期'] : '';
  5120. $updateData = [];
  5121. $logList = [];
  5122. $operTime = date('Y-m-d H:i:s');
  5123. $orderNo = $workOrder['订单编号'];
  5124. $fieldMap = [
  5125. 'remark' => ['label' => '备注', 'new' => $remark],
  5126. '工单完工日期' => ['label' => '工单完工日期', 'new' => $finishDate],
  5127. ];
  5128. foreach ($fieldMap as $field => $item) {
  5129. $oldValue = isset($workOrder[$field]) ? $workOrder[$field] : '';
  5130. $newValue = $item['new'];
  5131. if ((string)$oldValue === (string)$newValue) {
  5132. continue;
  5133. }
  5134. $updateData[$field] = $newValue;
  5135. $logList[] = [
  5136. 'order_no' => $orderNo,
  5137. 'change_field' => $item['label'],
  5138. 'old_value' => $oldValue === null ? '' : (string)$oldValue,
  5139. 'new_value' => (string)$newValue,
  5140. 'oper_type' => '修改工单备注和完工日期',
  5141. 'oper_user_name' => $params['sys_id'],
  5142. 'oper_time' => $operTime,
  5143. ];
  5144. }
  5145. if (empty($updateData)) {
  5146. $this->error('数据未发生变化');
  5147. }
  5148. Db::startTrans();
  5149. try {
  5150. $updateSql = Db::table('工单_基本资料')
  5151. ->where('Uniqid', intval($params['id']))
  5152. ->whereNull('Mod_rq')
  5153. ->fetchSql(true)
  5154. ->update($updateData);
  5155. $updateResult = db()->query($updateSql);
  5156. if ($updateResult === false) {
  5157. throw new \Exception('更新工单失败');
  5158. }
  5159. if ($updateResult === 0) {
  5160. throw new \Exception('未找到可更新的工单');
  5161. }
  5162. $logResult = Db::name('work_order_operation_log')->insertAll($logList);
  5163. if ($logResult === false || $logResult === 0) {
  5164. throw new \Exception('写入操作日志失败');
  5165. }
  5166. Db::commit();
  5167. } catch (\think\exception\HttpResponseException $e) {
  5168. throw $e;
  5169. } catch (\Exception $e) {
  5170. Db::rollback();
  5171. $this->error('修改失败:' . $e->getMessage());
  5172. }
  5173. $this->success('修改成功');
  5174. }
  5175. }