WorkOrder.php 224 KB

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