WorkOrder.php 218 KB

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