WorkOrder.php 226 KB

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