WorkOrder.php 217 KB

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