WorkOrder.php 230 KB

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