WorkOrder.php 219 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776
  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. // 仅入库:按工单+物料名称汇总 number;多条入库时 rq 取最大(最后入库日)
  1773. $inboundSub = \db('库存_出入库明细')
  1774. ->where('name', '入库')
  1775. ->whereNull('Mod_rq')
  1776. ->field('order_id, 物料名称, SUM(`number`) as 入库数量, MAX(rq) as 实际入库时间')
  1777. ->group('order_id, 物料名称')
  1778. ->buildSql();
  1779. $list = \db('工单_bom资料')
  1780. ->alias('a')
  1781. ->join('工单_基本资料 b', 'b.订单编号 = a.BOM_工单编号')
  1782. ->join([$inboundSub => 'c'], 'a.BOM_工单编号 = c.order_id AND a.BOM_物料名称 = c.物料名称', 'LEFT')
  1783. ->field('a.BOM_工单编号 as 订单编号,b.生产款号 as 生产款号,b.客户编号 as 客户编号,b.款式 as 款式,
  1784. a.BOM_物料名称 as 物料名称,a.BOM_投料单位 as 投料单位,a.BOM_计划用量 as 计划用料,a.BOM_标准用量 as 定额用料,
  1785. a.计划入库时间,
  1786. a.计划入库操作人,
  1787. b.审核日期 as 核批日期,
  1788. b.审核 as 核批人,
  1789. a.BOM_实际用量 as 裁床实际用料,a.BOM_desc as 备注,a.UNIQID,a.物料分类,
  1790. a.BOM_计划门幅 as 计划门幅, a.BOM_定额门幅 as 定额门幅,a.Sys_ID as ID,a.Sys_rq as 日期,
  1791. c.实际入库时间,c.入库数量')
  1792. ->where($where)
  1793. ->whereNull('a.Mod_rq')
  1794. ->order('a.UNIQID desc')
  1795. ->select();
  1796. if (!empty($list)) {
  1797. // 获取去重后的物料名称
  1798. $materialNames = array_column($list, '物料名称');
  1799. $materialNames = array_unique($materialNames);
  1800. // 根据去重后的物料名称查询工单_面料资料表,并获取BOM_desc
  1801. $materialDetails = \db('工单_面料资料')
  1802. ->field('BOM_物料名称 as 物料名称,BOM_desc')
  1803. ->whereIn('BOM_物料名称', $materialNames)
  1804. ->select();
  1805. // 将物料名称与BOM_desc对应起来
  1806. $materialDescMap = [];
  1807. foreach ($materialDetails as $detail) {
  1808. $materialDescMap[$detail['物料名称']] = $detail['BOM_desc'];
  1809. }
  1810. // 在list中添加对应的BOM_desc
  1811. foreach ($list as &$item) {
  1812. if (isset($materialDescMap[$item['物料名称']])) {
  1813. $item['BOM_desc'] = $materialDescMap[$item['物料名称']];
  1814. } else {
  1815. $item['BOM_desc'] = '';
  1816. }
  1817. }
  1818. $this->success('成功', $list);
  1819. } else {
  1820. $this->GdGtpAiOrder($param['order']);
  1821. $this->success('没有找到相关数据',[]);
  1822. // return $this->success('没有找到相关数据', []);
  1823. }
  1824. }
  1825. /**
  1826. * Bom资料删除
  1827. * */
  1828. public function Bomdel(){
  1829. if ($this->request->isGet() === false) {
  1830. $this->error('请求错误');
  1831. }
  1832. $param = $this->request->param();
  1833. if (empty($param) || !isset($param['UNIQID'])) {
  1834. $this->error('参数错误');
  1835. }
  1836. $uniqids = strpos($param['UNIQID'], ',') !== false ? explode(',', $param['UNIQID']) : [$param['UNIQID']];
  1837. $where = [];
  1838. $where['Mod_rq'] = date('Y-m-d H:i:s', time());
  1839. $allUpdated = true;
  1840. $failedUniqids = [];
  1841. // 遍历所有UNIQID并更新数据库
  1842. foreach ($uniqids as $uniqid) {
  1843. $list = \db('工单_bom资料')
  1844. ->where('UNIQID', $uniqid)
  1845. ->find();
  1846. $cangku = Db::name('库存_出入库明细')
  1847. ->where('order_id',$list['BOM_工单编号'])
  1848. ->where('物料名称',$list['BOM_物料名称'])
  1849. ->whereNull('Mod_rq')
  1850. ->find();
  1851. if ($cangku) {
  1852. return json([
  1853. 'code' => 1,
  1854. 'msg' => '【物料名称】:' . $list['BOM_物料名称'] . '。该物料仓库已录入,暂无法删除。如需删除,请联系仓库人员清除相关明细数据后再进行操作。'
  1855. ])->options(['json_encode_param' => JSON_UNESCAPED_UNICODE]);
  1856. }
  1857. $result = \db('工单_bom资料')
  1858. ->where('UNIQID', $uniqid)
  1859. ->update($where);
  1860. $arr = \db('工单_面料资料')
  1861. ->where('BOM_工单编号', $list['BOM_工单编号'])
  1862. ->where('BOM_物料名称', $list['BOM_物料名称'])
  1863. ->update($where);
  1864. $arr = \db('工单关联表')
  1865. ->where('订单编号', $list['BOM_工单编号'])
  1866. ->where('物料名称', $list['BOM_物料名称'])
  1867. ->update($where);
  1868. if (!$result) {
  1869. // 如果某个UNIQID更新失败,记录失败的ID
  1870. $allUpdated = false;
  1871. $failedUniqids[] = $uniqid;
  1872. }
  1873. }
  1874. if ($allUpdated) {
  1875. $list = \db('工单_bom资料')
  1876. ->whereIn('UNIQID', $uniqids)
  1877. ->select();
  1878. if (!empty($list)) {
  1879. $this->success('删除成功');
  1880. } else {
  1881. $this->GdGtpAiOrder($param['order']);
  1882. return $this->success('没有找到相关数据', []);
  1883. }
  1884. } else {
  1885. $this->error('部分更新失败,无法更新以下UNIQID: ' . implode(', ', $failedUniqids));
  1886. }
  1887. }
  1888. /**
  1889. * 前端选择订单时如果BOM资料数据为空则单独调用,重新生成最新
  1890. */
  1891. public function GdGtpAiOrder($order){
  1892. // 判断是否有指定的订单号
  1893. if (!empty($order)) {
  1894. // 查询单个订单的最大编号
  1895. $maxOrder = \db('工单_基本资料')
  1896. ->where('订单编号', 'like', "{$order}%")
  1897. ->order('订单编号', 'desc')
  1898. ->limit(1)
  1899. ->value('订单编号');
  1900. // 查询该订单的基本资料
  1901. $list = \db('工单_基本资料')
  1902. ->where('订单编号', 'like', "{$order}%")
  1903. ->order('订单编号', 'desc')
  1904. ->limit(1)
  1905. ->find();
  1906. // 如果面料数据为空,提示错误
  1907. if (empty($list['面料'])) {
  1908. $this->error('面料数据为空无法定义BOM');
  1909. }
  1910. // 处理订单编号
  1911. $numericPart = substr($maxOrder, 2);
  1912. $newNumericPart = str_pad((int)$numericPart + 1, strlen($numericPart), '0', STR_PAD_LEFT);
  1913. $param['订单编号'] = $order . $newNumericPart;
  1914. // 处理物料信息
  1915. $massage = empty($list['粘衬']) || $list['粘衬'] == '无' ? $list['面料'] : $list['面料'] . ',粘衬:' . $list['粘衬'];
  1916. $materialCategories = [];
  1917. $pattern = '/(\S+?):([^,]+)/'; // 匹配 类别:物料 格式
  1918. preg_match_all($pattern, $massage, $matches, PREG_SET_ORDER);
  1919. foreach ($matches as $match) {
  1920. $category = $match[1]; // 分类名称
  1921. $materials = explode('+', $match[2]); // 如果物料名称中有‘+’,则分开处理多个物料
  1922. // 将分类和对应的物料添加到数组中
  1923. foreach ($materials as $material) {
  1924. $materialCategories[$category][] = trim($material); // 去除物料两边的空格
  1925. }
  1926. }
  1927. $mianliao = $this->Gpt($massage);
  1928. $data = [];
  1929. // if ($mianliao) {
  1930. // $this->success('成功');
  1931. // }
  1932. foreach ($mianliao as $value) {
  1933. if (!empty($value) && $value !== '粘衬') { // 排除空值和粘衬
  1934. $category = '';
  1935. // 查找物料对应的分类
  1936. foreach ($materialCategories as $cat => $materials) {
  1937. if (in_array($value, $materials)) {
  1938. $category = $cat;
  1939. break;
  1940. }
  1941. }
  1942. // 如果找到分类,将数据存入BOM
  1943. $data[] = [
  1944. 'BOM_工单编号' => $list['订单编号'],
  1945. 'BOM_物料名称' => $value,
  1946. 'BOM_desc' => '',
  1947. '物料分类' => $category ? $category : '',
  1948. 'Sys_rq' => date('Y-m-d H:i:s'),
  1949. 'Sys_ID' => $list['Sys_id']
  1950. ];
  1951. }
  1952. }
  1953. foreach ($data as &$item) {
  1954. if (empty($item['物料分类'])) {
  1955. $item['物料分类'] = '';
  1956. }
  1957. // 去除所有非汉字字符
  1958. $item['物料分类'] = preg_replace('/[^\p{Han}]/u', '', $item['物料分类']);
  1959. }
  1960. // 批量插入BOM资料
  1961. if (!empty($data)) {
  1962. \db('工单_bom资料')->insertAll($data);
  1963. }
  1964. $this->success('成功',$order);
  1965. } else {
  1966. // 如果没有指定订单号,批量查询订单号并处理
  1967. $has_bom = \db('工单_bom资料')->alias('a')->field('a.BOM_工单编号')->group('a.BOM_工单编号')->select();
  1968. $all_orders = \db('工单_基本资料')->alias('a')->field('a.订单编号')->where('a.面料', '<>', '')->group('a.订单编号')->select();
  1969. // 提取有BOM资料的订单号
  1970. $has_bom_orders = array_column($has_bom, 'BOM_工单编号');
  1971. // 筛选出没有对应BOM资料的订单号
  1972. $no_bom_orders = array_filter($all_orders, function ($order) use ($has_bom_orders) {
  1973. return !in_array($order['订单编号'], $has_bom_orders);
  1974. });
  1975. // 遍历没有BOM资料的订单
  1976. foreach ($no_bom_orders as $orderData) {
  1977. // 获取该订单号的最大订单编号
  1978. $maxOrder = \db('工单_基本资料')
  1979. ->where('订单编号', 'like', "{$orderData['订单编号']}%")
  1980. ->order('订单编号', 'desc')
  1981. ->limit(1)
  1982. ->value('订单编号');
  1983. // 获取该订单号的具体数据
  1984. $list = \db('工单_基本资料')
  1985. ->where('订单编号', 'like', "{$orderData['订单编号']}%")
  1986. ->order('订单编号', 'desc')
  1987. ->limit(1)
  1988. ->find();
  1989. if (empty($list['面料'])) {
  1990. $this->error("订单 {$orderData['订单编号']} 面料数据为空,无法定义BOM");
  1991. }
  1992. // 处理订单编号
  1993. $numericPart = substr($maxOrder, 2);
  1994. $newNumericPart = str_pad((int)$numericPart + 1, strlen($numericPart), '0', STR_PAD_LEFT);
  1995. $param['订单编号'] = $order . $newNumericPart;
  1996. // // 处理物料信息
  1997. // $massage = empty($list['粘衬']) || $list['粘衬'] == '无' ? $list['面料'] : $list['面料'] . ',粘衬:' . $list['粘衬'];
  1998. // $mianliao = $this->Gpt($massage);
  1999. // // 插入物料数据
  2000. // $data = [];
  2001. // foreach ($mianliao as $key => $value) {
  2002. // if (!empty($value) && $value !== '粘衬') { // 排除空值和粘衬
  2003. // $data[] = [
  2004. // 'BOM_工单编号' => $list['订单编号'],
  2005. // 'BOM_物料名称' => $value,
  2006. // 'BOM_desc' => '',
  2007. // '物料分类' => '',
  2008. // 'Sys_rq' => date('Y-m-d H:i:s'),
  2009. // 'Sys_ID' => '超级管理员'
  2010. // ];
  2011. // }
  2012. // }
  2013. // 假设massage是从数据库获取的数据
  2014. $massage = empty($list['粘衬']) || $list['粘衬'] == '无' ? $list['面料'] : $list['面料'] . ',粘衬:' . $list['粘衬'];
  2015. $materialCategories = [];
  2016. $pattern = '/(\S+?):([^,]+)/'; // 匹配 类别:物料 格式
  2017. preg_match_all($pattern, $massage, $matches, PREG_SET_ORDER);
  2018. foreach ($matches as $match) {
  2019. $category = $match[1]; // 分类名称
  2020. $materials = explode('+', $match[2]); // 如果物料名称中有‘+’,则分开处理多个物料
  2021. // 将分类和对应的物料添加到数组中
  2022. foreach ($materials as $material) {
  2023. $materialCategories[$category][] = trim($material); // 去除物料两边的空格
  2024. }
  2025. }
  2026. $mianliao = $this->Gpt($massage);
  2027. $data = [];
  2028. foreach ($mianliao as $value) {
  2029. if (!empty($value) && $value !== '粘衬') { // 排除空值和粘衬
  2030. $category = '';
  2031. // 查找物料对应的分类
  2032. foreach ($materialCategories as $cat => $materials) {
  2033. if (in_array($value, $materials)) {
  2034. $category = $cat;
  2035. break;
  2036. }
  2037. }
  2038. // 如果找到分类,将数据存入BOM
  2039. $data[] = [
  2040. 'BOM_工单编号' => $list['订单编号'],
  2041. 'BOM_物料名称' => $value,
  2042. 'BOM_desc' => '',
  2043. '物料分类' => $category ? $category : '',
  2044. 'Sys_rq' => date('Y-m-d H:i:s'),
  2045. 'Sys_ID' => '超级管理员'
  2046. ];
  2047. }
  2048. }
  2049. foreach ($data as &$item) {
  2050. if (empty($item['物料分类'])) {
  2051. $item['物料分类'] = '';
  2052. }
  2053. // 去除所有非汉字字符
  2054. $item['物料分类'] = preg_replace('/[^\p{Han}]/u', '', $item['物料分类']);
  2055. }
  2056. // 批量插入BOM资料
  2057. if (!empty($data)) {
  2058. \db('工单_bom资料')->insertAll($data);
  2059. }
  2060. }
  2061. $this->success('成功');
  2062. }
  2063. }
  2064. /**
  2065. * 订单面料修改接口
  2066. */
  2067. public function FabricEdit()
  2068. {
  2069. if ($this->request->isPost() === false){
  2070. $this->error('请求错误');
  2071. }
  2072. $param = Request::instance()->post();
  2073. if (empty($param)){$this->error('请求错误');}
  2074. if(empty($param[0]['BOM_工单编号'])){$this->error('请求错误,请重新打开此页面');}
  2075. foreach ($param as $key => $value){
  2076. $data = $value;
  2077. unset($data['UNIQID']);
  2078. // 更新操作
  2079. if (!empty($value['UNIQID'])) {
  2080. // 查询旧数据
  2081. $oldData = \db('工单_bom资料')
  2082. ->where('UNIQID', $value['UNIQID'])
  2083. ->find();
  2084. // 日志记录逻辑
  2085. if ($oldData) {
  2086. foreach ($data as $field => $newValue) {
  2087. $oldValue = $oldData[$field] ?? null;
  2088. if ($oldValue != $newValue) {
  2089. $bom_sql = \db('工单_bom修改日志')
  2090. ->fetchSql(true)
  2091. ->insert([
  2092. '订单编号' => $oldData['BOM_工单编号'],
  2093. '字段' => $field,
  2094. '修改前数据' => $oldValue,
  2095. '修改后数据' => $newValue,
  2096. '修改人' => $param[0]['Sys_ID'],
  2097. '修改时间' => date('Y-m-d H:i:s'),
  2098. 'UNIQID' => $value['UNIQID'],
  2099. '物料名称' => $oldData['BOM_物料名称'],
  2100. ]);
  2101. $bom_res = \db()->query($bom_sql);
  2102. if ($bom_res === false) {
  2103. $this->error('日志写入失败');
  2104. }
  2105. }
  2106. }
  2107. }
  2108. $sql = \db('工单_bom资料')
  2109. ->where('UNIQID', $value['UNIQID'])
  2110. ->fetchSql(true)
  2111. ->update($data);
  2112. $res = \db()->query($sql);
  2113. }else {
  2114. $sql = \db('工单_bom资料')
  2115. ->fetchSql(true)
  2116. ->insert($value);
  2117. $res = \db()->query($sql);
  2118. }
  2119. if ($res === false){
  2120. $this->error('修改失败');
  2121. }
  2122. }
  2123. $orderList = \db('工单_基本资料')
  2124. ->field('订单编号, 生产款号, Sys_id')
  2125. ->where('订单编号', $param[0]['BOM_工单编号'])
  2126. ->find();
  2127. if (!$orderList) {
  2128. $this->error('工单基本资料未找到');
  2129. }
  2130. $colorList = \db('工单_印件资料')
  2131. ->field('颜色备注')
  2132. ->where('订单编号', $orderList['订单编号'])
  2133. ->group('颜色备注')
  2134. ->select();
  2135. $BomList = \db('工单_bom资料')
  2136. ->where('BOM_工单编号', $orderList['订单编号'])
  2137. ->whereNull('Mod_rq')
  2138. ->select();
  2139. if (!$BomList) {
  2140. $this->error('BOM 面料数据未找到');
  2141. }
  2142. $AssociatedNumber = \db('工单关联表')->order('关联编号 desc')->value('关联编号');
  2143. $number = empty($AssociatedNumber) ? 0 : (int)substr($AssociatedNumber, 4);
  2144. $MaterielList = [];
  2145. $MaterielLists = [];
  2146. $colorCounter = [];
  2147. foreach ($colorList as $color) {
  2148. $colorName = $color['颜色备注'];
  2149. $colorCounter[$colorName] = 1;
  2150. foreach ($BomList as $bom) {
  2151. $wulbm = $orderList['生产款号'] . '-' . $colorName . $colorCounter[$colorName]++;
  2152. $existsMateriel = \db('工单_面料资料')
  2153. ->where([
  2154. 'BOM_工单编号' => $orderList['订单编号'],
  2155. 'BOM_颜色' => $colorName,
  2156. 'BOM_物料名称' => $bom['BOM_物料名称']
  2157. ])
  2158. ->find();
  2159. if (!$existsMateriel) {
  2160. $MaterielList[] = [
  2161. 'BOM_工单编号' => $orderList['订单编号'],
  2162. 'BOM_颜色' => $colorName,
  2163. 'BOM_物料名称' => $bom['BOM_物料名称'],
  2164. 'BOM_标准用量' => $bom['BOM_标准用量'],
  2165. 'BOM_计划用量' => $bom['BOM_计划用量'],
  2166. 'BOM_计划门幅' => $bom['BOM_计划门幅'],
  2167. 'BOM_定额门幅' => $bom['BOM_定额门幅'],
  2168. 'BOM_投料单位' => $bom['BOM_投料单位'],
  2169. 'BOM_desc' => $bom['BOM_desc'],
  2170. 'BOM_物料编码' => $wulbm,
  2171. 'Sys_ID' => $bom['Sys_ID'],
  2172. 'Sys_rq' => date('Y-m-d H:i:s')
  2173. ];
  2174. }
  2175. $existsRelation = \db('工单关联表')
  2176. ->where([
  2177. '订单编号' => $orderList['订单编号'],
  2178. '颜色' => $colorName,
  2179. '物料名称' => $bom['BOM_物料名称']
  2180. ])
  2181. ->find();
  2182. if (!$existsRelation) {
  2183. $MaterielLists[] = [
  2184. '关联编号' => 'GDGL' . ($number + 1),
  2185. '订单编号' => $orderList['订单编号'],
  2186. '生产款号' => $orderList['生产款号'],
  2187. '颜色' => $colorName,
  2188. '物料编号' => $wulbm,
  2189. '物料名称' => $bom['BOM_物料名称'],
  2190. '备注' => $bom['BOM_desc'],
  2191. 'Sys_id' => $bom['Sys_ID'],
  2192. 'Sys_rq' => date('Y-m-d H:i:s')
  2193. ];
  2194. $number++;
  2195. }
  2196. }
  2197. }
  2198. if (!empty($MaterielList)) {
  2199. \db('工单_面料资料')->insertAll($MaterielList);
  2200. }
  2201. if (!empty($MaterielLists)) {
  2202. \db('工单关联表')->insertAll($MaterielLists);
  2203. }
  2204. $this->success('修改成功');
  2205. }
  2206. /**
  2207. * Bom资料操作日志左侧菜单
  2208. */
  2209. public function OrderBomLog()
  2210. {
  2211. $list = \db('工单_bom修改日志')
  2212. ->field('修改时间')
  2213. ->group('修改时间')
  2214. ->select();
  2215. $result = [];
  2216. foreach ($list as $item) {
  2217. $dateTime = $item['修改时间'];
  2218. $dateOnly = date('Y-m-d', strtotime($dateTime)); // 提取日期
  2219. $year = date('Y', strtotime($dateTime));
  2220. // 加上(int)date('m', strtotime($sys_rq))转成数字去掉前导 01 => 1
  2221. $month = date('m', strtotime($dateTime));
  2222. // 初始化结构
  2223. if (!isset($result[$year])) {
  2224. $result[$year] = [];
  2225. }
  2226. if (!isset($result[$year][$month])) {
  2227. $result[$year][$month] = [];
  2228. }
  2229. // 避免重复添加相同日期
  2230. if (!in_array($dateOnly, $result[$year][$month])) {
  2231. $result[$year][$month][] = $dateOnly;
  2232. }
  2233. }
  2234. // 按年月日进行倒序排序
  2235. foreach ($result as $year => &$months) {
  2236. krsort($months); // 月份倒序
  2237. foreach ($months as &$dates) {
  2238. rsort($dates); // 日期倒序
  2239. }
  2240. }
  2241. $this->success('成功', $result);
  2242. }
  2243. /**
  2244. * Bom资料操作变更日志记录查询
  2245. */
  2246. public function GetBomEditLog(){
  2247. $param = $this->request->param();
  2248. if (empty($param)){
  2249. $this->error('参数错误');
  2250. }
  2251. $sys_rq = $param['sys_rq'];
  2252. $where= [];
  2253. if (isset($param['search'])) {
  2254. $where['物料名称|订单编号'] = ['like', $param['search'] . '%'];
  2255. }
  2256. // 日期筛选
  2257. if ($sys_rq !== '') {
  2258. $where['修改时间'] = ['like', '%' . $sys_rq . '%'];
  2259. }
  2260. $page = isset($param['page']) ? (int)$param['page'] : 1;
  2261. $limit = isset($param['limit']) ? (int)$param['limit'] : 50;
  2262. $list = \db('工单_bom修改日志')
  2263. ->where($where)
  2264. ->order('修改时间 desc')
  2265. ->limit(($page-1)*$limit,$limit)
  2266. ->select();
  2267. $count = \db('工单_bom修改日志')
  2268. ->where($where)
  2269. ->count();
  2270. $data = [
  2271. 'total' => $count,
  2272. 'list' => $list
  2273. ];
  2274. $this->success('成功', $data);
  2275. }
  2276. /**
  2277. * 入库、出库、退还详情数据
  2278. */
  2279. public function FabricDetaillist()
  2280. {
  2281. if ($this->request->isGet() === false){
  2282. $this->error('请求错误');
  2283. }
  2284. $param = $this->request->param();
  2285. $where = [];
  2286. if (isset($param['order']) && !empty($param['order'])){
  2287. $where['a.order_id'] = $param['order'];
  2288. }
  2289. if (isset($param['lotNumber']) && !empty($param['lotNumber'])){
  2290. $where['a.批次号'] = $param['lotNumber'];
  2291. }
  2292. // 定义查询字段
  2293. $fields = '
  2294. a.id,
  2295. a.receipt_number as 单号,
  2296. a.批次号,
  2297. a.order_id as 订单编号,
  2298. a.客户编号,
  2299. a.款号 as 生产款号,
  2300. a.款式,
  2301. a.物料名称,
  2302. c.BOM_颜色 as 颜色,
  2303. d.BOM_计划用量 as 计划用料,
  2304. d.BOM_计划门幅 as 计划门幅,
  2305. d.BOM_标准用量 as 定额用料,
  2306. d.BOM_定额门幅 as 定额门幅,
  2307. b.单位 as 投料单位,
  2308. d.BOM_desc as 备注,
  2309. b.入仓总量 as 入仓总量,
  2310. b.库存数量 as 面料结余,
  2311. a.departname as 来料部门,
  2312. a.rq as 操作时间,
  2313. a.sys_id as 操作人员
  2314. ';
  2315. $list['入库记录'] = \db('库存_出入库明细')
  2316. ->alias('a')
  2317. ->join('物料_库存 b', 'a.批次号 = b.批次号 AND a.物料编码 = b.物料编号', 'left')
  2318. ->join('工单_面料资料 c','a.order_id = c.BOM_工单编号 AND a.物料编码 = c.BOM_物料编码','left')
  2319. ->join('工单_bom资料 d','a.order_id = d.BOM_工单编号 AND a.物料名称 = d.BOM_物料名称','left')
  2320. ->where($where)
  2321. ->where('a.name', '入库')
  2322. ->field($fields)
  2323. ->field('a.number as 入库数量')
  2324. ->order('a.rq desc')
  2325. ->whereNull('a.Mod_rq')
  2326. ->select();
  2327. //出库记录查询
  2328. $list['出库记录'] = \db('库存_出入库明细')->alias('a')
  2329. ->join('物料_库存 b', 'a.批次号 = b.批次号 AND a.物料编码 = b.物料编号', 'left')
  2330. ->join('工单_面料资料 c','a.order_id = c.BOM_工单编号 AND a.物料编码 = c.BOM_物料编码','left')
  2331. ->join('工单_bom资料 d','a.order_id = d.BOM_工单编号 AND a.物料名称 = d.BOM_物料名称','left')
  2332. ->where($where)
  2333. ->where('a.name', '出库')
  2334. ->field($fields)
  2335. ->field('b.领用数量 as 领用数量,a.number as 出库数量')
  2336. ->order('a.rq desc')
  2337. ->whereNull('a.Mod_rq')
  2338. ->select();
  2339. //退还记录查询
  2340. $list['退还记录'] = \db('库存_出入库明细')->alias('a')
  2341. ->join('物料_库存 b', 'a.批次号 = b.批次号 AND a.物料编码 = b.物料编号', 'left')
  2342. ->join('工单_面料资料 c','a.order_id = c.BOM_工单编号 AND a.物料编码 = c.BOM_物料编码','left')
  2343. ->join('工单_bom资料 d','a.order_id = d.BOM_工单编号 AND a.物料名称 = d.BOM_物料名称','left')
  2344. ->where($where)
  2345. ->where('a.name', '退还')
  2346. ->field($fields)
  2347. ->field('a.type as 退还类型,a.number as 退还数量')
  2348. ->order('a.rq desc')
  2349. ->whereNull('a.Mod_rq')
  2350. ->select();
  2351. $this->success('成功',$list);
  2352. }
  2353. /**
  2354. * 入库、出库、退还删除
  2355. */
  2356. public function FabricDetaildel()
  2357. {
  2358. if ($this->request->isPost() === false) {
  2359. $this->error('请求错误');
  2360. }
  2361. $param = $this->request->param();
  2362. if (empty($param) || !isset($param['id'])) {
  2363. $this->error('请求参数错误');
  2364. }
  2365. $id = $param['id'];
  2366. $where = [
  2367. 'Mod_id' => $param['Mod_id'],
  2368. 'Mod_rq' => date('Y-m-d H:i:s')
  2369. ];
  2370. // 获取出入库记录
  2371. $res = db('库存_出入库明细')->where('id', $id)->find();
  2372. if (!$res) {
  2373. $this->error('ID: ' . $id . ' 的出入库记录不存在');
  2374. }
  2375. // 获取库存信息
  2376. $res_list = db('物料_库存')->where('批次号', $res['批次号'])->find();
  2377. if (!$res_list) {
  2378. $this->error('批次号 ' . $res['批次号'] . ' 的库存记录不存在');
  2379. }
  2380. $updateData = [];
  2381. // 根据出入库类型处理逻辑
  2382. switch ($res['name']) {
  2383. case '入库':
  2384. $updateData['入仓总量'] = $res_list['入仓总量'] - $res['number'];
  2385. $updateData['库存数量'] = $res_list['库存数量'] - $res['number'];
  2386. break;
  2387. case '出库':
  2388. $updateData['领用数量'] = $res_list['领用数量'] - $res['number'];
  2389. $updateData['库存数量'] = $res_list['库存数量'] + $res['number'];
  2390. break;
  2391. case '退还':
  2392. if ($res['type'] == '退仓') {
  2393. $updateData['退还数量'] = $res_list['退还数量'] - $res['number'];
  2394. $updateData['库存数量'] = $res_list['库存数量'] + $res['number'];
  2395. }
  2396. if ($res['type'] == '退客户') {
  2397. $updateData['退还数量'] = $res_list['退还数量'] - $res['number'];
  2398. $updateData['库存数量'] = $res_list['库存数量'] + $res['number'];
  2399. }
  2400. break;
  2401. default:
  2402. $this->error('未知的出入库类型: ' . $res['name']);
  2403. }
  2404. // 安全性校验(防止负数)
  2405. foreach ($updateData as $field => $value) {
  2406. if ($value < 0) {
  2407. $this->error('删除失败,' . $field . ' 更新后为负数');
  2408. }
  2409. }
  2410. // 更新库存表
  2411. $updateResult = db('物料_库存')
  2412. ->where('批次号', $res['批次号'])
  2413. ->fetchSql(true)
  2414. ->update($updateData);
  2415. \db()->query($updateResult);
  2416. if ($updateResult === false) {
  2417. throw new \Exception('更新库存表失败');
  2418. }
  2419. // 更新出入库明细表(软删除)
  2420. $deleteResult = db('库存_出入库明细')
  2421. ->where('id', $id)
  2422. ->fetchSql(true)
  2423. ->update($where);
  2424. \db()->query($deleteResult);
  2425. if ($deleteResult === false) {
  2426. throw new \Exception('更新出入库明细表失败');
  2427. }
  2428. $this->success('删除成功');
  2429. }
  2430. public function Gpt($massage)
  2431. {
  2432. // $apiKey = 'sk-e0JuPjMntkbgi1BoMjrqyyzMKzAxILkQzyGMSy3xiMupuoWY';
  2433. // $apiKey = 'sk-Bhos1lXTRpZiAAmN06624a219a874eCd91Dc068b902a3e73';
  2434. $apiKey = 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss';
  2435. $messages = [
  2436. [
  2437. 'role' => 'user',
  2438. 'content' => '你好,帮我按照:面料1、面料2、面料3……来整理归纳下面的面料信息,我只需要面料信息,不需要其他:'.$massage
  2439. ]
  2440. ];
  2441. $data = [
  2442. 'model' => 'gpt-4',
  2443. 'messages' => $messages,
  2444. 'max_tokens' => 1024,
  2445. 'temperature' => 0.7,
  2446. ];
  2447. // 初始化 cURL 请求
  2448. // $ch = curl_init('https://niubi.zeabur.app/v1/chat/completions');
  2449. // $ch = curl_init('https://one.opengptgod.com/v1/chat/completions');
  2450. $ch = curl_init('https://chatapi.onechats.top/v1/chat/completions');
  2451. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2452. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  2453. 'Content-Type: application/json',
  2454. 'Authorization: Bearer ' . $apiKey,
  2455. ]);
  2456. curl_setopt($ch, CURLOPT_POST, true);
  2457. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  2458. // 跳过证书检查可暂时避免 pem 文件配置失败(测试用)
  2459. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2460. // 执行请求
  2461. $response = curl_exec($ch);
  2462. // 错误处理
  2463. if (curl_errno($ch)) {
  2464. return '请求失败: ' . curl_error($ch);
  2465. }
  2466. curl_close($ch);
  2467. // 解析响应
  2468. $responseData = json_decode($response, true);
  2469. if (isset($responseData['choices'][0]['message']['content'])) {
  2470. $gptReply = $responseData['choices'][0]['message']['content'];
  2471. // 使用正则提取“面料X:XXX”的内容
  2472. preg_match_all('/面料\d+[::](.+)/u', $gptReply, $matches);
  2473. return $matches[1] ?? [];
  2474. } else {
  2475. return '未能获取 GPT 回复';
  2476. }
  2477. }
  2478. /**
  2479. * 面料库存月份查询
  2480. */
  2481. public function fabricListmonth()
  2482. {
  2483. $data = \db('库存_出入库明细')
  2484. ->whereNull('Mod_rq')
  2485. ->field('DISTINCT DATE_FORMAT(rq, "%Y-%m") as month, DATE_FORMAT(rq, "%Y-%m-%d") as date')
  2486. ->whereNull('Mod_rq')
  2487. ->order('rq desc')
  2488. ->select();
  2489. // 按月份分组数据
  2490. $groupedData = [];
  2491. foreach ($data as $entry) {
  2492. $groupedData[$entry['month']][] = $entry['date'];
  2493. }
  2494. // 去重处理,防止重复
  2495. foreach ($groupedData as $month => $dates) {
  2496. $groupedData[$month] = array_values(array_unique($dates));
  2497. }
  2498. $this->success('成功', $groupedData);
  2499. }
  2500. /**
  2501. * 获取每月的面料记录\库存_出入库明细
  2502. * 入库出库退还日期
  2503. */
  2504. public function fetchMonthlyFabricRecords() {
  2505. $types = ['入库', '出库', '退还'];
  2506. $list = [];
  2507. foreach ($types as $type) {
  2508. $data = \db('库存_出入库明细')
  2509. ->where('name', $type)
  2510. ->whereNull('Mod_rq')
  2511. ->field('DISTINCT DATE_FORMAT(rq, "%Y-%m") as month, DATE_FORMAT(rq, "%Y-%m-%d") as date')
  2512. ->order('rq desc')
  2513. ->select();
  2514. // 按照月份分组数据
  2515. $groupedData = [];
  2516. foreach ($data as $entry) {
  2517. $groupedData[$entry['month']][] = $entry['date'];
  2518. }
  2519. // 进一步去重,避免意外重复
  2520. foreach ($groupedData as $month => $dates) {
  2521. $groupedData[$month] = array_values(array_unique($dates));
  2522. }
  2523. // 添加到返回列表
  2524. $list[$type] = $groupedData;
  2525. }
  2526. $this->success('成功', $list);
  2527. }
  2528. /**
  2529. * 面料库存列表
  2530. */
  2531. public function fabricList()
  2532. {
  2533. if ($this->request->isGet() === false) {
  2534. $this->error('请求错误');
  2535. }
  2536. $param = $this->request->param();
  2537. $where = [];
  2538. // 根据传入的参数构造查询条件
  2539. if (isset($param['order'])) {
  2540. $where['b.BOM_工单编号|a.生产款号|b.BOM_物料名称'] = ['like', $param['order'] . '%'];
  2541. }
  2542. if (isset($param['mouth'])) {
  2543. $where['a.Sys_rq'] = ['like', $param['mouth'] . '%'];
  2544. }
  2545. // 分页参数,防止未传递时出错
  2546. $page = isset($param['page']) ? (int)$param['page'] : 1; // 默认第1页
  2547. $limit = isset($param['limit']) ? (int)$param['limit'] : 50; // 默认每页50条
  2548. $excludeOrder = $param['order'];
  2549. // 获取其他订单中相同物料名称的订单编号组合
  2550. $subQuery = \db('工单关联表')
  2551. ->field("物料名称, GROUP_CONCAT(DISTINCT 订单编号 SEPARATOR ',') as 关联订单")
  2552. ->where('订单编号', '<>', $excludeOrder)
  2553. ->group('物料名称')
  2554. ->buildSql();
  2555. $data = \db('工单_基本资料')->alias('a')
  2556. ->field('
  2557. b.BOM_工单编号 as 订单编号,
  2558. a.生产款号,
  2559. a.款式,
  2560. b.BOM_颜色 as 颜色,
  2561. b.BOM_物料编码 as 物料编码,
  2562. b.BOM_物料名称 as 物料名称,
  2563. b.Sys_ID,
  2564. b.Sys_rq,
  2565. c.单位,
  2566. c.入仓总量,
  2567. c.库存数量,
  2568. c.领用数量,
  2569. d.BOM_desc as 备注,
  2570. d.BOM_标准用量 as 定额用料,
  2571. d.BOM_定额门幅 as 定额门幅,
  2572. e.批次号,f.关联订单
  2573. ')
  2574. ->join('工单_面料资料 b', 'a.订单编号 = b.BOM_工单编号')
  2575. ->join('库存_出入库明细 e', 'a.订单编号 = e.order_id')
  2576. ->join('物料_库存 c', 'b.BOM_物料编码 = c.物料编号 AND b.BOM_物料名称 = c.物料名称 AND e.批次号 = c.批次号')
  2577. ->join('工单_bom资料 d', 'a.订单编号 = d.BOM_工单编号 AND b.BOM_物料名称 = d.BOM_物料名称')
  2578. ->join([$subQuery => 'f'], 'f.物料名称 = d.BOM_物料名称','LEFT')
  2579. ->whereNull('a.Mod_rq')
  2580. ->whereNull('b.Mod_rq')
  2581. ->whereNull('c.Mod_rq')
  2582. ->whereNull('d.Mod_rq')
  2583. ->whereNull('e.Mod_rq')
  2584. ->group('e.批次号, b.BOM_物料编码')
  2585. ->where($where)
  2586. ->select();
  2587. // 统计条数进行分页
  2588. $count = \db('工单_面料资料')->where('BOM_工单编号',$param['order'])->count();
  2589. // 确保返回的格式固定
  2590. $list = [
  2591. 'total' => $count,
  2592. 'table' => $data ?: []
  2593. ];
  2594. $this->success('成功', $list);
  2595. }
  2596. /**
  2597. * 单条面料详情
  2598. */
  2599. public function oneFabricDetail()
  2600. {
  2601. if ($this->request->isGet() === false){
  2602. $this->error('请求错误');
  2603. }
  2604. $param = $this->request->param();
  2605. if (empty($param)){
  2606. $this->error('参数错误');
  2607. }
  2608. //面料入库记录
  2609. $list['入库'] = \db('库存_出入库明细')
  2610. ->where('',$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 操作机台,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 操作机台,receipt_number as 出库单据编号,recipient as 领用人员')
  2623. ->select();
  2624. //面料退还记录
  2625. $list['退还'] = \db('库存_出入库明细')
  2626. ->where('order_id',$param['order'])
  2627. ->where('物料名称',$param['fabricName'])
  2628. ->where('name','退还')
  2629. ->where('Mod_rq',null)
  2630. ->field('order_id as 订单编号,款号,物料名称,number as 数量,rq as 日期,sys_id as 操作机台,recipient as 退还人员')
  2631. ->select();
  2632. $this->success('成功',$list);
  2633. }
  2634. /**
  2635. * 单据号查询数据
  2636. * @return void
  2637. * @throws \think\db\exception\DataNotFoundException
  2638. * @throws \think\db\exception\ModelNotFoundException
  2639. * @throws \think\exception\DbException
  2640. */
  2641. public function ReceiptDetail()
  2642. {
  2643. if ($this->request->isGet() === false){
  2644. $this->error('请求错误');
  2645. }
  2646. $param = $this->request->param();
  2647. if (empty($param)){
  2648. $this->error('单据编号参数错误');
  2649. }
  2650. $list = \db('库存_出入库明细')
  2651. ->alias('a')
  2652. ->join('工单_面料资料 b','a.order_id = b.BOM_工单编号 AND b.BOM_物料编码 = a.物料编码')
  2653. ->join('物料_库存 c','a.物料编码 = c.物料编号 AND a.批次号 = c.批次号')
  2654. ->where('a.receipt_number',$param['receipt'])
  2655. ->field('a.id,a.order_id as 订单编号,a.款号,a.物料名称,a.number as 数量,a.rq as 日期,a.sys_rq as 创建日期,a.sys_id as 操作机台,
  2656. a.departname,a.remark,a.type as 退还类型,
  2657. a.receipt_number as 出库单据编号,a.recipient as 领用人员,b.BOM_颜色,c.单位,
  2658. b.BOM_计划用量 as 计划用料,
  2659. b.BOM_计划门幅 as 计划门幅,
  2660. b.BOM_标准用量 as 定额用料,
  2661. b.BOM_定额门幅 as 定额门幅,
  2662. c.实际门幅,c.状态,c.库存数量,c.入仓总量
  2663. ')
  2664. ->whereNull('a.Mod_rq')
  2665. ->whereNull('b.Mod_rq')
  2666. ->whereNull('c.Mod_rq')
  2667. ->select();
  2668. if (empty($list)){
  2669. $this->error('未找到该出库单');
  2670. }else{
  2671. $this->success('成功',$list);
  2672. }
  2673. }
  2674. /**
  2675. * 入库、出库、退还单号列表
  2676. */
  2677. public function ReceiptList(){
  2678. if ($this->request->isGet() === false){
  2679. $this->error('请求错误');
  2680. }
  2681. $param = $this->request->param();
  2682. if (empty($param)){
  2683. $this->error('参数错误');
  2684. }
  2685. $where= [];
  2686. if (isset($param['search'])) {
  2687. $where['物料名称|款号|order_id|receipt_number|款式|物料编码'] = ['like', $param['search'] . '%'];
  2688. }
  2689. if (isset($param['mouth'])) {
  2690. $where['rq'] = ['like', $param['mouth'] . '%'];
  2691. }
  2692. $page = isset($param['page']) ? (int)$param['page'] : 1; // 默认第1页
  2693. $limit = isset($param['limit']) ? (int)$param['limit'] : 50; // 默认每页50条
  2694. $list = \db('库存_出入库明细')
  2695. ->where('Mod_rq', null)
  2696. ->where($where)
  2697. ->where('name',$param['code'])
  2698. ->order('sys_rq desc')
  2699. ->limit(($page-1)*$limit,$limit)
  2700. ->select();
  2701. // 初始化一个合并后的数组
  2702. $merged = [];
  2703. foreach ($list as $item) {
  2704. $key = $item['receipt_number'];
  2705. if (!isset($merged[$key])) {
  2706. // 首次出现,初始化
  2707. $merged[$key] = [
  2708. '单号类型' => $item['name'],
  2709. '出库单' => $item['receipt_number'],
  2710. '订单编号' => $item['order_id'],
  2711. '款号' => $item['款号'],
  2712. '款式' => $item['款式'],
  2713. '物料编码' => $item['物料编码'],
  2714. '物料名称' => $item['物料名称'],
  2715. '总数' => floatval($item['number']),
  2716. '日期' => $item['rq'],
  2717. '创建日期' => $item['sys_rq'],
  2718. '操作机台' => $item['sys_id'],
  2719. '领料人员' => $item['recipient'],
  2720. ];
  2721. } else {
  2722. // 合并相同 receipt_number 的记录
  2723. $merged[$key]['订单编号'] .= ',' . $item['order_id'];
  2724. $merged[$key]['款号'] .= ',' . $item['款号'];
  2725. $merged[$key]['款式'] .= ',' . $item['款式'];
  2726. $merged[$key]['物料编码'] .= ',' . $item['物料编码'];
  2727. $merged[$key]['物料名称'] .= ',' . $item['物料名称'];
  2728. $merged[$key]['总数'] += floatval($item['number']);
  2729. }
  2730. }
  2731. // 对需要的字段进行逗号分隔后的去重
  2732. foreach ($merged as &$item) {
  2733. $item['订单编号'] = implode(',', array_unique(explode(',', $item['订单编号'])));
  2734. $item['款号'] = implode(',', array_unique(explode(',', $item['款号'])));
  2735. $item['款式'] = implode(',', array_unique(explode(',', $item['款式'])));
  2736. $item['物料编码'] = implode(',', array_unique(explode(',', $item['物料编码'])));
  2737. $item['物料名称'] = implode(',', array_unique(explode(',', $item['物料名称'])));
  2738. // 格式化总数
  2739. $item['总数'] = round($item['总数'], 2); // 保留2位小数,防止长尾
  2740. }
  2741. unset($item); // 避免引用问题
  2742. //统计数量
  2743. $count = \db('库存_出入库明细')
  2744. ->where($where)
  2745. ->where('name',$param['code'])
  2746. ->field('receipt_number as 出库单')
  2747. ->group('出库单')
  2748. ->where('Mod_rq',null)
  2749. ->order('rq desc')
  2750. ->select();
  2751. if (empty($merged)){
  2752. $this->success('未找到数据', '');
  2753. } else {
  2754. $data['total'] = count($count);
  2755. $data['table'] = array_values($merged);
  2756. $this->success('成功', $data);
  2757. }
  2758. }
  2759. /**
  2760. * 出库单左侧菜单
  2761. */
  2762. public function getReceiptTab()
  2763. {
  2764. if ($this->request->isGet() === false){
  2765. $this->error('请求错误');
  2766. }
  2767. $list = \db('库存_出入库明细')
  2768. ->field([
  2769. "DATE_FORMAT(rq, '%Y-%m') AS month",
  2770. ])
  2771. ->group('month')
  2772. ->order('month DESC')
  2773. ->select();
  2774. if (empty($list)){
  2775. $this->error('未查询到入库、出库、退还数据');
  2776. }else{
  2777. $this->success('成功',$list);
  2778. }
  2779. }
  2780. /**
  2781. * 获取入库单号、出库单号
  2782. * @return void
  2783. */
  2784. public function gitReceiptNumber()
  2785. {
  2786. if ($this->request->isGet() === false) {
  2787. $this->error('请求错误');
  2788. }
  2789. $param = $this->request->param();
  2790. if (empty($param)) {
  2791. $this->error('参数错误');
  2792. }
  2793. // 获取最新单号(按日期和序号排序)
  2794. $lastNumber = \db('库存_出入库明细')
  2795. ->where('receipt_number', 'like', $param['number'] . date('Ymd') . '-%')
  2796. ->order('receipt_number desc')
  2797. ->whereNull('Mod_rq')
  2798. ->limit(1)
  2799. ->value('receipt_number');
  2800. if (empty($lastNumber)) {
  2801. $num = 1;
  2802. } else {
  2803. // 提取最后3位并转为整数
  2804. $lastSeq = substr($lastNumber, -3);
  2805. $num = (int)$lastSeq + 1;
  2806. }
  2807. // 格式化为3位数字(001, 010, 100, 101...)
  2808. $seq = str_pad($num, 3, '0', STR_PAD_LEFT);
  2809. // 生成完整单号(如 BG20240615-101)
  2810. $number = $param['number'] . date('Ymd') . '-' . $seq;
  2811. // 获取最新出库人员
  2812. $lastUser = \db('库存_出入库明细')
  2813. ->where('name', '出库')
  2814. ->order('recipient desc')
  2815. ->group('recipient')
  2816. ->whereNull('Mod_rq')
  2817. ->limit(1)
  2818. ->value('recipient');
  2819. $data = [
  2820. 'number' => $number,
  2821. 'username' => $lastUser
  2822. ];
  2823. $this->success('成功', $data);
  2824. }
  2825. /**
  2826. * 面料批次列表
  2827. */
  2828. public function FabricLotList()
  2829. {
  2830. if ($this->request->isGet() === false){
  2831. $this->error('请求错误');
  2832. }
  2833. $param = $this->request->param();
  2834. if (empty($param)){
  2835. $this->error('参数错误');
  2836. }
  2837. $where= [];
  2838. if (isset($param['search'])) {
  2839. $where['c.物料编号|c.物料名称|a.生产款号|a.订单编号|b.BOM_颜色'] = ['like', '%' . $param['search'] . '%'];
  2840. }
  2841. if (isset($param['date'])) {
  2842. $where['e.rq'] = ['like', $param['date'] . '%'];
  2843. }
  2844. $subQuery = \db('工单关联表')
  2845. ->field("物料名称, GROUP_CONCAT(DISTINCT 订单编号 SEPARATOR ',') as 关联订单")
  2846. ->group('物料名称')
  2847. ->buildSql();
  2848. $list = \db('工单_基本资料')->alias('a')
  2849. ->field('
  2850. c.批次号,
  2851. c.关联号,
  2852. c.物料编号,
  2853. c.物料名称,
  2854. c.入仓总量,
  2855. c.库存数量,
  2856. c.领用数量,
  2857. c.退还数量 as 裁切退还,
  2858. c.单位,
  2859. c.实际门幅,
  2860. c.状态,
  2861. e.sys_id as 入仓人员,
  2862. e.sys_rq as 入仓日期,
  2863. b.BOM_颜色 as 颜色,
  2864. a.生产款号 as 款号,
  2865. d.BOM_计划用量 as 计划用料,
  2866. d.BOM_标准用量 as 定额用料,
  2867. d.BOM_计划门幅 as 计划门幅,
  2868. d.BOM_定额门幅 as 定额门幅,
  2869. f.关联订单
  2870. ')
  2871. ->join('工单_面料资料 b', 'a.订单编号 = b.BOM_工单编号')
  2872. ->join('库存_出入库明细 e', 'a.订单编号 = e.order_id')
  2873. ->join('物料_库存 c', 'b.BOM_物料编码 = c.物料编号 AND b.BOM_物料名称 = c.物料名称 AND e.批次号 = c.批次号')
  2874. ->join('工单_bom资料 d', 'a.订单编号 = d.BOM_工单编号 AND b.BOM_物料名称 = d.BOM_物料名称')
  2875. ->join([$subQuery => 'f'], 'f.物料名称 = d.BOM_物料名称')
  2876. ->whereNull('a.Mod_rq')
  2877. // ->whereNull('b.Mod_rq')
  2878. ->whereNull('c.Mod_rq')
  2879. // ->whereNull('d.Mod_rq')
  2880. ->whereNull('e.Mod_rq')
  2881. ->group('c.物料编号')
  2882. ->where($where)
  2883. ->select();
  2884. if (empty($list)){
  2885. $this->error('未找到面料数据');
  2886. }else{
  2887. $this->success('成功',$list);
  2888. }
  2889. }
  2890. public function SubOrderProgress()
  2891. {
  2892. if (!$this->request->isGet()) {
  2893. $this->error('请求错误');
  2894. }
  2895. $params = $this->request->param();
  2896. if (empty($params['order'])) {
  2897. $this->error('缺少订单编号');
  2898. }
  2899. $orderNo = $params['order'];
  2900. // ▶ 获取该主订单下的全部子订单(印件资料为主)
  2901. $styleData = Db::name('工单_印件资料')
  2902. ->where('订单编号', $orderNo)
  2903. ->field('子订单编号, 款号, 颜色, 颜色备注')
  2904. ->whereNull('Mod_rq')
  2905. ->select();
  2906. if (empty($styleData)) {
  2907. $this->success('未找到子订单资料', ['result' => [], 'list' => []]);
  2908. }
  2909. $subOrderNos = array_column($styleData, '子订单编号');
  2910. // 子订单 → 款号/颜色
  2911. $styleMap = [];
  2912. foreach ($styleData as $row) {
  2913. $styleMap[$row['子订单编号']] = [
  2914. '款号' => $row['款号'],
  2915. '颜色' => $row['颜色'],
  2916. '颜色备注' => $row['颜色备注'],
  2917. ];
  2918. }
  2919. // ▶ 入仓数量统计
  2920. $warehouseData = Db::name('成品入仓')
  2921. ->alias('a')
  2922. ->field('a.order_id as 子订单编号, SUM(a.sl) as 入仓数量')
  2923. ->where('a.order', $orderNo)
  2924. ->whereNull('a.mod_rq')
  2925. ->group('a.order_id')
  2926. ->select();
  2927. $warehouseMap = [];
  2928. foreach ($warehouseData as $row) {
  2929. $warehouseMap[$row['子订单编号']] = (int)$row['入仓数量'];
  2930. }
  2931. // ▶ 裁剪数量统计
  2932. $prodData = Db::name('设备_产量计酬')
  2933. ->field('子订单编号, SUM(数量) as 裁剪数量')
  2934. ->whereIn('子订单编号', $subOrderNos)
  2935. ->where('工序名称', '裁剪')
  2936. ->group('子订单编号')
  2937. ->select();
  2938. $cutMap = [];
  2939. foreach ($prodData as $row) {
  2940. $cutMap[$row['子订单编号']] = (int)$row['裁剪数量'];
  2941. }
  2942. // ▶ 合并结果(子订单明细)
  2943. $result = [];
  2944. $totalCut = 0;
  2945. $totalIn = 0;
  2946. foreach ($subOrderNos as $subOrderNo) {
  2947. $inQty = $warehouseMap[$subOrderNo] ?? 0;
  2948. $cutQty = $cutMap[$subOrderNo] ?? 0;
  2949. $rate = $cutQty > 0 ? round($inQty / $cutQty * 100, 2) . '%' : '0%';
  2950. $styleInfo = $styleMap[$subOrderNo] ?? ['款号'=>'','颜色'=>'','颜色备注'=>''];
  2951. $result[] = [
  2952. '子订单编号' => $subOrderNo,
  2953. '生产款号' => $styleInfo['款号'],
  2954. '颜色' => $styleInfo['颜色'],
  2955. '颜色备注' => $styleInfo['颜色备注'],
  2956. '裁剪数量' => $cutQty,
  2957. '入仓数量' => $inQty,
  2958. '完成率' => $rate,
  2959. ];
  2960. $totalCut += $cutQty;
  2961. $totalIn += $inQty;
  2962. }
  2963. // ▶ 汇总 list 字段(整张订单)
  2964. $list = [[
  2965. '订单编号' => $orderNo,
  2966. '订单总裁剪数量' => $totalCut,
  2967. '订单总入仓数量' => $totalIn,
  2968. '订单完成率' => $totalCut > 0 ? round($totalIn / $totalCut * 100, 2) . '%' : '0%'
  2969. ]];
  2970. // ▶ 返回数据
  2971. $this->success('请求成功', [
  2972. 'result' => $result,
  2973. 'list' => $list
  2974. ]);
  2975. }
  2976. /**
  2977. * 仓库管理
  2978. * 入库、出库、退还更新
  2979. */
  2980. public function rApictedit()
  2981. {
  2982. if (!$this->request->isPost()) {
  2983. $this->error('请求错误');
  2984. }
  2985. $param = Request::instance()->post();
  2986. if (empty($param)) {
  2987. $this->error('参数错误');
  2988. }
  2989. $logData = []; // 日志记录数组
  2990. $now = date('Y-m-d H:i:s');
  2991. foreach ($param as $item) {
  2992. $id = $item['id'];
  2993. $newQty = floatval($item['数量'] ?? 0);
  2994. $name = $item['name'];
  2995. $returnType = $item['退还类型'];
  2996. $sysId = $item['sys_id'];
  2997. $rq = $item['rq'];
  2998. $remark = $item['remark'];
  2999. if (!$id || !$name) {
  3000. $this->error('缺少必要参数');
  3001. }
  3002. // 获取库存_出入库明细 原记录
  3003. $record = \db('库存_出入库明细')
  3004. ->field('id, 批次号, number, type')
  3005. ->where('name', $name)
  3006. ->whereNull('Mod_rq')
  3007. ->where('id', $id)
  3008. ->find();
  3009. if (!$record) {
  3010. $this->error("未找到 ID 为 {$id} 的记录");
  3011. }
  3012. $batchNo = $record['批次号'];
  3013. $oldQty = floatval($record['number']);
  3014. $diff = $newQty - $oldQty;
  3015. //修改库存_出入库明细
  3016. $updateSql = \db('库存_出入库明细')
  3017. ->where('id', $id)
  3018. ->where('name', $name)
  3019. ->whereNull('Mod_rq')
  3020. ->fetchSql(true)
  3021. ->update(
  3022. [
  3023. 'number' => $newQty,
  3024. 'remark' => $remark,
  3025. 'rq' => $rq
  3026. ]
  3027. );
  3028. \db()->query($updateSql); // 执行 SQL
  3029. // 写入日志,增加 ids 字段
  3030. $logData[] = [
  3031. '批次号' => $batchNo,
  3032. '操作字段' => 'number',
  3033. '原值' => $oldQty,
  3034. '新值' => $newQty,
  3035. '操作人' => $sysId,
  3036. '操作类型' => $name,
  3037. '操作时间' => $now,
  3038. '修改表' => '库存_出入库明细',
  3039. 'ids' => $id
  3040. ];
  3041. // === 获取同批次的记录以统计新合计 ===
  3042. $sameBatchList = \db('库存_出入库明细')
  3043. ->field('number')
  3044. ->where('name', $name)
  3045. ->whereNull('Mod_rq')
  3046. ->where('批次号', $batchNo)
  3047. ->select();
  3048. $newTotal = array_sum(array_column($sameBatchList, 'number'));
  3049. // === 获取物料_库存信息(加上 id 字段) ===
  3050. $inventory = \db('物料_库存')
  3051. ->field('id, 入仓总量, 领用数量, 库存数量, 退还数量')
  3052. ->where('批次号', $batchNo)
  3053. ->find();
  3054. if ($inventory) {
  3055. $stockId = $inventory['id']; // 记录当前库存表的 id
  3056. $inQty = floatval($inventory['入仓总量']);
  3057. $stockQty = floatval($inventory['库存数量']);
  3058. $useQty = floatval($inventory['领用数量']);
  3059. $returnQty = floatval($inventory['退还数量']);
  3060. if ($name == '入库') {
  3061. $newIn = $inQty + $diff;
  3062. $newStock = $stockQty + $diff;
  3063. $updateFields = [];
  3064. if ($newIn != $inQty) {
  3065. $updateFields['入仓总量'] = $newIn;
  3066. $logData[] = [
  3067. '批次号' => $batchNo,
  3068. '操作字段' => '入仓总量',
  3069. '原值' => $inQty,
  3070. '新值' => $newIn,
  3071. '操作人' => $sysId,
  3072. '操作类型' => '入库',
  3073. '操作时间' => $now,
  3074. '修改表' => '物料_库存',
  3075. 'ids' => $stockId
  3076. ];
  3077. }
  3078. if ($newStock != $stockQty) {
  3079. $updateFields['库存数量'] = $newStock;
  3080. $logData[] = [
  3081. '批次号' => $batchNo,
  3082. '操作字段' => '库存数量',
  3083. '原值' => $stockQty,
  3084. '新值' => $newStock,
  3085. '操作人' => $sysId,
  3086. '操作类型' => '入库',
  3087. '操作时间' => $now,
  3088. '修改表' => '物料_库存',
  3089. 'ids' => $stockId
  3090. ];
  3091. }
  3092. if (!empty($updateFields)) {
  3093. $updateStockSql = \db('物料_库存')
  3094. ->where('id', $stockId)
  3095. ->fetchSql(true)
  3096. ->update($updateFields);
  3097. \db()->query($updateStockSql);
  3098. }
  3099. }elseif ($name == '出库') {
  3100. if ($newTotal != $useQty) {
  3101. // 计算新的库存数量
  3102. $newStock = $inQty - $newTotal - $returnQty;
  3103. $updateFields = [
  3104. '领用数量' => $newTotal,
  3105. '库存数量' => $newStock
  3106. ];
  3107. $updateStockSql = \db('物料_库存')
  3108. ->where('id', $stockId)
  3109. ->fetchSql(true)
  3110. ->update($updateFields);
  3111. \db()->query($updateStockSql);
  3112. $logData[] = [
  3113. '批次号' => $batchNo,
  3114. '操作字段' => '领用数量',
  3115. '原值' => $useQty,
  3116. '新值' => $newTotal,
  3117. '操作人' => $sysId,
  3118. '操作类型' => '出库',
  3119. '操作时间' => $now,
  3120. '修改表' => '物料_库存',
  3121. 'ids' => $stockId
  3122. ];
  3123. $logData[] = [
  3124. '批次号' => $batchNo,
  3125. '操作字段' => '库存数量',
  3126. '原值' => $stockQty,
  3127. '新值' => $newStock,
  3128. '操作人' => $sysId,
  3129. '操作类型' => '出库',
  3130. '操作时间' => $now,
  3131. '修改表' => '物料_库存',
  3132. 'ids' => $stockId
  3133. ];
  3134. }
  3135. }elseif ($name == '退还') {
  3136. if ($returnType == '退面料' && $newTotal != $returnQty) {
  3137. $newStock = $inQty - $useQty - $newTotal;
  3138. $updateFields = [
  3139. '退还数量' => $newTotal,
  3140. '库存数量' => $newStock
  3141. ];
  3142. $updateStockSql = \db('物料_库存')
  3143. ->where('id', $stockId)
  3144. ->fetchSql(true)
  3145. ->update($updateFields);
  3146. \db()->query($updateStockSql);
  3147. $logData[] = [
  3148. '批次号' => $batchNo,
  3149. '操作字段' => '退还数量',
  3150. '原值' => $returnQty,
  3151. '新值' => $newTotal,
  3152. '操作人' => $sysId,
  3153. '操作类型' => '退还',
  3154. '操作时间' => $now,
  3155. '修改表' => '物料_库存',
  3156. 'ids' => $stockId
  3157. ];
  3158. // 添加库存数量变更日志
  3159. $logData[] = [
  3160. '批次号' => $batchNo,
  3161. '操作字段' => '库存数量',
  3162. '原值' => $stockQty,
  3163. '新值' => $newStock,
  3164. '操作人' => $sysId,
  3165. '操作类型' => '退还',
  3166. '操作时间' => $now,
  3167. '修改表' => '物料_库存',
  3168. 'ids' => $stockId
  3169. ];
  3170. }
  3171. }
  3172. }
  3173. }
  3174. // 批量写入日志
  3175. if (!empty($logData)) {
  3176. \db('物料_库存日志')->insertAll($logData);
  3177. }
  3178. $this->success('更新成功');
  3179. }
  3180. /**
  3181. * 成品入仓合格率左侧菜单
  3182. */
  3183. public function GetWfpDataLeft()
  3184. {
  3185. // $countData = Db::name('设备_产量计酬')->alias('a')
  3186. // ->field('COUNT(DISTINCT a.订单编号) as total_count,
  3187. // DATE_FORMAT(a.sys_rq, "%Y%m") as 年月,
  3188. // b.客户编号')
  3189. // ->where('工序编号',6)
  3190. // ->join('工单_基本资料 b', 'a.订单编号 = b.订单编号', 'left')
  3191. // ->group('DATE_FORMAT(b.Sys_rq, "%Y%m"), b.客户编号')
  3192. // ->whereNull('a.mod_rq')
  3193. // ->whereNull('b.Mod_rq')
  3194. // ->select();
  3195. // 统计每个客户每月的去重订单数
  3196. $countData = Db::name('成品入仓')
  3197. ->alias('a')
  3198. ->field('COUNT(DISTINCT a.order) as total_count,
  3199. DATE_FORMAT(a.sys_rq, "%Y%m") as 年月,
  3200. b.客户编号')
  3201. ->join('工单_基本资料 b', 'a.order = b.订单编号', 'left')
  3202. ->group('DATE_FORMAT(a.sys_rq, "%Y%m"), b.客户编号')
  3203. ->whereNull('a.mod_rq')
  3204. ->whereNull('b.Mod_rq')
  3205. ->select();
  3206. // 整理结果:按年月分组
  3207. $result = [];
  3208. foreach ($countData as $item) {
  3209. $yearMonth = $item['年月'];
  3210. if (!isset($result[$yearMonth])) {
  3211. $result[$yearMonth] = [];
  3212. }
  3213. $result[$yearMonth][] = [
  3214. '客户编号' => $item['客户编号'],
  3215. 'total' => '订单数:'.(int)$item['total_count']
  3216. ];
  3217. }
  3218. krsort($result);
  3219. $this->success('请求成功', $result);
  3220. }
  3221. /**
  3222. 成品入仓订单列表
  3223. */
  3224. public function GetWfpList()
  3225. {
  3226. if (!$this->request->isGet()) {
  3227. $this->error('请求失败');
  3228. }
  3229. $params = $this->request->get();
  3230. // 判断是否有日期参数
  3231. $hasDate = !empty($params['sys_rq']);
  3232. // 时间范围处理
  3233. if ($hasDate) {
  3234. $startDate = date('Y-m-01', strtotime($params['sys_rq'] . '01'));
  3235. $endDate = date('Y-m-d', strtotime("$startDate +1 month"));
  3236. }
  3237. // 获取订单列表(支持搜索)
  3238. $gdQuery = Db::name('工单_基本资料')
  3239. ->field('订单编号, 生产款号, 款式, 订单数量, 客户编号')
  3240. ->whereNull('mod_rq');
  3241. if (!empty($params['search'])) {
  3242. $gdQuery->where('订单编号|生产款号|款式', 'like', '%' . $params['search'] . '%');
  3243. }
  3244. $gdlist = $gdQuery->select();
  3245. if (empty($gdlist)) {
  3246. $this->success('无匹配订单', ['result' => []]);
  3247. }
  3248. // 提取订单编号列表
  3249. $filteredOrderNos = array_column($gdlist, '订单编号');
  3250. $where = [];
  3251. if (!empty($params['customer'])) {
  3252. $where['a.customer'] = $params['customer'];
  3253. }
  3254. // 入仓数据查询
  3255. // 确保参数存在且格式正确
  3256. $yearMonth = !empty($params['sys_rq']) ? $params['sys_rq'] : '';
  3257. // 构建查询
  3258. $warehouseQuery = Db::name('成品入仓')
  3259. ->alias('a')
  3260. ->field('a.order as 订单编号, SUM(a.sl) as 入仓数量,a.sys_rq,a.customer')
  3261. ->where($where)
  3262. ->whereIn('a.order', $filteredOrderNos)
  3263. ->whereNull('a.mod_rq');
  3264. // 只当有有效年月参数时添加日期筛选
  3265. if ($yearMonth && strlen($yearMonth) == 6) {
  3266. // 使用字符串拼接的方式确保SQL函数正确执行
  3267. $warehouseQuery->where("DATE_FORMAT(a.sys_rq, '%Y%m') = '{$yearMonth}'");
  3268. }
  3269. $warehouseData = $warehouseQuery->group('a.order')->select();
  3270. // 提取入仓涉及的订单编号
  3271. $orderNos = array_column($warehouseData, '订单编号');
  3272. if (empty($orderNos)) {
  3273. $this->success('无数据', ['result' => []]);
  3274. }
  3275. // 入仓 map
  3276. $warehouseMap = [];
  3277. foreach ($warehouseData as $row) {
  3278. $warehouseMap[$row['订单编号']] = (int)$row['入仓数量'];
  3279. }
  3280. // 累计入仓处理
  3281. $cumulativeMap = [];
  3282. if ($hasDate) {
  3283. // 有日期时,累计入仓是所有时间的总和
  3284. $cumulativeData = Db::name('成品入仓')
  3285. ->alias('a')
  3286. ->field('a.order as 订单编号, SUM(a.sl) as 累计入仓数量')
  3287. ->where($where)
  3288. ->whereIn('a.order', $orderNos)
  3289. ->whereNull('a.mod_rq')
  3290. ->group('a.order')
  3291. ->select();
  3292. foreach ($cumulativeData as $row) {
  3293. $cumulativeMap[$row['订单编号']] = (int)$row['累计入仓数量'];
  3294. }
  3295. } else {
  3296. // 没有日期时,累计入仓就是当前入仓数量
  3297. foreach ($warehouseData as $row) {
  3298. $cumulativeMap[$row['订单编号']] = (int)$row['入仓数量'];
  3299. }
  3300. }
  3301. // 裁剪产量
  3302. $prodRecords = Db::name('设备_产量计酬')
  3303. ->whereIn('订单编号', $orderNos)
  3304. ->where('工序名称', '裁剪')
  3305. ->select();
  3306. $cutMap = [];
  3307. foreach ($prodRecords as $record) {
  3308. $orderNo = $record['订单编号'];
  3309. $styleCode = $record['款号'] ?? '';
  3310. $qty = (int)$record['数量'];
  3311. if (!isset($cutMap[$orderNo])) {
  3312. $cutMap[$orderNo] = [
  3313. '生产款号' => $styleCode,
  3314. '裁剪总产量' => 0
  3315. ];
  3316. }
  3317. $cutMap[$orderNo]['裁剪总产量'] += $qty;
  3318. }
  3319. // 质量数据(返工/次片)
  3320. $qualityData = Db::name('设备_质量汇总')
  3321. ->field('订单编号, 状态, SUM(数量) as 数量')
  3322. ->whereIn('订单编号', $orderNos)
  3323. ->group('订单编号, 状态')
  3324. ->select();
  3325. $qualityMap = [];
  3326. foreach ($qualityData as $item) {
  3327. $orderNo = $item['订单编号'];
  3328. $status = $item['状态'];
  3329. $qty = (int)$item['数量'];
  3330. if (!isset($qualityMap[$orderNo])) {
  3331. $qualityMap[$orderNo] = [
  3332. '返工总数' => 0,
  3333. '次片总数' => 0
  3334. ];
  3335. }
  3336. if ($status === '返工') {
  3337. $qualityMap[$orderNo]['返工总数'] += $qty;
  3338. } elseif ($status === '次片') {
  3339. $qualityMap[$orderNo]['次片总数'] += $qty;
  3340. }
  3341. }
  3342. // 获取订单信息映射
  3343. $orderInfoList = Db::name('工单_基本资料')
  3344. ->field('订单编号, 款式, 订单数量, 客户编号')
  3345. ->whereIn('订单编号', $orderNos)
  3346. ->select();
  3347. $orderInfoMap = [];
  3348. foreach ($orderInfoList as $orderInfo) {
  3349. $orderNo = $orderInfo['订单编号'];
  3350. $orderInfoMap[$orderNo] = [
  3351. '款式' => $orderInfo['款式'] ?? '',
  3352. '订单数量' => $orderInfo['订单数量'] ?? 0,
  3353. '客户编号' => $orderInfo['客户编号'] ?? ''
  3354. ];
  3355. }
  3356. // 汇总数据
  3357. $result = [];
  3358. foreach ($orderNos as $orderNo) {
  3359. $cutQty = $cutMap[$orderNo]['裁剪总产量'] ?? 0;
  3360. $warehouseQty = $warehouseMap[$orderNo] ?? 0;
  3361. $cumulativeQty = $cumulativeMap[$orderNo] ?? 0;
  3362. $styleCode = $cutMap[$orderNo]['生产款号'] ?? '';
  3363. $orderInfo = $orderInfoMap[$orderNo] ?? [];
  3364. $khName = $orderInfo['客户编号'] ?? '';
  3365. $styleName = $orderInfo['款式'] ?? '';
  3366. $orderQty = $orderInfo['订单数量'] ?? 0;
  3367. $actualPassRate = $cutQty > 0 ? round($cumulativeQty / $cutQty * 100, 2) . '%' : '0%';
  3368. $reworkQty = $qualityMap[$orderNo]['返工总数'] ?? 0;
  3369. $secondQty = $qualityMap[$orderNo]['次片总数'] ?? 0;
  3370. $result[] = [
  3371. '订单编号' => $orderNo,
  3372. '生产款号' => $styleCode,
  3373. '客户编号' => $khName,
  3374. '款式' => $styleName,
  3375. '订单数量' => $orderQty,
  3376. '裁剪总产量' => $cutQty,
  3377. '入仓数量' => $warehouseQty,
  3378. '累计入仓数量' => $cumulativeQty,
  3379. '裁剪合格率' => $actualPassRate,
  3380. '返工总数' => $reworkQty,
  3381. '次片总数' => $secondQty,
  3382. '统计类型' => $hasDate ? '月度统计' : '总计'
  3383. ];
  3384. }
  3385. $this->success('请求成功', ['result' => $result]);
  3386. }
  3387. /**
  3388. * 成品入仓子订单列表
  3389. */
  3390. public function GetSubOrderStats()
  3391. {
  3392. if (!$this->request->isGet()) {
  3393. $this->error('请求失败');
  3394. }
  3395. $params = $this->request->get();
  3396. $startDate = date('Y-m-01', strtotime($params['sys_rq'] . '01'));
  3397. $endDate = date('Y-m-d', strtotime("$startDate +1 month"));
  3398. //获取该订单的所有子订单
  3399. $styleData = Db::name('工单_印件资料')
  3400. ->where('订单编号', $params['order'])
  3401. ->field('子订单编号, 款号, 颜色备注, 颜色,zdtotal')
  3402. ->whereNull('Mod_rq')
  3403. ->select();
  3404. $subOrderNos = array_column($styleData, '子订单编号');
  3405. if (empty($subOrderNos)) {
  3406. $this->success('未找到该订单下的子订单资料', ['result' => [], 'list' => []]);
  3407. }
  3408. $styleMap = [];
  3409. foreach ($styleData as $row) {
  3410. $styleMap[$row['子订单编号']] = [
  3411. 'zdtotal' => $row['zdtotal'],
  3412. '款号' => $row['款号'],
  3413. '颜色' => $row['颜色'],
  3414. '颜色备注' => $row['颜色备注']
  3415. ];
  3416. }
  3417. // 子订单入仓数据(当前月)
  3418. $warehouseData = Db::name('设备_产量计酬')
  3419. ->field('子订单编号, SUM(s_num) as 入仓数量')
  3420. // ->where('customer', $params['customer'])
  3421. ->where('订单编号', $params['order'])
  3422. ->whereNull('mod_rq')
  3423. ->where('工序名称', '总检')
  3424. ->whereBetween('sys_rq', [$startDate, $endDate])
  3425. ->group('子订单编号')
  3426. ->select();
  3427. $warehouseMap = [];
  3428. foreach ($warehouseData as $row) {
  3429. $warehouseMap[$row['子订单编号']] = (int)$row['入仓数量'];
  3430. }
  3431. //累计入仓(不限时间)
  3432. $cumulativeData = Db::name('设备_产量计酬')
  3433. ->field('子订单编号, SUM(s_num) as 累计入仓数量')
  3434. // ->where('customer', $params['customer'])
  3435. ->where('子订单编号', $params['order'])
  3436. ->where('工序名称', '总检')
  3437. ->whereNull('mod_rq')
  3438. ->group('子订单编号')
  3439. ->select();
  3440. $cumulativeMap = [];
  3441. foreach ($cumulativeData as $row) {
  3442. $cumulativeMap[$row['子订单编号']] = (int)$row['累计入仓数量'];
  3443. }
  3444. // 裁剪产量(不限时间)
  3445. $prodRecords = Db::name('设备_产量计酬')
  3446. ->whereIn('子订单编号', $subOrderNos)
  3447. ->where('工序名称', '裁剪')
  3448. ->select();
  3449. $cutMap = [];
  3450. foreach ($prodRecords as $row) {
  3451. $subOrder = $row['子订单编号'];
  3452. $qty = (int)$row['数量'];
  3453. if (!isset($cutMap[$subOrder])) {
  3454. $cutMap[$subOrder] = 0;
  3455. }
  3456. $cutMap[$subOrder] += $qty;
  3457. }
  3458. $result = [];
  3459. $totalCut = 0;
  3460. $totalIn = 0;
  3461. $orderNo = $params['order'];
  3462. foreach ($subOrderNos as $subOrderNo) {
  3463. $inQty = $warehouseMap[$subOrderNo] ?? 0;
  3464. $totalInQty = $cumulativeMap[$subOrderNo] ?? 0;
  3465. $cutQty = $cutMap[$subOrderNo] ?? 0;
  3466. $styleInfo = $styleMap[$subOrderNo] ?? ['zdtotal' => '','款号' => '', '颜色' => '', '颜色备注' => ''];
  3467. $monthlyRate = $cutQty > 0 ? round($inQty / $cutQty * 100, 2) . '%' : '0%';
  3468. $cumulativeRate = $cutQty > 0 ? round($totalInQty / $cutQty * 100, 2) . '%' : '0%';
  3469. $result[] = [
  3470. '订单编号' => $orderNo,
  3471. '子订单编号' => $subOrderNo,
  3472. '生产款号' => $styleInfo['款号'],
  3473. '颜色' => $styleInfo['颜色'],
  3474. 'zdtotal' => $styleInfo['zdtotal'],
  3475. '颜色备注' => $styleInfo['颜色备注'],
  3476. '裁剪数量' => $cutQty,
  3477. '入仓数量' => $inQty,
  3478. '累计入仓数量' => $totalInQty,
  3479. '月度合格率' => $monthlyRate,
  3480. '实际合格率' => $cumulativeRate
  3481. ];
  3482. $totalCut += $cutQty;
  3483. $totalIn += $totalInQty;
  3484. }
  3485. $list = [[
  3486. '订单编号' => $orderNo,
  3487. '订单累计裁剪数量' => $totalCut,
  3488. '订单累计入仓数量' => $totalIn,
  3489. '订单合格率' => $totalCut > 0 ? round($totalIn / $totalCut * 100, 2) . '%' : '0%'
  3490. ]];
  3491. $this->success('请求成功', [
  3492. 'list' => $list,
  3493. 'result' => $result
  3494. ]);
  3495. }
  3496. /**
  3497. * 电表管理
  3498. */
  3499. private function httpGetRequest($url, $params = [])
  3500. {
  3501. if (!empty($params)) {
  3502. $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
  3503. }
  3504. $ch = curl_init();
  3505. curl_setopt($ch, CURLOPT_URL, $url);
  3506. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3507. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  3508. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  3509. 'Content-Type: application/json',
  3510. ]);
  3511. $response = curl_exec($ch);
  3512. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  3513. if (curl_errno($ch)) {
  3514. $errorMsg = curl_error($ch);
  3515. curl_close($ch);
  3516. throw new Exception('cURL错误: ' . $errorMsg);
  3517. }
  3518. curl_close($ch);
  3519. if ($httpCode !== 200) {
  3520. throw new Exception('API请求失败,HTTP状态码: ' . $httpCode);
  3521. }
  3522. $resultData = json_decode($response, true);
  3523. if (json_last_error() !== JSON_ERROR_NONE) {
  3524. throw new Exception('JSON解析错误: ' . json_last_error_msg());
  3525. }
  3526. return $resultData;
  3527. }
  3528. /**
  3529. * 接口api说明:设备数据/设备状态
  3530. * 接口说明:查询设备列表和当前状态-左侧菜单
  3531. */
  3532. public function Meter()
  3533. {
  3534. $res = Db::name('电表设备列表')->select();
  3535. $this->success('请求成功', $res);
  3536. }
  3537. /**
  3538. * 查询电表能耗数据日数据
  3539. */
  3540. public function StatisticEleDay()
  3541. {
  3542. if (!$this->request->isGet()) {
  3543. $this->error('非法请求');
  3544. }
  3545. $params = $this->request->get();
  3546. // 检查 mid 参数是否为空
  3547. if (empty($params['mid'])) {
  3548. $this->error('mid参数不能为空');
  3549. }
  3550. $mid = (int)$params['mid'];
  3551. $riqi = $params['riqi'] ?? date('Ym');
  3552. $where = [];
  3553. $where['电表ID'] = $mid;
  3554. // 通过日期查询
  3555. if (!empty($params['riqi'])) {
  3556. if (preg_match('/^\d{6}$/', $params['riqi'])) {
  3557. // 年月格式:YYYYMM,查询该月份所有数据
  3558. $startDate = $params['riqi'] . '01';
  3559. $endDate = date('Ymd', strtotime("last day of {$params['riqi']}01"));
  3560. $where['日期'] = ['between', [$startDate, $endDate]];
  3561. } else {
  3562. $this->error('日期参数格式错误,应为 YYYYMM');
  3563. }
  3564. } else {
  3565. // 默认查询当前月份
  3566. $currentMonth = date('Ym');
  3567. $startDate = $currentMonth . '01';
  3568. $endDate = date('Ymd');
  3569. $where['日期'] = ['between', [$startDate, $endDate]];
  3570. }
  3571. $res = Db::name('电表能耗日数据')
  3572. ->where($where)->order('日期 DESC')->select();
  3573. $this->success('查询成功', $res);
  3574. }
  3575. /**
  3576. * 导出电表月数据
  3577. */
  3578. public function Excel_StatisticEle(){
  3579. if (!$this->request->isGet()) {
  3580. $this->error('非法请求');
  3581. }
  3582. $params = $this->request->get();
  3583. $res = Db::name('电表能耗月数据')->alias('a')
  3584. ->field('
  3585. a.id,
  3586. a.电表ID,
  3587. a.总电量,
  3588. a.尖电量,
  3589. a.峰电量,
  3590. a.平电量,
  3591. a.谷电量,
  3592. a.起始总电量,
  3593. a.结束总电量,
  3594. a.开始时间,
  3595. a.结束时间,
  3596. a.日期,
  3597. b.description as 小组
  3598. ')
  3599. ->join('电表设备列表 b', 'a.电表ID = b.mid', 'LEFT')
  3600. ->where('日期',$params['sys_rq'])
  3601. ->where('b.description', '<>', '')
  3602. ->where('b.description', 'not null')
  3603. ->order('b.id asc')
  3604. ->select();
  3605. $this->success('请求成功', $res);
  3606. }
  3607. /**
  3608. * 同步电表序号列表数据
  3609. * 查询设备列表和当前状态-左侧菜单
  3610. */
  3611. public function saveToDatabase()
  3612. {
  3613. $url = "http://api1.tqdianbiao.com/Api/Meter?type=json&auth=a15dbee8d66bf1b4149637e3912bf631";
  3614. $resultData = $this->httpGetRequest($url);
  3615. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3616. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3617. }
  3618. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3619. throw new Exception('API返回数据格式不正确');
  3620. }
  3621. $result = [];
  3622. foreach ($resultData['data'] as $meter) {
  3623. $result[] = [
  3624. 'mid' => $meter['id'],
  3625. 'collectorid' => $meter['collectorid'],
  3626. 'description' => $meter['description']
  3627. ];
  3628. }
  3629. // 批量处理数据
  3630. foreach ($result as $item) {
  3631. $dbData = [
  3632. 'mid' => (int)$item['mid'],
  3633. 'collectorid' => (int)$item['collectorid'],
  3634. 'description' => $item['description']
  3635. ];
  3636. $exists = Db::name('电表设备列表')->where('mid', $dbData['mid'])->find();
  3637. if ($exists) {
  3638. Db::name('电表设备列表')
  3639. ->where('mid', $dbData['mid'])
  3640. ->update($dbData);
  3641. } else {
  3642. Db::name('电表设备列表')->insert($dbData);
  3643. }
  3644. }
  3645. }
  3646. /**
  3647. * 同步电表能耗数据小时数据
  3648. * 查询指定月份的电表能耗小时数据
  3649. */
  3650. public function StatisticEle_Hour()
  3651. {
  3652. if (!$this->request->isGet()) {
  3653. $this->error('非法请求');
  3654. }
  3655. $params = $this->request->get();
  3656. $filterMid = $params['mid'] ?? null;
  3657. // // 默认当天
  3658. $startDate = $params['riqi'] ?? date('Ymd');
  3659. $endDate = $params['riqi'] ?? date('Ymd');
  3660. // 验证日期格式
  3661. if (!preg_match('/^\d{8}$/', $startDate) || !preg_match('/^\d{8}$/', $endDate)) {
  3662. $this->error('参数格式错误');
  3663. }
  3664. // 确保开始日期不大于结束日期
  3665. if ($startDate > $endDate) {
  3666. $this->error('开始日期不能大于结束日期');
  3667. }
  3668. $startTime = $startDate . '00'; // 从开始日期的00点开始
  3669. $endTime = $endDate . '23'; // 到结束日期的23点结束
  3670. $url = "http://api1.tqdianbiao.com/Api/StatisticEle/hour?auth=a15dbee8d66bf1b4149637e3912bf631&type=json&ignore_radio=0&start_time={$startTime}&end_time={$endTime}";
  3671. try {
  3672. $resultData = $this->httpGetRequest($url);
  3673. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3674. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3675. }
  3676. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3677. throw new Exception('API返回数据格式不正确');
  3678. }
  3679. $rawData = $resultData['data'];
  3680. $result = [];
  3681. foreach ($rawData as $date => $records) {
  3682. foreach ($records as $row) {
  3683. $result[] = [
  3684. '日期' => $date,
  3685. '电表ID' => $row['mid'] ?? '',
  3686. '开始时间' => $row['st'] ?? '',
  3687. '结束时间' => $row['et'] ?? '',
  3688. '互感器变比' => $row['r'] ?? 1,
  3689. '总电量' => $row['d'][0] ?? 0,
  3690. '尖电量' => $row['d'][1] ?? 0,
  3691. '峰电量' => $row['d'][2] ?? 0,
  3692. '平电量' => $row['d'][3] ?? 0,
  3693. '谷电量' => $row['d'][4] ?? 0,
  3694. '起始总电量' => $row['s'][0] ?? 0,
  3695. '结束总电量' => $row['e'][0] ?? 0
  3696. ];
  3697. }
  3698. }
  3699. // 按日期时间倒序排序
  3700. usort($result, function ($a, $b) {
  3701. $timeA = strtotime($a['开始时间']);
  3702. $timeB = strtotime($b['开始时间']);
  3703. return $timeB - $timeA;
  3704. });
  3705. // 直接保存到数据库
  3706. $insertCount = 0;
  3707. $updateCount = 0;
  3708. $errorCount = 0;
  3709. if (!empty($result)) {
  3710. foreach ($result as $index => $item) {
  3711. $sql = '';
  3712. try {
  3713. Log::info("=== 处理第 {$index} 条数据 ===");
  3714. // 准备数据库数据
  3715. $dbData = [
  3716. '电表ID' => (string)$item['电表ID'],
  3717. '互感器变比' => (string)$item['互感器变比'],
  3718. '总电量' => (string)$item['总电量'],
  3719. '尖电量' => (string)$item['尖电量'],
  3720. '峰电量' => (string)$item['峰电量'],
  3721. '平电量' => (string)$item['平电量'],
  3722. '谷电量' => (string)$item['谷电量'],
  3723. '起始总电量' => (string)$item['起始总电量'],
  3724. '结束总电量' => (string)$item['结束总电量'],
  3725. '开始时间' => $item['开始时间'],
  3726. '结束时间' => $item['结束时间'],
  3727. '日期' => (string)$item['日期']
  3728. ];
  3729. Log::info('处理数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3730. // 检查记录是否已存在 - 使用电表ID、开始时间和结束时间作为唯一标识
  3731. $exists = Db::name('电表能耗小时数据')
  3732. ->where('电表ID', $dbData['电表ID'])
  3733. ->where('开始时间', $dbData['开始时间'])
  3734. ->where('结束时间', $dbData['结束时间'])
  3735. ->find();
  3736. Log::info('查询条件: 电表ID=' . $dbData['电表ID'] . ', 开始时间=' . $dbData['开始时间'] . ', 结束时间=' . $dbData['结束时间']);
  3737. Log::info('查询结果: ' . ($exists ? '记录存在, ID=' . $exists['id'] : '记录不存在'));
  3738. if ($exists) {
  3739. // 检查数据是否有变化,有变化才更新
  3740. $needUpdate = false;
  3741. $updateFields = [];
  3742. $fieldsToCompare = [
  3743. '互感器变比', '总电量', '尖电量', '峰电量', '平电量', '谷电量',
  3744. '起始总电量', '结束总电量', '日期'
  3745. ];
  3746. foreach ($fieldsToCompare as $field) {
  3747. $oldValue = $exists[$field] ?? '';
  3748. $newValue = $dbData[$field] ?? '';
  3749. if ($oldValue != $newValue) {
  3750. $needUpdate = true;
  3751. $updateFields[$field] = $newValue;
  3752. Log::info("字段 {$field} 有变化: '{$oldValue}' -> '{$newValue}'");
  3753. }
  3754. }
  3755. if ($needUpdate) {
  3756. $sql = Db::name('电表能耗小时数据')
  3757. ->where('id', $exists['id'])
  3758. ->fetchSql(true)
  3759. ->update($updateFields);
  3760. Log::info('执行更新SQL: ' . $sql);
  3761. $updateResult = \db()->query($sql);
  3762. Log::info('更新结果: ' . ($updateResult !== false ? '成功' : '失败'));
  3763. $updateCount++;
  3764. } else {
  3765. Log::info('数据无变化,跳过更新');
  3766. }
  3767. } else {
  3768. // 插入新记录
  3769. $sql = Db::name('电表能耗小时数据')->fetchSql(true)->insert($dbData);
  3770. Log::info('执行插入SQL: ' . $sql);
  3771. $insertResult = \db()->query($sql);
  3772. Log::info('插入结果: ' . ($insertResult !== false ? '成功' : '失败'));
  3773. if ($insertResult !== false) {
  3774. $insertCount++;
  3775. } else {
  3776. throw new Exception('插入操作返回false');
  3777. }
  3778. }
  3779. Log::info("=== 第 {$index} 条数据处理完成 ===\n");
  3780. } catch (Exception $e) {
  3781. $errorCount++;
  3782. Log::error("=== 第 {$index} 条数据处理失败 ===");
  3783. Log::error('错误信息: ' . $e->getMessage());
  3784. Log::error('失败数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3785. Log::error('执行SQL: ' . $sql);
  3786. Log::error('错误位置: ' . $e->getFile() . ':' . $e->getLine());
  3787. Log::error("=== 第 {$index} 条数据处理结束 ===\n");
  3788. }
  3789. }
  3790. }
  3791. $saveMessage = "数据保存完成 - 新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条";
  3792. $this->success($saveMessage, [
  3793. 'data' => $result,
  3794. ]);
  3795. } catch (Exception $e) {
  3796. $this->error('请求失败: ' . $e->getMessage());
  3797. }
  3798. }
  3799. /**
  3800. * 同步电表能耗数据小时数据
  3801. * 查询指定月份的电表能耗日数据
  3802. */
  3803. public function StatisticEle_Day()
  3804. {
  3805. if (!$this->request->isGet()) {
  3806. $this->error('非法请求');
  3807. }
  3808. $params = $this->request->get();
  3809. $filterMid = $params['mid'] ?? null;
  3810. $riqi = $params['riqi'] ?? date('Ym'); // 默认当前年月
  3811. if (!preg_match('/^\d{6}$/', $riqi)) {
  3812. $this->error('参数 riqi 格式错误,应为 YYYYMM');
  3813. }
  3814. // 构造 start_time
  3815. $startTime = $riqi . '01';
  3816. // 判断是当前月还是历史月
  3817. $currentMonth = date('Ym');
  3818. if ($riqi === $currentMonth) {
  3819. $endTime = date('Ymd'); // 今天
  3820. } else {
  3821. $endTime = date('Ymd', strtotime("last day of {$riqi}01")); // 历史月最后一天
  3822. }
  3823. // 构造 API 请求 URL - 查询指定月份的电表能耗日数据
  3824. $url = "http://api1.tqdianbiao.com/Api/StatisticEle/day?auth=a15dbee8d66bf1b4149637e3912bf631&type=json&ignore_radio=0&start_time={$startTime}&end_time={$endTime}";
  3825. try {
  3826. $resultData = $this->httpGetRequest($url);
  3827. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3828. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3829. }
  3830. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3831. throw new Exception('API返回数据格式不正确');
  3832. }
  3833. $rawData = $resultData['data'];
  3834. $result = [];
  3835. foreach ($rawData as $date => $records) {
  3836. foreach ($records as $row) {
  3837. $result[] = [
  3838. '日期' => $date,
  3839. '电表ID' => $row['mid'] ?? '',
  3840. '开始时间' => $row['st'] ?? '',
  3841. '结束时间' => $row['et'] ?? '',
  3842. '互感器变比' => $row['r'] ?? 1,
  3843. '总电量' => $row['d'][0] ?? 0,
  3844. '尖电量' => $row['d'][1] ?? 0,
  3845. '峰电量' => $row['d'][2] ?? 0,
  3846. '平电量' => $row['d'][3] ?? 0,
  3847. '谷电量' => $row['d'][4] ?? 0,
  3848. '起始总电量' => $row['s'][0] ?? 0,
  3849. '结束总电量' => $row['e'][0] ?? 0
  3850. ];
  3851. }
  3852. }
  3853. usort($result, function ($a, $b) {
  3854. return strcmp($b['日期'], $a['日期']);
  3855. });
  3856. // 直接保存到数据库
  3857. $insertCount = 0;
  3858. $updateCount = 0;
  3859. $errorCount = 0;
  3860. if (!empty($result)) {
  3861. foreach ($result as $index => $item) {
  3862. $sql = '';
  3863. try {
  3864. Log::info("=== 处理第 {$index} 条数据 ===");
  3865. // 准备数据库数据 - 修正字段名为大写
  3866. $dbData = [
  3867. '电表ID' => (string)$item['电表ID'], // 修正:电表ID(大写)
  3868. '互感器变比' => (string)$item['互感器变比'],
  3869. '总电量' => (string)$item['总电量'],
  3870. '尖电量' => (string)$item['尖电量'],
  3871. '峰电量' => (string)$item['峰电量'],
  3872. '平电量' => (string)$item['平电量'],
  3873. '谷电量' => (string)$item['谷电量'],
  3874. '起始总电量' => (string)$item['起始总电量'],
  3875. '结束总电量' => (string)$item['结束总电量'],
  3876. '开始时间' => $item['开始时间'],
  3877. '结束时间' => $item['结束时间'],
  3878. '日期' => (string)$item['日期']
  3879. ];
  3880. Log::info('处理数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3881. // 检查记录是否已存在 - 使用正确的字段名
  3882. $exists = Db::name('电表能耗日数据')
  3883. ->where('电表ID', $dbData['电表ID']) // 修正:电表ID(大写)
  3884. ->where('日期', $dbData['日期'])
  3885. ->find();
  3886. Log::info('查询条件: 电表ID=' . $dbData['电表ID'] . ', 日期=' . $dbData['日期']);
  3887. Log::info('查询结果: ' . ($exists ? '记录存在, ID=' . $exists['id'] : '记录不存在'));
  3888. if ($exists) {
  3889. // 检查数据是否有变化,有变化才更新
  3890. $needUpdate = false;
  3891. $updateFields = [];
  3892. $fieldsToCompare = [
  3893. '互感器变比', '总电量', '尖电量', '峰电量', '平电量', '谷电量',
  3894. '起始总电量', '结束总电量', '开始时间', '结束时间'
  3895. ];
  3896. foreach ($fieldsToCompare as $field) {
  3897. $oldValue = $exists[$field] ?? '';
  3898. $newValue = $dbData[$field] ?? '';
  3899. if ($oldValue != $newValue) {
  3900. $needUpdate = true;
  3901. $updateFields[$field] = $newValue;
  3902. Log::info("字段 {$field} 有变化: '{$oldValue}' -> '{$newValue}'");
  3903. }
  3904. }
  3905. if ($needUpdate) {
  3906. $sql = Db::name('电表能耗日数据')
  3907. ->where('id', $exists['id'])
  3908. ->fetchSql(true)
  3909. ->update($updateFields);
  3910. Log::info('执行更新SQL: ' . $sql);
  3911. $updateResult = \db()->query($sql);
  3912. Log::info('更新结果: ' . ($updateResult !== false ? '成功' : '失败'));
  3913. $updateCount++;
  3914. } else {
  3915. Log::info('数据无变化,跳过更新');
  3916. }
  3917. } else {
  3918. // 插入新记录
  3919. $sql = Db::name('电表能耗日数据')->fetchSql(true)->insert($dbData);
  3920. Log::info('执行插入SQL: ' . $sql);
  3921. $insertResult = \db()->query($sql);
  3922. Log::info('插入结果: ' . ($insertResult !== false ? '成功' : '失败'));
  3923. if ($insertResult !== false) {
  3924. $insertCount++;
  3925. } else {
  3926. throw new Exception('插入操作返回false');
  3927. }
  3928. }
  3929. Log::info("=== 第 {$index} 条数据处理完成 ===\n");
  3930. } catch (Exception $e) {
  3931. $errorCount++;
  3932. Log::error("=== 第 {$index} 条数据处理失败 ===");
  3933. Log::error('错误信息: ' . $e->getMessage());
  3934. Log::error('失败数据: ' . json_encode($dbData, JSON_UNESCAPED_UNICODE));
  3935. Log::error('执行SQL: ' . $sql);
  3936. Log::error('错误位置: ' . $e->getFile() . ':' . $e->getLine());
  3937. Log::error("=== 第 {$index} 条数据处理结束 ===\n");
  3938. }
  3939. }
  3940. }
  3941. Log::info("=== 最终统计 ===");
  3942. Log::info("新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条");
  3943. $saveMessage = "数据保存完成 - 新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条";
  3944. $this->success($saveMessage, [
  3945. 'data' => $result,
  3946. ]);
  3947. } catch (Exception $e) {
  3948. $this->error('请求失败: ' . $e->getMessage());
  3949. }
  3950. }
  3951. /**
  3952. * 同步电表能耗数据月数据
  3953. * 查询指定月份的电表能耗月数据
  3954. */
  3955. public function StatisticEle_Month()
  3956. {
  3957. if (!$this->request->isGet()) {
  3958. $this->error('非法请求');
  3959. }
  3960. $params = $this->request->get();
  3961. $filterMid = $params['mid'] ?? null;
  3962. $riqi = $params['riqi'] ?? date('Ym'); // 默认当前年月
  3963. if (!preg_match('/^\d{6}$/', $riqi)) {
  3964. $this->error('参数 riqi 格式错误,应为 YYYYMM');
  3965. }
  3966. // 构造 start_time 和 end_time - 月接口通常只需要月份参数,查询指定月份的所有数据
  3967. $startTime = $riqi . '01';
  3968. $endTime = $riqi . '31'; // 月数据通常查询单个月份
  3969. // 构造 API 请求 URL - 使用 month 接口查询指定月份的电表能耗月数据
  3970. $url = "http://api1.tqdianbiao.com/Api/StatisticEle/month?auth=a15dbee8d66bf1b4149637e3912bf631&type=json&ignore_radio=0&start_time={$startTime}&end_time={$endTime}";
  3971. try {
  3972. $resultData = $this->httpGetRequest($url);
  3973. if (!isset($resultData['status']) || $resultData['status'] != 1) {
  3974. throw new Exception('API返回状态异常: ' . ($resultData['message'] ?? '未知错误'));
  3975. }
  3976. if (!isset($resultData['data']) || !is_array($resultData['data'])) {
  3977. throw new Exception('API返回数据格式不正确');
  3978. }
  3979. $rawData = $resultData['data'];
  3980. $result = [];
  3981. foreach ($rawData as $date => $records) {
  3982. foreach ($records as $row) {
  3983. $result[] = [
  3984. '月份' => $date,
  3985. '电表ID' => $row['mid'] ?? '',
  3986. '开始时间' => $row['st'] ?? '',
  3987. '结束时间' => $row['et'] ?? '',
  3988. '互感器变比' => $row['r'] ?? 1,
  3989. '总电量' => $row['d'][0] ?? 0,
  3990. '尖电量' => $row['d'][1] ?? 0,
  3991. '峰电量' => $row['d'][2] ?? 0,
  3992. '平电量' => $row['d'][3] ?? 0,
  3993. '谷电量' => $row['d'][4] ?? 0,
  3994. '起始总电量' => $row['s'][0] ?? 0,
  3995. '结束总电量' => $row['e'][0] ?? 0
  3996. ];
  3997. }
  3998. }
  3999. usort($result, function ($a, $b) {
  4000. return strcmp($b['月份'], $a['月份']);
  4001. });
  4002. // 直接保存到数据库
  4003. $insertCount = 0;
  4004. $updateCount = 0;
  4005. $errorCount = 0;
  4006. if (!empty($result)) {
  4007. foreach ($result as $item) {
  4008. try {
  4009. $dbData = [
  4010. '电表ID' => (int)$item['电表ID'],
  4011. '互感器变比' => (string)$item['互感器变比'],
  4012. '总电量' => (string)$item['总电量'],
  4013. '尖电量' => (string)$item['尖电量'],
  4014. '峰电量' => (string)$item['峰电量'],
  4015. '平电量' => (string)$item['平电量'],
  4016. '谷电量' => (string)$item['谷电量'],
  4017. '起始总电量' => (string)$item['起始总电量'],
  4018. '结束总电量' => (string)$item['结束总电量'],
  4019. '开始时间' => $item['开始时间'],
  4020. '结束时间' => $item['结束时间'],
  4021. '日期' => $item['月份']
  4022. ];
  4023. // 查询是否已存在相同月份的记录
  4024. $exists = Db::name('电表能耗月数据')
  4025. ->where('电表ID', $dbData['电表ID'])
  4026. ->where('日期', $dbData['日期'])
  4027. ->find();
  4028. if ($exists) {
  4029. // 检查是否有字段值不同
  4030. $needUpdate = false;
  4031. $updateFields = [];
  4032. // 检查是否有字段值不同
  4033. $fieldsToCompare = [
  4034. '互感器变比', '总电量', '尖电量', '峰电量', '平电量', '谷电量',
  4035. '起始总电量', '结束总电量', '开始时间', '结束时间'
  4036. ];
  4037. foreach ($fieldsToCompare as $field) {
  4038. if (isset($exists[$field]) && isset($dbData[$field]) && $exists[$field] != $dbData[$field]) {
  4039. $needUpdate = true;
  4040. $updateFields[$field] = $dbData[$field];
  4041. }
  4042. }
  4043. if ($needUpdate) {
  4044. // 只更新有变化的字段
  4045. $sql = Db::name('电表能耗月数据')
  4046. ->where('id', $exists['id'])
  4047. ->fetchSql(true)
  4048. ->update($updateFields);
  4049. \db()->query($sql);
  4050. $updateCount++;
  4051. }
  4052. } else {
  4053. // 插入新记录
  4054. $sql = Db::name('电表能耗月数据')->fetchSql(true)->insert($dbData);
  4055. \db()->query($sql);
  4056. $insertCount++;
  4057. }
  4058. } catch (Exception $e) {
  4059. $errorCount++;
  4060. }
  4061. }
  4062. }
  4063. $saveMessage = "月数据保存完成 - 新增: {$insertCount}条, 更新: {$updateCount}条, 失败: {$errorCount}条";
  4064. $this->success($saveMessage, [
  4065. 'data' => $result,
  4066. ]);
  4067. } catch (Exception $e) {
  4068. $this->error('请求失败: ' . $e->getMessage());
  4069. }
  4070. }
  4071. /**
  4072. * 订单电量管理 - 左侧菜单
  4073. * 客户编号按自然顺序排序
  4074. * 返回年份分组的数据结构
  4075. */
  4076. public function CustomerMenu()
  4077. {
  4078. try {
  4079. $startDate = input('start_date', '');
  4080. $endDate = input('end_date', '');
  4081. $query = Db::name('设备_产量计酬')->alias('c')
  4082. ->field('c.订单编号, c.sys_rq, j.客户编号, DATE_FORMAT(c.sys_rq, "%Y%m") as date_group')
  4083. ->join('工单_基本资料 j', 'c.订单编号 = j.订单编号', 'LEFT')
  4084. ->whereNull('c.mod_rq')
  4085. ->whereNull('j.Mod_rq')
  4086. ->where('j.客户编号', '<>', '')
  4087. ->whereNotNull('j.客户编号');
  4088. if (!empty($startDate)) {
  4089. $query->where('c.sys_rq', '>=', $startDate);
  4090. }
  4091. if (!empty($endDate)) {
  4092. $query->where('c.sys_rq', '<=', $endDate);
  4093. }
  4094. $orderRecords = $query->select();
  4095. // 重新组织数据结构,按年份分组
  4096. $structuredData = [];
  4097. foreach ($orderRecords as $record) {
  4098. $yearMonth = $record['date_group'];
  4099. $customerNo = $record['客户编号'];
  4100. if ($yearMonth && $customerNo) {
  4101. $year = substr($yearMonth, 0, 4); // 提取年份
  4102. if (!isset($structuredData[$year])) {
  4103. $structuredData[$year] = [];
  4104. }
  4105. if (!isset($structuredData[$year][$yearMonth])) {
  4106. $structuredData[$year][$yearMonth] = [];
  4107. }
  4108. if (!in_array($customerNo, $structuredData[$year][$yearMonth])) {
  4109. $structuredData[$year][$yearMonth][] = $customerNo;
  4110. }
  4111. }
  4112. }
  4113. // 对每个月份的客户编号进行自然排序,并对月份按倒序排列
  4114. foreach ($structuredData as $year => &$months) {
  4115. foreach ($months as &$customers) {
  4116. natsort($customers);
  4117. $customers = array_values($customers);
  4118. }
  4119. // 对月份按倒序排列
  4120. krsort($months);
  4121. }
  4122. // 对年份按倒序排列
  4123. krsort($structuredData);
  4124. return json([
  4125. 'code' => 0,
  4126. 'msg' => '成功',
  4127. 'time' => time(),
  4128. 'data' => $structuredData
  4129. ]);
  4130. } catch (\Exception $e) {
  4131. return json([
  4132. 'code' => 1,
  4133. 'msg' => '查询失败: ' . $e->getMessage(),
  4134. 'time' => time(),
  4135. 'data' => []
  4136. ]);
  4137. }
  4138. }
  4139. /**
  4140. * 订单电量管理 - 汇总统计
  4141. */
  4142. public function OrderElectricitySummary(){
  4143. if (!$this->request->isGet()) {
  4144. $this->error('非法请求');
  4145. }
  4146. $params = $this->request->get();
  4147. $where = [];
  4148. if (!empty($params['order'])) {
  4149. $where['订单编号'] = $params['order'];
  4150. }
  4151. if (!empty($params['khbh'])) {
  4152. $where['客户编号'] = $params['khbh'];
  4153. }
  4154. $orders = Db::name('工单_基本资料')
  4155. ->field('订单编号,客户编号,生产款号')
  4156. ->where($where)
  4157. ->whereNull('Mod_rq')
  4158. ->select();
  4159. if (empty($orders)) {
  4160. $this->success('未查询到订单数据', []);
  4161. }
  4162. // 获取所有订单编号
  4163. $orderNumbers = array_column($orders, '订单编号');
  4164. // 首先查询每个订单的总产量和总时间范围
  4165. $orderTimeRanges = Db::name('设备_产量计酬')
  4166. ->field('订单编号,SUM(数量) as 总产量,MIN(sys_rq) as 最早报工时间,MAX(sys_rq) as 最晚报工时间,COUNT(*) as 总报工次数')
  4167. ->where('订单编号', 'in', $orderNumbers)
  4168. ->whereNull('mod_rq')
  4169. ->group('订单编号')
  4170. ->select();
  4171. // 构建订单时间范围映射
  4172. $orderTimeMap = [];
  4173. foreach ($orderTimeRanges as $timeRange) {
  4174. $orderTimeMap[$timeRange['订单编号']] = [
  4175. '总产量' => $timeRange['总产量'],
  4176. '最早报工时间' => $timeRange['最早报工时间'],
  4177. '最晚报工时间' => $timeRange['最晚报工时间'],
  4178. '总报工次数' => $timeRange['总报工次数']
  4179. ];
  4180. }
  4181. // 构建报工记录查询(按设备分组)
  4182. $orderRecordsQuery = Db::name('设备_产量计酬')
  4183. ->field('订单编号,sczl_bh,SUM(数量) as 总产量,MIN(sys_rq) as 最早报工时间,MAX(sys_rq) as 最晚报工时间,COUNT(*) as 报工次数')
  4184. ->where('订单编号', 'in', $orderNumbers)
  4185. ->whereNull('mod_rq');
  4186. // 如果有日期参数,按日期筛选报工记录
  4187. $startDate = null;
  4188. $endDate = null;
  4189. if (!empty($params['riqi'])) {
  4190. $date = $params['riqi'];
  4191. $startDate = date('Y-m-01', strtotime($date)); // 当月第一天
  4192. $endDate = date('Y-m-t 23:59:59', strtotime($date)); // 当月最后一天
  4193. $orderRecordsQuery->whereTime('sys_rq', 'between', [$startDate, $endDate]);
  4194. }
  4195. $orderRecords = $orderRecordsQuery->group('订单编号,sczl_bh')->select();
  4196. if (empty($orderRecords)) {
  4197. // 如果没有报工记录,只返回订单基本信息
  4198. $summary = [];
  4199. foreach ($orders as $order) {
  4200. $orderNumber = $order['订单编号'];
  4201. $timeInfo = $orderTimeMap[$orderNumber] ?? [
  4202. '总产量' => 0,
  4203. '最早报工时间' => null,
  4204. '最晚报工时间' => null,
  4205. '总报工次数' => 0
  4206. ];
  4207. $summary[] = [
  4208. '订单编号' => $orderNumber,
  4209. '生产款号' => $order['生产款号'],
  4210. '客户编号' => $order['客户编号'],
  4211. '累计总用电量' => 0,
  4212. '单位电量' => 0,
  4213. '生产时间段' => $timeInfo['最早报工时间'] ? ($timeInfo['最早报工时间'] . ' 至 ' . $timeInfo['最晚报工时间']) : '无生产记录'
  4214. ];
  4215. }
  4216. $this->success('成功', $summary);
  4217. }
  4218. // 获取所有涉及的设备编号
  4219. $sczlBhs = array_unique(array_column($orderRecords, 'sczl_bh'));
  4220. // 通过sczl_bh去电表设备列表表匹配对应的mid
  4221. $deviceMappings = Db::name('电表设备列表')
  4222. ->field('mid, collectorid, description')
  4223. ->where('description', 'in', $sczlBhs)
  4224. ->select();
  4225. $midMap = [];
  4226. $collectorIdMap = [];
  4227. foreach ($deviceMappings as $mapping) {
  4228. $midMap[$mapping['description']] = $mapping['mid'];
  4229. $collectorIdMap[$mapping['description']] = $mapping['collectorid'];
  4230. }
  4231. // 获取所有相关电表的能耗数据 - 使用mid来关联
  4232. $electricData = [];
  4233. if (!empty($midMap)) {
  4234. $mids = array_values($midMap);
  4235. $electricData = Db::name('电表能耗小时数据')
  4236. ->where('电表ID', 'in', $mids)
  4237. ->order('开始时间', 'asc')
  4238. ->select();
  4239. }
  4240. // 按订单编号分组统计总电量
  4241. $orderStats = [];
  4242. // 初始化订单统计
  4243. foreach ($orders as $order) {
  4244. $orderNumber = $order['订单编号'];
  4245. $timeInfo = $orderTimeMap[$orderNumber] ?? [
  4246. '总产量' => 0,
  4247. '最早报工时间' => null,
  4248. '最晚报工时间' => null,
  4249. '总报工次数' => 0
  4250. ];
  4251. $orderStats[$orderNumber] = [
  4252. '订单编号' => $orderNumber,
  4253. '生产款号' => $order['生产款号'],
  4254. '客户编号' => $order['客户编号'],
  4255. '总电量' => 0,
  4256. '总产量' => $timeInfo['总产量'],
  4257. '最早报工时间' => $timeInfo['最早报工时间'],
  4258. '最晚报工时间' => $timeInfo['最晚报工时间']
  4259. ];
  4260. }
  4261. // 统计每个订单的总电量(使用与明细查询相同的逻辑)
  4262. foreach ($orderRecords as $record) {
  4263. $orderNumber = $record['订单编号'];
  4264. $sczlBh = $record['sczl_bh'];
  4265. if (!isset($orderStats[$orderNumber])) {
  4266. continue;
  4267. }
  4268. // 获取对应的电表mid
  4269. $mid = $midMap[$sczlBh] ?? null;
  4270. if (!$mid) {
  4271. continue;
  4272. }
  4273. // 使用订单总时间范围而不是设备小组的时间范围
  4274. $orderTimeInfo = $orderTimeMap[$orderNumber] ?? null;
  4275. if (!$orderTimeInfo) {
  4276. continue;
  4277. }
  4278. $deviceStart = strtotime($orderTimeInfo['最早报工时间']);
  4279. $deviceEnd = strtotime($orderTimeInfo['最晚报工时间']);
  4280. $deviceElectricity = 0;
  4281. foreach ($electricData as $elec) {
  4282. // 正确的比较:电表能耗数据中的电表ID应该等于设备对应的mid
  4283. if ($elec['电表ID'] != $mid) {
  4284. continue;
  4285. }
  4286. $elecStart = strtotime($elec['开始时间']);
  4287. $elecEnd = strtotime($elec['结束时间']);
  4288. // 匹配电表时间段在订单总生产时间段范围内
  4289. if ($elecStart >= $deviceStart && $elecEnd <= $deviceEnd) {
  4290. $deviceElectricity += $elec['总电量'];
  4291. }
  4292. }
  4293. $orderStats[$orderNumber]['总电量'] += $deviceElectricity;
  4294. }
  4295. // 格式化输出结果,并过滤掉总电量为0的记录
  4296. $summary = [];
  4297. foreach ($orderStats as $order) {
  4298. // 只有当总电量大于0时才添加到结果中
  4299. if ($order['总电量'] > 0) {
  4300. $summary[] = [
  4301. '订单编号' => $order['订单编号'],
  4302. '生产款号' => $order['生产款号'],
  4303. '客户编号' => $order['客户编号'],
  4304. '累计总用电量' => round($order['总电量'], 2),
  4305. '单位电量' => $order['总产量'] > 0 ? round($order['总电量'] / $order['总产量'], 4) : 0,
  4306. '生产时间段' => $order['最早报工时间'] ? ($order['最早报工时间'] . ' 至 ' . $order['最晚报工时间']) : '无生产记录'
  4307. ];
  4308. }
  4309. }
  4310. $this->success('成功', $summary);
  4311. }
  4312. /**
  4313. * 订单电量管理 - 明细查询
  4314. */
  4315. public function OrderElectricityDetail(){
  4316. if (!$this->request->isGet()) {
  4317. $this->error('非法请求');
  4318. }
  4319. $params = $this->request->get();
  4320. if (empty($params['order'])) {
  4321. $this->error('订单编号不能为空');
  4322. }
  4323. // 查询订单的基本信息
  4324. $orderInfo = Db::name('工单_基本资料')
  4325. ->field('订单编号,生产款号,客户编号')
  4326. ->where('订单编号', $params['order'])
  4327. ->whereNull('Mod_rq')
  4328. ->find();
  4329. if (!$orderInfo) {
  4330. $this->error('订单不存在');
  4331. }
  4332. // 查询该订单的所有报工记录,按设备分组
  4333. $orderRecords = Db::name('设备_产量计酬')
  4334. ->field('订单编号,sczl_bh,
  4335. CASE
  4336. WHEN 工序名称 IN ("裁剪", "车缝") THEN SUM(数量)
  4337. ELSE SUM(s_num)
  4338. END as 总产量,MIN(sys_rq) as 最早报工时间,MAX(sys_rq) as 最晚报工时间,COUNT(*) as 报工次数')
  4339. ->where('订单编号', $params['order'])
  4340. ->whereNull('mod_rq')
  4341. ->group('sczl_bh')
  4342. ->select();
  4343. if (empty($orderRecords)) {
  4344. $this->success('成功', [
  4345. '订单信息' => $orderInfo,
  4346. '明细数据' => []
  4347. ]);
  4348. }
  4349. // 获取所有涉及的设备编号
  4350. $sczlBhs = array_column($orderRecords, 'sczl_bh');
  4351. // 通过sczl_bh去电表设备列表表匹配对应的mid
  4352. $deviceMappings = Db::name('电表设备列表')
  4353. ->field('mid, collectorid, description')
  4354. ->where('description', 'in', $sczlBhs)
  4355. ->select();
  4356. $midMap = [];
  4357. $collectorIdMap = [];
  4358. foreach ($deviceMappings as $mapping) {
  4359. $midMap[$mapping['description']] = $mapping['mid'];
  4360. $collectorIdMap[$mapping['description']] = $mapping['collectorid'];
  4361. }
  4362. // 获取所有相关电表的能耗数据 - 使用mid来关联
  4363. $electricData = [];
  4364. if (!empty($midMap)) {
  4365. $mids = array_values($midMap);
  4366. $electricData = Db::name('电表能耗小时数据')
  4367. ->where('电表ID', 'in', $mids) // 这里电表ID对应的是mid
  4368. ->order('开始时间', 'asc')
  4369. ->select();
  4370. }
  4371. // 组织明细数据
  4372. $details = [];
  4373. $orderTotalElectricity = 0;
  4374. $orderTotalOutput = 0;
  4375. // 定义设备小组的固定排序
  4376. $deviceOrder = [
  4377. '裁剪' => 1,
  4378. '车缝' => 2,
  4379. '手工' => 3,
  4380. '大烫' => 4,
  4381. '总检' => 5,
  4382. '包装' => 6
  4383. ];
  4384. foreach ($orderRecords as $record) {
  4385. $sczlBh = $record['sczl_bh'];
  4386. $mid = $midMap[$sczlBh] ?? null;
  4387. $collectorId = $collectorIdMap[$sczlBh] ?? null;
  4388. $deviceElectricity = 0;
  4389. $matchedHours = 0;
  4390. $hourlyDetails = [];
  4391. if ($mid && !empty($electricData)) {
  4392. $deviceStart = strtotime($record['最早报工时间']);
  4393. $deviceEnd = strtotime($record['最晚报工时间']);
  4394. // 筛选该设备在报工期间的电表数据
  4395. foreach ($electricData as $elec) {
  4396. // 正确的比较:电表能耗数据中的电表ID应该等于设备对应的mid
  4397. if ($elec['电表ID'] != $mid) {
  4398. continue;
  4399. }
  4400. $elecStart = strtotime($elec['开始时间']);
  4401. $elecEnd = strtotime($elec['结束时间']);
  4402. // 匹配电表时间段在设备生产时间段范围内
  4403. if ($elecStart >= $deviceStart && $elecEnd <= $deviceEnd) {
  4404. $deviceElectricity += $elec['总电量'];
  4405. $matchedHours++;
  4406. $hourlyDetails[] = [
  4407. '电表时间段' => $elec['开始时间'] . ' - ' . $elec['结束时间'],
  4408. '电量' => round($elec['总电量'], 2),
  4409. '日期' => $elec['日期']
  4410. ];
  4411. }
  4412. }
  4413. }
  4414. // 如果累计用电量为空或0,跳过不显示
  4415. if (empty($deviceElectricity)) {
  4416. continue;
  4417. }
  4418. $orderTotalElectricity += $deviceElectricity;
  4419. $orderTotalOutput += $record['总产量'];
  4420. // 确定设备类型和排序权重
  4421. $deviceType = '';
  4422. $sortWeight = 999; // 默认权重,排在最后
  4423. foreach ($deviceOrder as $type => $weight) {
  4424. if (strpos($sczlBh, $type) !== false) {
  4425. $deviceType = $type;
  4426. $sortWeight = $weight;
  4427. break;
  4428. }
  4429. }
  4430. // 改进的设备序号提取方法
  4431. $deviceNumber = 0;
  4432. if (preg_match('/\d+/', $sczlBh, $matches)) {
  4433. $deviceNumber = intval($matches[0]);
  4434. }
  4435. $details[] = [
  4436. '订单编号' => $record['订单编号'],
  4437. '设备小组' => $sczlBh,
  4438. '电表ID' => $mid,
  4439. '采集器ID' => $collectorId,
  4440. '生产款号' => $orderInfo['生产款号'],
  4441. '产量' => $record['总产量'],
  4442. '累计用电量' => round($deviceElectricity, 2),
  4443. '单位电量' => $record['总产量'] > 0 ? round($deviceElectricity / $record['总产量'], 4) : 0,
  4444. '生产时间段' => $record['最早报工时间'] . ' 至 ' . $record['最晚报工时间'],
  4445. '报工次数' => $record['报工次数'],
  4446. '匹配小时数' => $matchedHours,
  4447. // 用于排序的字段
  4448. '_sort_weight' => $sortWeight,
  4449. '_device_number' => $deviceNumber,
  4450. '_device_name' => $sczlBh // 添加设备名称用于调试
  4451. ];
  4452. }
  4453. // 按照设备类型和序号排序
  4454. usort($details, function($a, $b) {
  4455. // 首先按设备类型排序
  4456. if ($a['_sort_weight'] != $b['_sort_weight']) {
  4457. return $a['_sort_weight'] - $b['_sort_weight'];
  4458. }
  4459. // 然后按设备序号排序
  4460. if ($a['_device_number'] != $b['_device_number']) {
  4461. return $a['_device_number'] - $b['_device_number'];
  4462. }
  4463. // 最后按设备名称排序(确保完全一致)
  4464. return strcmp($a['_device_name'], $b['_device_name']);
  4465. });
  4466. // 移除排序用的临时字段
  4467. foreach ($details as &$item) {
  4468. unset($item['_sort_weight']);
  4469. unset($item['_device_number']);
  4470. unset($item['_device_name']);
  4471. }
  4472. $result = [
  4473. 'list' => $details
  4474. ];
  4475. $this->success('成功', $result);
  4476. }
  4477. //成品入仓左侧菜单
  4478. public function Finished_Datalist(){
  4479. // 获取成品入仓表中的所有数据
  4480. $data = Db::name('成品入仓')
  4481. ->field('sys_rq')
  4482. ->whereNull('mod_rq')
  4483. ->select();
  4484. // 按年、年月、年月日构建嵌套数据结构
  4485. $dateData = [];
  4486. foreach ($data as $item) {
  4487. if (!empty($item['sys_rq'])) {
  4488. $date = $item['sys_rq'];
  4489. $year = date('Y', strtotime($date));
  4490. $yearMonth = date('Y-m', strtotime($date));
  4491. $yearMonthDay = date('Y-m-d', strtotime($date));
  4492. // 初始化年、年月、年月日的数据结构
  4493. if (!isset($dateData[$year])) {
  4494. $dateData[$year] = [];
  4495. }
  4496. if (!isset($dateData[$year][$yearMonth])) {
  4497. $dateData[$year][$yearMonth] = [];
  4498. }
  4499. // 添加年月日到对应年月数组中,避免重复
  4500. if (!in_array($yearMonthDay, $dateData[$year][$yearMonth])) {
  4501. $dateData[$year][$yearMonth][] = $yearMonthDay;
  4502. }
  4503. }
  4504. }
  4505. // 对年月日数组进行降序排序(最近的日期在前面)
  4506. foreach ($dateData as $year => $yearMonths) {
  4507. foreach ($yearMonths as $yearMonth => $days) {
  4508. rsort($dateData[$year][$yearMonth]);
  4509. }
  4510. // 对年月进行降序排序
  4511. krsort($dateData[$year]);
  4512. }
  4513. // 对年进行降序排序
  4514. krsort($dateData);
  4515. // 构建响应
  4516. $res['code'] = 0;
  4517. $res['msg'] = '成功';
  4518. $res['time'] = time(); // 当前时间戳
  4519. $res['data'] = $dateData;
  4520. return json($res);
  4521. }
  4522. //成品入仓列表数据
  4523. public function Finished_Product(){
  4524. if (!$this->request->isGet()) {
  4525. $this->error('请求方式错误');
  4526. }
  4527. $params = $this->request->param();
  4528. $search = input('order', '');
  4529. $page = input('page', 1, 'intval');
  4530. $limit = input('limit', 10, 'intval');
  4531. $where = [];
  4532. if (!empty($search)) {
  4533. $where['a.order|j.生产款号|j.款式'] = ['like', '%' . $search . '%'];
  4534. }
  4535. if (!empty($params['date'])) {
  4536. $where['a.sys_rq'] = ['like', "%{$params['date']}%"];
  4537. }
  4538. // 计算总记录数(去重后的订单数量)
  4539. $total = Db::name('成品入仓')->alias('a')
  4540. ->join('工单_基本资料 j', 'a.order=j.订单编号', 'left')
  4541. ->where($where)
  4542. ->group('a.order')
  4543. ->count();
  4544. // 查询数据,对相同订单分组并求和成品数量
  4545. $list = Db::name('成品入仓')->alias('a')
  4546. ->field('
  4547. a.order as 订单编号,
  4548. SUM(a.sl) as 成品数量,
  4549. j.生产款号,
  4550. j.款式,
  4551. j.订单数量
  4552. ')
  4553. ->join('工单_基本资料 j', 'a.order=j.订单编号', 'left')
  4554. ->where($where)
  4555. ->group('a.order')
  4556. ->limit(($page - 1) * $limit, $limit)
  4557. ->select();
  4558. // 计算未入仓数量和入仓率
  4559. foreach ($list as &$item) {
  4560. $item['未入仓数量'] = $item['订单数量'] - $item['成品数量'];
  4561. // 计算入仓率(成品数量 / 订单数量 * 100%),保留2位小数
  4562. $item['入仓率'] = $item['订单数量'] > 0 ? round(($item['成品数量'] / $item['订单数量']) * 100, 2) . '%' : '0%';
  4563. }
  4564. $res['code'] = 0;
  4565. $res['msg'] = '成功';
  4566. $res['count'] = $total;
  4567. $res['data'] = $list;
  4568. return json($res);
  4569. }
  4570. //面料库存列表
  4571. public function GetFabric(){
  4572. if (!$this->request->isGet()) {
  4573. $this->error('请求方式错误');
  4574. }
  4575. $params = $this->request->param();
  4576. $search = input('search', '');
  4577. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4578. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4579. $where = [];
  4580. if (!empty($search)) {
  4581. $where['物料编号|物料名称'] = ['like', '%' . $search . '%'];
  4582. }
  4583. $list = Db::name('物料_库存')
  4584. ->where($where)
  4585. ->whereNull('Mod_rq')
  4586. ->limit(($page - 1) * $limit, $limit)
  4587. ->select();
  4588. $total = Db::name('物料_库存')->whereNull('Mod_rq')->where($where) ->count();
  4589. $res['code'] = 0;
  4590. $res['msg'] = '成功';
  4591. $res['count'] = $total;
  4592. $res['data'] = $list;
  4593. return json($res);
  4594. }
  4595. //面料库存分析
  4596. public function GetAPIFabric(){
  4597. // 查询所有物料库存数据
  4598. $allItems = Db::name('物料_库存')
  4599. ->field('物料名称,库存数量,入仓总量,领用数量,退还数量,单位')
  4600. ->order('Sys_rq desc')
  4601. ->whereNull('Mod_rq')
  4602. ->select();
  4603. // 按物料名称分组并累加库存数量
  4604. $groupedData = [];
  4605. foreach ($allItems as $item) {
  4606. $materialName = $item['物料名称'];
  4607. if (!isset($groupedData[$materialName])) {
  4608. // 初始化新的物料记录
  4609. $groupedData[$materialName] = [
  4610. '物料名称' => $materialName,
  4611. '库存数量' => 0,
  4612. '入仓总量' => 0,
  4613. '领用数量' => 0,
  4614. '退还数量' => 0,
  4615. '单位' => $item['单位']
  4616. ];
  4617. }
  4618. // 累加各项数量(确保转换为数字类型)
  4619. $groupedData[$materialName]['库存数量'] += floatval($item['库存数量']);
  4620. $groupedData[$materialName]['入仓总量'] += floatval($item['入仓总量']);
  4621. $groupedData[$materialName]['领用数量'] += floatval($item['领用数量']);
  4622. $groupedData[$materialName]['退还数量'] += floatval($item['退还数量'] ?? 0);
  4623. }
  4624. // 将关联数组转换为索引数组
  4625. $sortedList = array_values($groupedData);
  4626. // 按库存数量降序排序,确保库存最多的物料显示在最前面
  4627. usort($sortedList, function($a, $b) {
  4628. return $b['库存数量'] - $a['库存数量'];
  4629. });
  4630. // 格式化数值字段,保留两位小数
  4631. foreach ($sortedList as &$item) {
  4632. $item['库存数量'] = round($item['库存数量'], 2);
  4633. $item['入仓总量'] = round($item['入仓总量'], 2);
  4634. $item['领用数量'] = round($item['领用数量'], 2);
  4635. $item['退还数量'] = round($item['退还数量'], 2);
  4636. }
  4637. // 限制只返回前20个物料
  4638. $limitedList = array_slice($sortedList, 0, 20);
  4639. $res['code'] = 0;
  4640. $res['msg'] = '成功';
  4641. $res['data'] = $limitedList;
  4642. return json($res);
  4643. }
  4644. //Bom资料列表
  4645. public function Get_BomList(){
  4646. if (!$this->request->isGet()) {
  4647. $this->error('请求方式错误');
  4648. }
  4649. $params = $this->request->param();
  4650. $search = input('search', '');
  4651. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4652. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4653. $where = [];
  4654. if (!empty($search)) {
  4655. $where['a.BOM_工单编号|a.物料分类|a.BOM_desc'] = ['like', '%' . $search . '%'];
  4656. }
  4657. $list = Db::name('工单_bom资料')->alias('a')
  4658. ->field('
  4659. a.BOM_工单编号 as 订单编号,
  4660. a.物料分类,
  4661. a.BOM_物料名称 as 物料名称,
  4662. a.BOM_计划用量 as 计划用料,
  4663. a.BOM_计划门幅 as 计划门幅,
  4664. a.BOM_标准用量 as 定额用料,
  4665. a.BOM_定额门幅 as 定额门幅,
  4666. a.BOM_desc as 备注,
  4667. j.生产款号,
  4668. j.款式
  4669. ')
  4670. ->join('工单_基本资料 j', 'a.BOM_工单编号 = j.订单编号', 'left')
  4671. ->where($where)
  4672. ->limit(($page - 1) * $limit, $limit)
  4673. ->order('a.Sys_rq desc')
  4674. ->whereNull('a.Mod_rq')
  4675. ->select();
  4676. $total = Db::name('工单_bom资料')->alias('a')
  4677. ->whereNull('Mod_rq')
  4678. ->where($where)
  4679. ->count();
  4680. $res['code'] = 0;
  4681. $res['msg'] = '成功';
  4682. $res['count'] = $total;
  4683. $res['data'] = $list;
  4684. return json($res);
  4685. }
  4686. //查询订单进度情况
  4687. public function GetOrderprogress(){
  4688. if (!$this->request->isGet()) {
  4689. $this->error('请求方式错误');
  4690. }
  4691. $params = $this->request->param();
  4692. $search = input('search', '');
  4693. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4694. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4695. $where = [];
  4696. if (!empty($search)) {
  4697. $where['a.订单编号|a.客户编号|a.生产款号|a.款式'] = ['like', '%' . $search . '%'];
  4698. }
  4699. // 获取所有订单基本信息(先分页)
  4700. $orders = Db::name('工单_基本资料')->alias('a')
  4701. ->field('
  4702. a.订单编号,
  4703. a.客户编号,
  4704. a.生产款号,
  4705. a.款式,
  4706. a.img,
  4707. a.订单数量
  4708. ')
  4709. ->whereNull('a.Mod_rq')
  4710. ->where($where)
  4711. ->limit(($page - 1) * $limit, $limit)
  4712. ->order('a.Sys_rq desc')
  4713. ->select();
  4714. $total = Db::name('工单_基本资料')->alias('a')
  4715. ->whereNull('Mod_rq')
  4716. ->where($where)
  4717. ->count();
  4718. if (empty($orders)) {
  4719. $res['code'] = 0;
  4720. $res['msg'] = '成功';
  4721. $res['count'] = $total;
  4722. $res['data'] = [];
  4723. return json($res);
  4724. }
  4725. // 提取订单编号列表
  4726. $orderNumbers = array_column($orders, '订单编号');
  4727. // 获取这些订单的所有报工数据
  4728. $reportData = Db::name('设备_产量计酬')->alias('c')
  4729. ->field('
  4730. c.订单编号,
  4731. c.工序名称,
  4732. CASE
  4733. WHEN c.工序名称 IN ("裁剪", "车缝") THEN c.数量
  4734. ELSE c.s_num
  4735. END as 报工数量,
  4736. c.sczl_bh as 报工小组
  4737. ')
  4738. ->whereIn('c.订单编号', $orderNumbers)
  4739. ->whereNull('c.mod_rq')
  4740. ->select();
  4741. // 按订单编号和工序名称分组处理数据
  4742. $orderProcessReportMap = [];
  4743. foreach ($reportData as $item) {
  4744. $orderNo = $item['订单编号'];
  4745. $processName = $item['工序名称'];
  4746. if (!isset($orderProcessReportMap[$orderNo])) {
  4747. $orderProcessReportMap[$orderNo] = [
  4748. '工序列表' => [],
  4749. '工序报工数量' => [],
  4750. '工序报工小组' => [],
  4751. ];
  4752. }
  4753. // 初始化该工序的数据
  4754. if (!isset($orderProcessReportMap[$orderNo]['工序报工数量'][$processName])) {
  4755. $orderProcessReportMap[$orderNo]['工序报工数量'][$processName] = 0;
  4756. $orderProcessReportMap[$orderNo]['工序报工小组'][$processName] = [];
  4757. }
  4758. // 累加各工序的报工数量
  4759. $orderProcessReportMap[$orderNo]['工序报工数量'][$processName] += $item['报工数量'];
  4760. // 收集该工序的报工小组(去重)
  4761. if (!in_array($item['报工小组'], $orderProcessReportMap[$orderNo]['工序报工小组'][$processName])) {
  4762. $orderProcessReportMap[$orderNo]['工序报工小组'][$processName][] = $item['报工小组'];
  4763. }
  4764. }
  4765. // 将报工数据合并到订单数据中
  4766. $result = [];
  4767. foreach ($orders as $order) {
  4768. $orderNo = $order['订单编号'];
  4769. if (isset($orderProcessReportMap[$orderNo])) {
  4770. $report = $orderProcessReportMap[$orderNo];
  4771. // 将每个工序的名称和数量作为单独的字段
  4772. foreach ($report['工序报工数量'] as $process => $quantity) {
  4773. $order[$process] = $quantity;
  4774. }
  4775. // 将每个工序的报工小组作为单独的字段
  4776. foreach ($report['工序报工小组'] as $process => $groups) {
  4777. $order[$process . '小组'] = implode(',', $groups);
  4778. }
  4779. }
  4780. $result[] = $order;
  4781. }
  4782. $res['code'] = 0;
  4783. $res['msg'] = '成功';
  4784. $res['count'] = $total;
  4785. $res['data'] = $result;
  4786. return json($res);
  4787. }
  4788. public function Getvideolist(){
  4789. if (!$this->request->isGet()) {
  4790. $this->error('请求方式错误');
  4791. }
  4792. $params = $this->request->param();
  4793. $search = input('search', '');
  4794. $page = isset($params['page']) ? (int)$params['page'] : 1;
  4795. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  4796. $where = [];
  4797. if (!empty($search)) {
  4798. $where['prompt'] = ['like', '%' . $search . '%'];
  4799. }
  4800. $list = Db::name('video')->where('mod_rq', null)
  4801. ->where($where)
  4802. ->order('id desc')
  4803. ->limit(($page - 1) * $limit, $limit)
  4804. ->select();
  4805. $total = Db::name('video')->where('mod_rq', null)
  4806. ->where($where)
  4807. ->count();
  4808. $res['code'] = 0;
  4809. $res['msg'] = '成功';
  4810. $res['count'] = $total;
  4811. $res['data'] = $list;
  4812. return json($res);
  4813. }
  4814. //video_691c078dbb648190a17625bbef815ce50cbc1621ce1702d7
  4815. public function video()
  4816. {
  4817. $params = $this->request->param();
  4818. $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
  4819. $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
  4820. $postData = [
  4821. 'prompt' => $params['prompt'],
  4822. 'model' => $params['model'],
  4823. 'seconds' => $params['seconds'],
  4824. 'size' => $params['size'],
  4825. ];
  4826. // 初始化CURL
  4827. $ch = curl_init();
  4828. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  4829. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  4830. curl_setopt($ch, CURLOPT_POST, true);
  4831. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  4832. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  4833. 'Authorization: Bearer ' . $apiKey
  4834. ]);
  4835. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  4836. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  4837. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  4838. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  4839. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  4840. // 创建临时文件来捕获详细的cURL输出
  4841. $verbose = fopen('php://temp', 'w+');
  4842. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  4843. // 执行请求
  4844. $response = curl_exec($ch);
  4845. //HTTP状态码
  4846. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  4847. // 获取详细的cURL调试信息
  4848. rewind($verbose);
  4849. //CURL调试信息
  4850. $verboseLog = stream_get_contents($verbose);
  4851. fclose($verbose);
  4852. // 分离头部和主体
  4853. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  4854. //响应头部
  4855. $header = substr($response, 0, $header_size);
  4856. //响应主体
  4857. $body = substr($response, $header_size);
  4858. // 检查CURL错误
  4859. $curlError = curl_error($ch);
  4860. curl_close($ch);
  4861. $responseData = json_decode($body, true);
  4862. // 检查API是否返回了错误信息
  4863. if (isset($responseData['error'])) {
  4864. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  4865. return json([
  4866. 'code' => 1,
  4867. 'msg' => '视频生成请求失败',
  4868. 'data' => [
  4869. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  4870. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  4871. 'error_message' => $errorMessage
  4872. ]
  4873. ]);
  4874. }
  4875. // 检查是否有自定义错误格式
  4876. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  4877. return json([
  4878. 'code' => 1,
  4879. 'msg' => '视频生成请求失败',
  4880. 'data' => [
  4881. 'error_code' => $responseData['code'],
  4882. 'error_message' => $responseData['message']
  4883. ]
  4884. ]);
  4885. }
  4886. // 检查是否存在id字段
  4887. if (!isset($responseData['id'])) {
  4888. return json([
  4889. 'code' => 1,
  4890. 'msg' => '无法获取视频ID',
  4891. 'data' => [
  4892. 'response_data' => $responseData,
  4893. 'http_code' => $httpCode
  4894. ]
  4895. ]);
  4896. }
  4897. $videoData = [
  4898. 'video_id' => $responseData['id'],
  4899. 'prompt' => $postData['prompt'],
  4900. 'model' => $postData['model'],
  4901. 'seconds' => $postData['seconds'],
  4902. 'size' => $postData['size'],
  4903. 'sys_rq' => date("Y-m-d H:i:s")
  4904. ];
  4905. // 尝试插入数据
  4906. try {
  4907. $res = Db::name('video')->insert($videoData);
  4908. return json([
  4909. 'code' => 0,
  4910. 'msg' => '视频正在生成中',
  4911. 'data' => [
  4912. 'video_id' => $responseData['id'],
  4913. 'insert_result' => $res
  4914. ]
  4915. ]);
  4916. } catch (Exception $e) {
  4917. return json([
  4918. 'code' => 1,
  4919. 'msg' => '数据库操作失败',
  4920. 'data' => [
  4921. 'error_message' => $e->getMessage()
  4922. ]
  4923. ]);
  4924. }
  4925. }
  4926. /**
  4927. * 获取视频内容
  4928. * 下载已完成的视频内容
  4929. */
  4930. public function videoContent(){
  4931. // 从请求参数获取video_id,如果没有则使用默认值
  4932. $video_id = input('get.video_id');
  4933. $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
  4934. // 1. 先检查视频状态
  4935. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
  4936. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  4937. // 检查视频状态
  4938. if ($statusData['status'] !== 'completed') {
  4939. return json([
  4940. 'code' => 202,
  4941. 'msg' => '视频尚未生成完成',
  4942. 'data' => [
  4943. 'video_id' => $video_id,
  4944. 'status' => $statusData['status'],
  4945. 'progress' => $statusData['progress'],
  4946. 'created_at' => $statusData['created_at'],
  4947. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  4948. ]
  4949. ]);
  4950. }
  4951. // 2. 视频生成完成,准备下载
  4952. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
  4953. // 获取可选的variant参数
  4954. $variant = input('get.variant', '');
  4955. if (!empty($variant)) {
  4956. $apiUrl .= '?variant=' . urlencode($variant);
  4957. }
  4958. // 创建保存目录
  4959. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  4960. if (!is_dir($saveDir)) {
  4961. mkdir($saveDir, 0755, true);
  4962. }
  4963. // 生成唯一文件名
  4964. $filename = $video_id . '.mp4';
  4965. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  4966. $fullPath = $saveDir . DS . $filename;
  4967. // 3. 下载视频
  4968. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  4969. // 4. 保存视频文件
  4970. if (file_put_contents($fullPath, $videoData) === false) {
  4971. throw new Exception('视频保存失败');
  4972. }
  4973. // 确保路径使用正斜杠,并只保存相对路径部分
  4974. $localPath = str_replace('\\', '/', $localPath);
  4975. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  4976. $savePath = ltrim($localPath, '/');
  4977. // 将正确格式的文件路径存入数据库
  4978. Db::name('video')->where('video_id', $video_id)->update([
  4979. 'web_url' => $savePath
  4980. ]);
  4981. // 返回成功响应
  4982. return json([
  4983. 'code' => 0,
  4984. 'msg' => '视频下载成功',
  4985. 'data' => [
  4986. 'video_id' => $video_id,
  4987. 'local_path' => $localPath,
  4988. 'web_url' => $savePath,
  4989. 'file_size' => filesize($fullPath)
  4990. ]
  4991. ]);
  4992. }
  4993. /**
  4994. * 获取视频状态
  4995. */
  4996. private function fetchVideoStatus($url, $apiKey) {
  4997. $ch = curl_init();
  4998. curl_setopt($ch, CURLOPT_URL, $url);
  4999. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  5000. curl_setopt($ch, CURLOPT_HTTPGET, true);
  5001. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  5002. 'Authorization: Bearer ' . $apiKey,
  5003. 'Accept: application/json'
  5004. ]);
  5005. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  5006. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  5007. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  5008. $response = curl_exec($ch);
  5009. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  5010. $error = curl_error($ch);
  5011. curl_close($ch);
  5012. if ($error) {
  5013. throw new Exception('获取视频状态失败: ' . $error);
  5014. }
  5015. if ($httpCode < 200 || $httpCode >= 300) {
  5016. throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
  5017. }
  5018. $data = json_decode($response, true);
  5019. if (!is_array($data)) {
  5020. throw new Exception('视频状态数据格式错误');
  5021. }
  5022. return $data;
  5023. }
  5024. /**
  5025. * 下载视频文件
  5026. */
  5027. private function downloadVideo($url, $apiKey) {
  5028. $ch = curl_init();
  5029. curl_setopt($ch, CURLOPT_URL, $url);
  5030. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  5031. curl_setopt($ch, CURLOPT_HTTPGET, true);
  5032. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  5033. 'Authorization: Bearer ' . $apiKey
  5034. ]);
  5035. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  5036. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  5037. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  5038. $response = curl_exec($ch);
  5039. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  5040. $error = curl_error($ch);
  5041. curl_close($ch);
  5042. if ($error) {
  5043. throw new Exception('视频下载失败: ' . $error);
  5044. }
  5045. if ($httpCode < 200 || $httpCode >= 300) {
  5046. throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
  5047. }
  5048. return $response;
  5049. }
  5050. /**
  5051. * 获取产品款式列表
  5052. * @return \think\response\Json
  5053. * @throws \think\db\exception\DataNotFoundException
  5054. */
  5055. public function getProductStyleList()
  5056. {
  5057. if (!$this->request->isGet()) {
  5058. $this->error('请求方式错误');
  5059. }
  5060. $list = db('产品_基本资料')
  5061. ->whereNotNull('product_type')
  5062. ->where('product_type', '<>', '')
  5063. ->field('product_type')
  5064. ->distinct(true)
  5065. ->order('product_type asc')
  5066. ->column('product_type');
  5067. $this->success('成功', $list);
  5068. }
  5069. }