WorkOrder.php 225 KB

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