WorkOrder.php 224 KB

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