Procuremen.php 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use PHPMailer\PHPMailer\PHPMailer;
  6. use think\Config;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  9. use PhpOffice\PhpSpreadsheet\Style\Border;
  10. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  11. use think\Db;
  12. use think\Log;
  13. class Procuremen extends Backend
  14. {
  15. /**
  16. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  17. */
  18. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  19. /**
  20. * Procuremen模型对象
  21. * @var \app\admin\model\Procuremen
  22. */
  23. protected $model = null;
  24. /**
  25. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  26. */
  27. protected $notifyDryRunPreview = [];
  28. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  29. protected $procuremenRedisCache = null;
  30. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  31. protected $pickHiddenScydgySetCache = null;
  32. /**
  33. * @var array
  34. */
  35. protected $noNeedRight = [
  36. 'review', 'reviewCompanies', 'outward_detail', 'export_month_outward', 'snapshotToProcure',
  37. 'pick', 'audit', 'confirm', 'pickreview', 'picksubmit', 'pickadd', 'auditissue', 'auditsubmit',
  38. 'auditresendsms', 'auditabandon', 'archiveabandon', 'auditresendemail', 'purchaseconfirmpick', 'purchaseapprovalreject', 'add', 'pickdelete', 'completeDirectly', 'rfqlist', 'details',
  39. ];
  40. public function _initialize()
  41. {
  42. parent::_initialize();
  43. $this->model = new \app\admin\model\Procuremen;
  44. }
  45. /**
  46. * 手机端外发明细首页直达链接(登录后打开对应明细,免搜索)
  47. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  48. *
  49. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  50. */
  51. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  52. {
  53. static $mprocCfgLoaded = false;
  54. if (!$mprocCfgLoaded) {
  55. $mprocCfgLoaded = true;
  56. if (is_file(APP_PATH . 'extra/mproc.php')) {
  57. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  58. }
  59. }
  60. $eid = (int)$purchaseOrderDetailId;
  61. $base = $this->resolveMprocMobilePublicBaseUrl();
  62. if ($base === '') {
  63. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  64. }
  65. $path = trim((string)Config::get('mproc.mobile_index_path'));
  66. if ($path === '') {
  67. $path = '/index.php/index/index/index';
  68. } else {
  69. $path = '/' . ltrim($path, '/');
  70. }
  71. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  72. if ($eid > 0) {
  73. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  74. }
  75. return $base . $path . '?main_tab=orders';
  76. }
  77. /**
  78. * 邮件/短信外链:须为带点的公网域名
  79. */
  80. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  81. {
  82. $u = trim((string)$baseUrl);
  83. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  84. return false;
  85. }
  86. $host = parse_url($u, PHP_URL_HOST);
  87. if (!is_string($host) || $host === '') {
  88. return false;
  89. }
  90. if (strcasecmp($host, 'localhost') === 0) {
  91. return false;
  92. }
  93. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  94. return false;
  95. }
  96. if (strpos($host, '.') === false) {
  97. return false;
  98. }
  99. return true;
  100. }
  101. /**
  102. * 解析用于外发邮件/短信的手机端站点根
  103. */
  104. protected function resolveMprocMobilePublicBaseUrl()
  105. {
  106. $candidates = [];
  107. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  108. $candidates[] = trim((string)Config::get('site.indexurl'));
  109. $cdn = trim((string)Config::get('site.cdnurl'));
  110. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  111. $candidates[] = rtrim($cdn, '/');
  112. }
  113. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  114. $candidates[] = $reqBase;
  115. foreach ($candidates as $c) {
  116. if ($c === '') {
  117. continue;
  118. }
  119. $c = rtrim($c, '/');
  120. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  121. return $c;
  122. }
  123. }
  124. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  125. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  126. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  127. return $reqBase;
  128. }
  129. Log::write('外发邮件手机链接:配置地址失效', 'warning');
  130. return '';
  131. }
  132. /**
  133. * 排除 mcyd.dputrecord 空串、零日期等非法值,避免 MySQL 1525(DATE_FORMAT/BETWEEN 遇 '' 报错)
  134. */
  135. protected function whereMcydDputrecordValid($query, $alias = 'a')
  136. {
  137. $c = $alias . '.dStamp';
  138. // 先转成 CHAR 再判断,避免 DATETIME 列里存 '' / 0000-00-00 时参与日期函数报错
  139. return $query->whereRaw(
  140. $c . ' IS NOT NULL'
  141. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) <> \'\''
  142. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) NOT LIKE \'0000-00-00%\''
  143. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) REGEXP \'^[12][0-9]{3}-[01][0-9]-[0-3][0-9]\''
  144. );
  145. }
  146. /**
  147. * 获取 Redis 中 procuremen_redis
  148. */
  149. protected function ProcuremenRedis(): array
  150. {
  151. if ($this->procuremenRedisCache !== null) {
  152. return $this->procuremenRedisCache;
  153. }
  154. try {
  155. $redis = redis();
  156. $raw = $redis->get('procuremen_redis');
  157. if ($raw === false || $raw === '') {
  158. $this->procuremenRedisCache = [];
  159. return $this->procuremenRedisCache;
  160. }
  161. $decoded = json_decode($raw, true);
  162. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  163. $this->procuremenRedisCache = [];
  164. return $this->procuremenRedisCache;
  165. }
  166. $this->procuremenRedisCache = $decoded['data'];
  167. return $this->procuremenRedisCache;
  168. } catch (\Throwable $e) {
  169. $this->procuremenRedisCache = [];
  170. return $this->procuremenRedisCache;
  171. }
  172. }
  173. /**
  174. * 左侧菜单
  175. */
  176. protected function GetIndexYearMonths()
  177. {
  178. $ymSet = [];
  179. //获取此方法调用缓存数据
  180. foreach ($this->ProcuremenRedis() as $r) {
  181. if (!is_array($r)) {
  182. continue;
  183. }
  184. $ds = trim((string)($r['dputrecord'] ?? ''));
  185. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  186. continue;
  187. }
  188. if (!preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  189. continue;
  190. }
  191. $mo = (int)$m[2];
  192. if ($mo < 1 || $mo > 12) {
  193. continue;
  194. }
  195. $ymSet[$m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT)] = true;
  196. }
  197. $ymList = array_keys($ymSet);
  198. return $this->buildYearMonthSidebar($ymList);
  199. }
  200. /**
  201. * @param string[] $ymList 形如 2026-06
  202. * @return array<int, array{year:string, months:array}>
  203. */
  204. protected function buildYearMonthSidebar(array $ymList): array
  205. {
  206. rsort($ymList, SORT_STRING);
  207. $byYear = [];
  208. foreach ($ymList as $ym) {
  209. $y = substr($ym, 0, 4);
  210. $mo = (int)substr($ym, 5, 2);
  211. if (!isset($byYear[$y])) {
  212. $byYear[$y] = [];
  213. }
  214. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  215. }
  216. krsort($byYear, SORT_NUMERIC);
  217. foreach ($byYear as $y => $items) {
  218. usort($byYear[$y], function ($a, $b) {
  219. return strcmp($b['ym'], $a['ym']);
  220. });
  221. }
  222. $sidebar = [];
  223. foreach ($byYear as $y => $months) {
  224. $sidebar[] = ['year' => $y, 'months' => $months];
  225. }
  226. return $sidebar;
  227. }
  228. /**
  229. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  230. */
  231. protected function GetIssuedOrderYearMonths(string $stage): array
  232. {
  233. $ymSet = [];
  234. try {
  235. $query = Db::table('purchase_order');
  236. $this->applyPurchaseOrderNotDeletedWhere($query);
  237. if ($stage === 'audit') {
  238. $query->whereIn('wflow_status', [1, '1']);
  239. } elseif ($stage === 'confirm') {
  240. $query->where('status', 0)->where(function ($q) {
  241. $q->where('wflow_status', 2)
  242. ->whereOr(function ($q2) {
  243. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  244. });
  245. });
  246. } else {
  247. return $this->GetIndexYearMonths();
  248. }
  249. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  250. if (is_array($rows)) {
  251. foreach ($rows as $r) {
  252. if (!is_array($r)) {
  253. continue;
  254. }
  255. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  256. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  257. continue;
  258. }
  259. $mo = (int)$m[2];
  260. if ($mo < 1 || $mo > 12) {
  261. continue;
  262. }
  263. $ymSet[$m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT)] = true;
  264. }
  265. }
  266. } catch (\Throwable $e) {
  267. $ymSet = [];
  268. }
  269. $ymList = array_keys($ymSet);
  270. if ($ymList === []) {
  271. $def = $this->resolveProcuremenDefaultYm($stage);
  272. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  273. }
  274. return $this->buildYearMonthSidebar($ymList);
  275. }
  276. /**
  277. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  278. */
  279. protected function resolveProcuremenDefaultYm(string $stage): string
  280. {
  281. if ($stage === 'pick') {
  282. return date('Y-m');
  283. }
  284. try {
  285. $query = Db::table('purchase_order');
  286. $this->applyPurchaseOrderNotDeletedWhere($query);
  287. if ($stage === 'audit') {
  288. $query->whereIn('wflow_status', [1, '1']);
  289. } elseif ($stage === 'confirm') {
  290. $query->where('status', 0)->where(function ($q) {
  291. $q->where('wflow_status', 2)
  292. ->whereOr(function ($q2) {
  293. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  294. });
  295. });
  296. } else {
  297. return date('Y-m');
  298. }
  299. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  300. if ($latest === null || $latest === '') {
  301. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  302. }
  303. $t = $this->formatProcuremenDetailTime($latest);
  304. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  305. return $m[1] . '-' . $m[2];
  306. }
  307. } catch (\Throwable $e) {
  308. }
  309. return date('Y-m');
  310. }
  311. protected function applyPurchaseOrderNotDeletedWhere($query): void
  312. {
  313. $query->whereRaw(
  314. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  315. );
  316. }
  317. /** purchase_order_detail.status:2=废弃归档(保留留痕,不参与当前流程) */
  318. protected const PURCHASE_DETAIL_STATUS_VOID = 2;
  319. protected function isPurchaseOrderDetailVoid(array $row): bool
  320. {
  321. if ((int)($row['status'] ?? 0) === self::PURCHASE_DETAIL_STATUS_VOID) {
  322. return true;
  323. }
  324. return trim((string)($row['status_name'] ?? '')) === '已废弃';
  325. }
  326. /**
  327. * 仅当前有效下发明细(排除废弃归档)
  328. */
  329. protected function applyActivePurchaseOrderDetailWhere($query): void
  330. {
  331. $void = self::PURCHASE_DETAIL_STATUS_VOID;
  332. $query->whereRaw('(`status` IS NULL OR `status` <> ' . $void . ')')
  333. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'已废弃\')');
  334. }
  335. /**
  336. * 列表/流程判定:存在有效下发明细
  337. */
  338. protected function purchaseOrderDetailActiveExistsSql(string $detailAlias = 'd'): string
  339. {
  340. $void = self::PURCHASE_DETAIL_STATUS_VOID;
  341. return 'EXISTS (SELECT 1 FROM purchase_order_detail ' . $detailAlias
  342. . ' WHERE ' . $detailAlias . '.scydgy_id = purchase_order.scydgy_id'
  343. . ' AND (' . $detailAlias . '.`status` IS NULL OR ' . $detailAlias . '.`status` <> ' . $void . ')'
  344. . ' AND (' . $detailAlias . '.status_name IS NULL OR TRIM(' . $detailAlias . '.status_name) = \'\' OR ' . $detailAlias . '.status_name <> \'已废弃\')'
  345. . ' LIMIT 1)';
  346. }
  347. /**
  348. * 废弃退回初选:下发明细标记归档,不物理删除
  349. *
  350. * @param array<int, int|string> $scydgyIds
  351. */
  352. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  353. {
  354. $ids = [];
  355. foreach ($scydgyIds as $sid) {
  356. $n = (int)$sid;
  357. if ($this->isValidScydgyRowId($n) || $n < 0) {
  358. $ids[$n] = true;
  359. }
  360. }
  361. if ($ids === []) {
  362. return;
  363. }
  364. $void = self::PURCHASE_DETAIL_STATUS_VOID;
  365. Db::table('purchase_order_detail')
  366. ->where('scydgy_id', 'in', array_keys($ids))
  367. ->whereRaw('(`status` IS NULL OR `status` <> ' . $void . ')')
  368. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'已废弃\')')
  369. ->update([
  370. 'status' => $void,
  371. 'status_name' => '已废弃',
  372. ]);
  373. }
  374. /**
  375. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  376. */
  377. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  378. {
  379. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  380. $norm = function (string $col) use ($p): string {
  381. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  382. };
  383. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  384. $parts = [];
  385. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  386. if ($key === 'createtime') {
  387. $parts[] = $createtime;
  388. } else {
  389. $parts[] = $norm($key);
  390. }
  391. }
  392. return 'COALESCE(' . implode(', ', $parts) . ')';
  393. }
  394. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  395. {
  396. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  397. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  398. }
  399. /**
  400. * @return array<int, array<string, mixed>>
  401. */
  402. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  403. {
  404. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  405. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  406. try {
  407. $query = Db::table('purchase_order')->field($fields);
  408. $this->applyPurchaseOrderNotDeletedWhere($query);
  409. if ($stage === 'audit') {
  410. $query->whereIn('wflow_status', [1, '1'])->order('pick_time', 'desc')->order('id', 'desc');
  411. } elseif ($stage === 'confirm') {
  412. $query->where('status', 0)->where(function ($q) {
  413. $q->where('wflow_status', 2)
  414. ->whereOr(function ($q2) {
  415. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  416. });
  417. })->order('pick_time', 'desc')->order('id', 'desc');
  418. } else {
  419. return [];
  420. }
  421. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  422. $monthStart = $ym . '-01 00:00:00';
  423. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  424. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  425. }
  426. $rows = $query->select();
  427. } catch (\Throwable $e) {
  428. $rows = [];
  429. }
  430. return is_array($rows) ? $rows : [];
  431. }
  432. /**
  433. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  434. */
  435. protected function resolveProcuremenListStage(): string
  436. {
  437. $action = strtolower((string)$this->request->action());
  438. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  439. return $action;
  440. }
  441. $tab = trim((string)$this->request->request('wff_tab', 'pick'));
  442. return in_array($tab, ['pick', 'audit', 'confirm'], true) ? $tab : 'pick';
  443. }
  444. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  445. {
  446. $rootTrue = rtrim((string)$this->request->root(true), '/');
  447. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  448. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  449. $indexPhpRoot = $rootTrue . '/index.php';
  450. }
  451. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  452. $this->view->assign('defaultYm', $this->resolveProcuremenDefaultYm($stage));
  453. $this->view->assign(
  454. 'sidebarYearMonths',
  455. $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage)
  456. );
  457. $this->view->assign('procuremenStage', $stage);
  458. $this->view->assign('procuremenPageTitle', $pageTitle);
  459. }
  460. /** 外发下发(选工序+供应商,发短信邮件通知报价) */
  461. public function pick()
  462. {
  463. $this->request->filter(['strip_tags', 'trim']);
  464. if (!$this->request->isAjax()) {
  465. $this->assignProcuremenListPage('pick', '外发下发');
  466. return $this->view->fetch('procuremen/index');
  467. }
  468. return $this->index();
  469. }
  470. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  471. public function audit()
  472. {
  473. $this->request->filter(['strip_tags', 'trim']);
  474. if (!$this->request->isAjax()) {
  475. $this->assignProcuremenListPage('audit', '确认供应商');
  476. return $this->view->fetch('procuremen/index');
  477. }
  478. return $this->index();
  479. }
  480. /** 采购确认(定标) */
  481. public function confirm()
  482. {
  483. $this->request->filter(['strip_tags', 'trim']);
  484. if (!$this->request->isAjax()) {
  485. $this->assignProcuremenListPage('confirm', '采购确认');
  486. return $this->view->fetch('procuremen/index');
  487. }
  488. return $this->index();
  489. }
  490. /**
  491. * 列表页(兼容旧菜单 procuremen/index,等同外发下发)
  492. */
  493. public function index()
  494. {
  495. $this->request->filter(['strip_tags', 'trim']);
  496. if (!$this->request->isAjax()) {
  497. $this->assignProcuremenListPage('pick', '外发下发');
  498. return $this->view->fetch('procuremen/index');
  499. }
  500. if ($this->request->request('keyField')) {
  501. return $this->selectpage();
  502. }
  503. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  504. $limit = max(10, min(500, (int)$limit));
  505. $ym = $this->request->request('ym', date('Y-m'));
  506. $ym = is_string($ym) ? trim($ym) : '';
  507. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  508. $ym = date('Y-m');
  509. }
  510. $monthStart = $ym . '-01 00:00:00';
  511. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  512. $search = trim((string)$this->request->get('search', ''));
  513. $hasActiveSearch = ($search !== '');
  514. if (!$hasActiveSearch) {
  515. $filterStr = $this->request->get('filter', '');
  516. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  517. $arr = json_decode($filterStr, true);
  518. if (is_array($arr) && count($arr) > 0) {
  519. foreach ($arr as $v) {
  520. if (is_array($v)) {
  521. if (array_filter($v, function ($x) {
  522. return $x !== '' && $x !== null;
  523. })) {
  524. $hasActiveSearch = true;
  525. break;
  526. }
  527. } elseif ($v !== '' && $v !== null) {
  528. $hasActiveSearch = true;
  529. break;
  530. }
  531. }
  532. }
  533. }
  534. }
  535. $applyMonthRange = !$hasActiveSearch;
  536. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  537. $opArr = (array)json_decode($this->request->get('op', ''), true);
  538. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  539. $wffTab = $this->resolveProcuremenListStage();
  540. try {
  541. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  542. if ($wffTab === 'audit') {
  543. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  544. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  545. );
  546. } elseif ($wffTab === 'confirm') {
  547. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  548. $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange)
  549. );
  550. } else {
  551. $pool = $this->ProcuremenRedis();
  552. if (!is_array($pool)) {
  553. $pool = [];
  554. }
  555. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  556. $hideSet = $this->loadPickHiddenScydgySet();
  557. if ($pool !== [] && $hideSet !== []) {
  558. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  559. if (!is_array($r)) {
  560. return false;
  561. }
  562. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  563. return $id <= 0 || !isset($hideSet[$id]);
  564. }));
  565. }
  566. $manualPool = $this->loadPickManualOrderRows();
  567. if ($manualPool !== []) {
  568. $pool = array_merge($pool, $manualPool);
  569. }
  570. if ($pool === []) {
  571. return json([
  572. 'total' => 0,
  573. 'rows' => [],
  574. 'msg' => '暂无缓存数据',
  575. ]);
  576. }
  577. }
  578. $filtered = $this->filterProcuremenIndexPool(
  579. $pool,
  580. $monthStart,
  581. $monthEnd,
  582. $applyMonthRange,
  583. $search,
  584. $filterArr,
  585. $opArr,
  586. $listTimePrimary
  587. );
  588. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  589. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  590. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  591. }
  592. $sortField = 'ID';
  593. if (is_string($sort) && $sort !== '') {
  594. $parts = explode(',', $sort);
  595. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  596. if ($sortField === '') {
  597. $sortField = 'ID';
  598. }
  599. }
  600. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  601. $nFiltered = count($filtered);
  602. if ($nFiltered > 1) {
  603. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  604. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  605. $ta = $this->procuremenRowListSortTime($a, $sortField);
  606. $tb = $this->procuremenRowListSortTime($b, $sortField);
  607. if ($ta === $tb) {
  608. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  609. }
  610. if ($ta === '') {
  611. return 1;
  612. }
  613. if ($tb === '') {
  614. return -1;
  615. }
  616. return strcmp($ta, $tb) * $ord;
  617. });
  618. } elseif ($sortField === 'ID') {
  619. $sortKeys = [];
  620. foreach ($filtered as $i => $row) {
  621. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  622. }
  623. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  624. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  625. } else {
  626. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  627. $va = $a[$sortField] ?? null;
  628. $vb = $b[$sortField] ?? null;
  629. $sa = (string)$va;
  630. $sb = (string)$vb;
  631. if ($sa === $sb) {
  632. return 0;
  633. }
  634. return strcmp($sa, $sb) * $ord;
  635. });
  636. }
  637. }
  638. $offset = max(0, (int)$offset);
  639. $limit = max(1, (int)$limit);
  640. $rows = array_slice($filtered, $offset, $limit);
  641. foreach ($rows as &$rw) {
  642. if (!is_array($rw)) {
  643. continue;
  644. }
  645. $rid = (int)($rw['ID'] ?? 0);
  646. $rw['_iss_out'] = ($wffTab !== 'pick');
  647. }
  648. unset($rw);
  649. if ($wffTab === 'confirm' && count($rows) > 0) {
  650. $idList = [];
  651. foreach ($rows as $rw) {
  652. if (!is_array($rw)) {
  653. continue;
  654. }
  655. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  656. foreach ($rw['_order_merge_rows'] as $mr) {
  657. $mid = (int)($mr['ID'] ?? 0);
  658. if ($this->isValidScydgyRowId($mid)) {
  659. $idList[$mid] = true;
  660. }
  661. }
  662. }
  663. $id = (int)($rw['ID'] ?? 0);
  664. if ($this->isValidScydgyRowId($id)) {
  665. $idList[$id] = true;
  666. }
  667. }
  668. $sumMap = $this->OrderDetailSummary(array_keys($idList));
  669. foreach ($rows as &$rw) {
  670. if (!is_array($rw)) {
  671. continue;
  672. }
  673. $mergeIds = [];
  674. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  675. foreach ($rw['_order_merge_rows'] as $mr) {
  676. $mid = (int)($mr['ID'] ?? 0);
  677. if ($this->isValidScydgyRowId($mid)) {
  678. $mergeIds[$mid] = true;
  679. }
  680. }
  681. }
  682. $rid = (int)($rw['ID'] ?? 0);
  683. if ($this->isValidScydgyRowId($rid)) {
  684. $mergeIds[$rid] = true;
  685. }
  686. $cnt = 0;
  687. $amt = 0;
  688. $deliv = 0;
  689. foreach (array_keys($mergeIds) as $mid) {
  690. $s = isset($sumMap[$mid]) ? $sumMap[$mid] : ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  691. $cnt += (int)($s['cnt'] ?? 0);
  692. $amt += (int)($s['amt'] ?? 0);
  693. $deliv += (int)($s['deliv'] ?? 0);
  694. }
  695. $rw['po_detail_count'] = $cnt;
  696. $rw['po_amount_fill_cnt'] = $amt;
  697. $rw['po_delivery_fill_cnt'] = $deliv;
  698. }
  699. unset($rw);
  700. }
  701. if ($wffTab === 'confirm' && count($rows) > 0) {
  702. $idList = [];
  703. foreach ($rows as $rw) {
  704. if (!is_array($rw)) {
  705. continue;
  706. }
  707. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  708. foreach ($rw['_order_merge_rows'] as $mr) {
  709. $mid = (int)($mr['ID'] ?? 0);
  710. if ($this->isValidScydgyRowId($mid)) {
  711. $idList[$mid] = true;
  712. }
  713. }
  714. }
  715. $id = (int)($rw['ID'] ?? 0);
  716. if ($this->isValidScydgyRowId($id)) {
  717. $idList[$id] = true;
  718. }
  719. }
  720. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  721. foreach ($rows as &$rw) {
  722. if (!is_array($rw)) {
  723. continue;
  724. }
  725. $mergeIds = [];
  726. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  727. foreach ($rw['_order_merge_rows'] as $mr) {
  728. $mid = (int)($mr['ID'] ?? 0);
  729. if ($this->isValidScydgyRowId($mid)) {
  730. $mergeIds[$mid] = true;
  731. }
  732. }
  733. }
  734. $rid = (int)($rw['ID'] ?? 0);
  735. if ($this->isValidScydgyRowId($rid)) {
  736. $mergeIds[$rid] = true;
  737. }
  738. $buckets = [];
  739. foreach (array_keys($mergeIds) as $mid) {
  740. if (isset($quoteBucket[$mid])) {
  741. $buckets[] = $quoteBucket[$mid];
  742. }
  743. }
  744. $rw['picked_supplier_name'] = $buckets !== []
  745. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  746. : '';
  747. }
  748. unset($rw);
  749. }
  750. if ($wffTab === 'audit' && count($rows) > 0) {
  751. $idList = [];
  752. foreach ($rows as $rw) {
  753. if (!is_array($rw)) {
  754. continue;
  755. }
  756. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  757. foreach ($rw['_order_merge_rows'] as $mr) {
  758. $mid = (int)($mr['ID'] ?? 0);
  759. if ($this->isValidScydgyRowId($mid)) {
  760. $idList[$mid] = true;
  761. }
  762. }
  763. }
  764. $id = (int)($rw['ID'] ?? 0);
  765. if ($this->isValidScydgyRowId($id)) {
  766. $idList[$id] = true;
  767. }
  768. }
  769. $notifyMap = $this->loadNotifySupplierNamesByScydgyIds(array_keys($idList));
  770. foreach ($rows as &$rw) {
  771. if (!is_array($rw)) {
  772. continue;
  773. }
  774. $mergeIds = [];
  775. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  776. foreach ($rw['_order_merge_rows'] as $mr) {
  777. $mid = (int)($mr['ID'] ?? 0);
  778. if ($this->isValidScydgyRowId($mid)) {
  779. $mergeIds[$mid] = true;
  780. }
  781. }
  782. }
  783. $rid = (int)($rw['ID'] ?? 0);
  784. if ($this->isValidScydgyRowId($rid)) {
  785. $mergeIds[$rid] = true;
  786. }
  787. $names = [];
  788. foreach (array_keys($mergeIds) as $mid) {
  789. foreach ($notifyMap[$mid] ?? [] as $cn) {
  790. if ($cn !== '' && !in_array($cn, $names, true)) {
  791. $names[] = $cn;
  792. }
  793. }
  794. }
  795. sort($names, SORT_STRING);
  796. $rw['notify_supplier_text'] = $this->formatNotifySupplierDisplay($names);
  797. }
  798. unset($rw);
  799. }
  800. if ($wffTab === 'all' && count($rows) > 0) {
  801. $this->mergePurchaseOrder($rows);
  802. }
  803. if ($wffTab === 'pick' && count($rows) > 0) {
  804. $this->mergePurchaseOrder($rows);
  805. }
  806. foreach ($rows as &$rwClean) {
  807. if (is_array($rwClean)) {
  808. unset($rwClean['_order_merge_rows']);
  809. if (array_key_exists('NGZL', $rwClean)) {
  810. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  811. }
  812. }
  813. }
  814. unset($rwClean);
  815. return json([
  816. 'total' => count($filtered),
  817. 'rows' => $rows,
  818. ]);
  819. } catch (\Throwable $e) {
  820. return json([
  821. 'total' => 0,
  822. 'rows' => [],
  823. 'msg' => $e->getMessage(),
  824. ]);
  825. }
  826. }
  827. /**
  828. * 已外发/不可再审核判定(与「未发」列表隐藏规则一致,避免仅保存数量却被当成已下发)
  829. * - purchase_order.status 为 0 或 1:已审核下发或已完结
  830. * - 或存在 purchase_order_detail:已向供应商下过明细
  831. * 仅写入 purchase_order 且 status 为空:视为未发(如只填本次数量、最高限价)
  832. *
  833. * @return array<int, true> scydgy_id => true
  834. */
  835. protected function loadIssuedScydgySet()
  836. {
  837. $issuedSet = [];
  838. try {
  839. $poList = Db::table('purchase_order')
  840. ->whereRaw('(`status` = 0 OR `status` = 1)')
  841. ->column('scydgy_id');
  842. if (is_array($poList)) {
  843. foreach ($poList as $ids) {
  844. $n = (int)$ids;
  845. if ($n > 0) {
  846. $issuedSet[$n] = true;
  847. }
  848. }
  849. }
  850. } catch (\Throwable $e) {
  851. }
  852. try {
  853. $detList = Db::table('purchase_order_detail');
  854. $this->applyActivePurchaseOrderDetailWhere($detList);
  855. $detList = $detList->group('scydgy_id')->column('scydgy_id');
  856. if (is_array($detList)) {
  857. foreach ($detList as $ids) {
  858. $n = (int)$ids;
  859. if ($n > 0) {
  860. $issuedSet[$n] = true;
  861. }
  862. }
  863. }
  864. } catch (\Throwable $e) {
  865. }
  866. return $issuedSet;
  867. }
  868. /**
  869. * 外发下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  870. *
  871. * @return array<int, true>
  872. */
  873. protected function loadPickHiddenScydgySet(): array
  874. {
  875. if ($this->pickHiddenScydgySetCache !== null) {
  876. return $this->pickHiddenScydgySetCache;
  877. }
  878. $hideSet = [];
  879. try {
  880. $poIds = Db::table('purchase_order')
  881. ->where(function ($q) {
  882. $q->where('wflow_status', '>=', 1)
  883. ->whereOr('status', 1)
  884. ->whereOr(function ($q2) {
  885. $q2->whereNotNull('pick_time')
  886. ->where('pick_time', '<>', '')
  887. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  888. })
  889. ->whereOr(function ($q3) {
  890. $q3->whereNotNull('mod_rq')
  891. ->where('mod_rq', '<>', '')
  892. ->where('mod_rq', 'not like', '0000-00-00%');
  893. });
  894. })
  895. ->column('scydgy_id');
  896. if (is_array($poIds)) {
  897. foreach ($poIds as $pid) {
  898. $k = (int)$pid;
  899. if ($k !== 0) {
  900. $hideSet[$k] = true;
  901. }
  902. }
  903. }
  904. } catch (\Throwable $e) {
  905. }
  906. try {
  907. $detIdsQuery = Db::table('purchase_order_detail');
  908. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  909. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  910. if (is_array($detIds)) {
  911. foreach ($detIds as $pid) {
  912. $k = (int)$pid;
  913. if ($this->isValidScydgyRowId($k)) {
  914. $hideSet[$k] = true;
  915. }
  916. }
  917. }
  918. } catch (\Throwable $e) {
  919. }
  920. $this->pickHiddenScydgySetCache = $hideSet;
  921. return $hideSet;
  922. }
  923. /**
  924. * 外发下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  925. *
  926. * @return array<int, array<string, mixed>>
  927. */
  928. protected function loadPickManualOrderRows(): array
  929. {
  930. try {
  931. $dbRows = Db::table('purchase_order')
  932. ->where('scydgy_id', '<', 0)
  933. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  934. ->order('scydgy_id', 'asc')
  935. ->select();
  936. } catch (\Throwable $e) {
  937. try {
  938. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  939. } catch (\Throwable $e2) {
  940. return [];
  941. }
  942. }
  943. if (!is_array($dbRows) || $dbRows === []) {
  944. return [];
  945. }
  946. $detailSidSet = [];
  947. try {
  948. $negIds = [];
  949. foreach ($dbRows as $dbRow) {
  950. if (!is_array($dbRow)) {
  951. continue;
  952. }
  953. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  954. if ($sid < 0) {
  955. $negIds[$sid] = true;
  956. }
  957. }
  958. if ($negIds !== []) {
  959. $detQuery = Db::table('purchase_order_detail')
  960. ->where('scydgy_id', 'in', array_keys($negIds));
  961. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  962. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  963. if (is_array($detRows)) {
  964. foreach ($detRows as $did) {
  965. $detailSidSet[(int)$did] = true;
  966. }
  967. }
  968. }
  969. } catch (\Throwable $e) {
  970. }
  971. $pool = [];
  972. foreach ($dbRows as $dbRow) {
  973. if (!is_array($dbRow)) {
  974. continue;
  975. }
  976. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  977. if ($sid >= 0) {
  978. continue;
  979. }
  980. $wf = (int)($dbRow['wflow_status'] ?? 0);
  981. if ($wf >= 1) {
  982. continue;
  983. }
  984. $st = trim((string)($dbRow['status'] ?? ''));
  985. if ($st === '1' || $st === '0') {
  986. continue;
  987. }
  988. if (isset($detailSidSet[$sid])) {
  989. continue;
  990. }
  991. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  992. $r['_is_manual'] = 1;
  993. $pool[] = $r;
  994. }
  995. return $pool;
  996. }
  997. /**
  998. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  999. */
  1000. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1001. {
  1002. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1003. foreach ($keys as $k) {
  1004. $t = trim((string)($row[$k] ?? ''));
  1005. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1006. return $t;
  1007. }
  1008. }
  1009. return '';
  1010. }
  1011. /**
  1012. * 分配手工新增工序行 ID(负数递减)
  1013. */
  1014. protected function allocateManualScydgyId(): int
  1015. {
  1016. try {
  1017. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1018. $min = (int)$min;
  1019. return $min < 0 ? $min - 1 : -1;
  1020. } catch (\Throwable $e) {
  1021. return -1;
  1022. }
  1023. }
  1024. /**
  1025. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1026. */
  1027. protected function allocateManualOrderCcydh(): string
  1028. {
  1029. $prefix = 'YW' . date('Ymd');
  1030. $maxSeq = 0;
  1031. try {
  1032. $rows = Db::table('purchase_order')
  1033. ->where('CCYDH', 'like', $prefix . '%')
  1034. ->column('CCYDH');
  1035. if (is_array($rows)) {
  1036. foreach ($rows as $ccydh) {
  1037. $ccydh = trim((string)$ccydh);
  1038. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1039. $maxSeq = max($maxSeq, (int)$m[1]);
  1040. }
  1041. }
  1042. }
  1043. } catch (\Throwable $e) {
  1044. }
  1045. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1046. }
  1047. /**
  1048. * purchase_order.mod_rq 是否有有效软删除时间
  1049. */
  1050. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1051. {
  1052. $t = trim((string)$modRq);
  1053. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1054. }
  1055. /**
  1056. * 列表行 → purchase_order 写入字段
  1057. *
  1058. * @return array<string, mixed>
  1059. */
  1060. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1061. {
  1062. return [
  1063. 'scydgy_id' => $scydgyId,
  1064. 'CCYDH' => $row['CCYDH'] ?? null,
  1065. 'CYJMC' => $row['CYJMC'] ?? null,
  1066. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1067. 'CDXMC' => $row['CDXMC'] ?? null,
  1068. 'CGYBH' => $row['CGYBH'] ?? null,
  1069. 'CGYMC' => $row['CGYMC'] ?? null,
  1070. 'CDW' => $row['CDW'] ?? null,
  1071. 'NGZL' => $row['NGZL'] ?? null,
  1072. 'CDF' => $row['CDF'] ?? null,
  1073. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1074. 'MBZ' => $row['MBZ'] ?? null,
  1075. 'bwjg' => $row['bwjg'] ?? null,
  1076. 'iStatus' => $row['iStatus'] ?? null,
  1077. 'dStamp' => $row['dStamp'] ?? null,
  1078. 'dputrecord' => $row['dputrecord'] ?? null,
  1079. 'cywyxm' => $row['cywyxm'] ?? null,
  1080. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1081. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1082. ];
  1083. }
  1084. /**
  1085. * 外发初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1086. */
  1087. protected function softDeleteProcuremenPickRow(array $row): void
  1088. {
  1089. $sid = $this->extractScydgyRowId($row);
  1090. if (!$this->isValidScydgyRowId($sid)) {
  1091. throw new \InvalidArgumentException('无效的行主键');
  1092. }
  1093. $hideSet = $this->loadPickHiddenScydgySet();
  1094. if ($sid > 0 && isset($hideSet[$sid])) {
  1095. throw new \InvalidArgumentException('订单号「' . trim((string)($row['CCYDH'] ?? '')) . '」已下发或已进入后续流程,无法删除');
  1096. }
  1097. if ($sid < 0) {
  1098. try {
  1099. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1100. if (is_array($po)) {
  1101. if ((int)($po['wflow_status'] ?? 0) >= 1) {
  1102. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1103. }
  1104. if ($this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1105. return;
  1106. }
  1107. }
  1108. } catch (\InvalidArgumentException $e) {
  1109. throw $e;
  1110. } catch (\Throwable $e) {
  1111. }
  1112. }
  1113. $now = date('Y-m-d H:i:s');
  1114. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1115. if (is_array($exists)) {
  1116. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1117. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1118. } else {
  1119. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1120. $data['mod_rq'] = $now;
  1121. $data['createtime'] = $now;
  1122. Db::table('purchase_order')->insert($data);
  1123. $poIdLog = (int)Db::getLastInsID();
  1124. }
  1125. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1126. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1127. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1128. if ($gymcLog !== '') {
  1129. $logTail .= ' / ' . $gymcLog;
  1130. }
  1131. $this->addOrderLog($sid, 'pick_soft_delete', '外发初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1132. }
  1133. /**
  1134. * 手工新增外发工序(写入 purchase_order)
  1135. *
  1136. * @param array<string, mixed> $params
  1137. * @return int scydgy_id
  1138. */
  1139. protected function saveManualPickOrder(array $params): int
  1140. {
  1141. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1142. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1143. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1144. if ($ccydh === '') {
  1145. $ccydh = $this->allocateManualOrderCcydh();
  1146. }
  1147. $now = date('Y-m-d H:i:s');
  1148. $sid = $this->allocateManualScydgyId();
  1149. $data = [
  1150. 'scydgy_id' => $sid,
  1151. 'CCYDH' => $ccydh,
  1152. 'CYJMC' => $cyjmc,
  1153. 'CGYMC' => $cgymc,
  1154. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1155. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1156. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1157. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1158. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1159. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1160. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1161. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1162. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1163. 'wflow_status' => 0,
  1164. 'createtime' => $now,
  1165. 'dStamp' => $now,
  1166. 'dputrecord' => $now,
  1167. ];
  1168. Db::table('purchase_order')->insert($data);
  1169. $poId = (int)Db::getLastInsID();
  1170. $this->addOrderLog($sid, 'manual_add', '手工新增外发工序', $poId > 0 ? $poId : null);
  1171. return $sid;
  1172. }
  1173. protected function formatProcuremenRowLabel(array $row): string
  1174. {
  1175. $dh = trim((string)($row['CCYDH'] ?? ''));
  1176. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1177. if ($dh !== '' && $gymc !== '') {
  1178. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1179. }
  1180. if ($dh !== '') {
  1181. return '订单「' . $dh . '」';
  1182. }
  1183. if ($gymc !== '') {
  1184. return '工序「' . $gymc . '」';
  1185. }
  1186. $id = $this->extractScydgyRowId($row);
  1187. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1188. }
  1189. /**
  1190. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1191. */
  1192. protected function extractScydgyRowId(array $row): int
  1193. {
  1194. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1195. }
  1196. protected function isValidScydgyRowId(int $id): bool
  1197. {
  1198. return $id !== 0;
  1199. }
  1200. protected function isManualScydgyRowId(int $id): bool
  1201. {
  1202. return $id < 0;
  1203. }
  1204. /**
  1205. * 采购确认已选定供应商:明细 purchase_order_detail.status = 1 的工序行 scydgy_id 集合
  1206. *
  1207. * @return array<int, true>
  1208. */
  1209. protected function loadScydgyIdsWithPickedSupplierDetail(): array
  1210. {
  1211. $set = [];
  1212. try {
  1213. $rows = Db::table('purchase_order_detail')->where('status', 1)->field('scydgy_id')->select();
  1214. } catch (\Throwable $e) {
  1215. $rows = [];
  1216. }
  1217. if (!is_array($rows)) {
  1218. return $set;
  1219. }
  1220. foreach ($rows as $r) {
  1221. if (!is_array($r)) {
  1222. continue;
  1223. }
  1224. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1225. if ($sid > 0) {
  1226. $set[$sid] = true;
  1227. }
  1228. }
  1229. return $set;
  1230. }
  1231. /**
  1232. * 每个工序行对应已选中供应商名称(取 status=1 的首条明细 company_name)
  1233. *
  1234. * @param int[] $scydgyIds
  1235. * @return array<int, string> scydgy_id => company_name
  1236. */
  1237. protected function loadPickedSupplierCompanyByScydgyIds(array $scydgyIds): array
  1238. {
  1239. $out = [];
  1240. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1241. if ($scydgyIds === []) {
  1242. return $out;
  1243. }
  1244. try {
  1245. $rows = Db::table('purchase_order_detail')
  1246. ->where('scydgy_id', 'in', $scydgyIds)
  1247. ->where('status', 1)
  1248. ->field('scydgy_id,company_name')
  1249. ->order('id', 'asc')
  1250. ->select();
  1251. } catch (\Throwable $e) {
  1252. try {
  1253. $rows = Db::table('purchase_order_detail')
  1254. ->where('scydgy_id', 'in', $scydgyIds)
  1255. ->where('status', 1)
  1256. ->field('scydgy_id,company_name')
  1257. ->order('ID', 'asc')
  1258. ->select();
  1259. } catch (\Throwable $e2) {
  1260. $rows = [];
  1261. }
  1262. }
  1263. if (!is_array($rows)) {
  1264. return $out;
  1265. }
  1266. foreach ($rows as $r) {
  1267. if (!is_array($r)) {
  1268. continue;
  1269. }
  1270. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1271. if (!$this->isValidScydgyRowId($sid) || isset($out[$sid])) {
  1272. continue;
  1273. }
  1274. $name = trim((string)($r['company_name'] ?? ''));
  1275. $out[$sid] = $name;
  1276. }
  1277. return $out;
  1278. }
  1279. /**
  1280. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1281. *
  1282. * @param int[] $scydgyIds
  1283. * @return array<int, string[]>
  1284. */
  1285. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1286. {
  1287. $out = [];
  1288. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1289. if ($scydgyIds === []) {
  1290. return $out;
  1291. }
  1292. try {
  1293. $rows = Db::table('purchase_order_detail')
  1294. ->where('scydgy_id', 'in', $scydgyIds)
  1295. ->field('scydgy_id,company_name')
  1296. ->order('company_name', 'asc')
  1297. ->select();
  1298. } catch (\Throwable $e) {
  1299. $rows = [];
  1300. }
  1301. if (!is_array($rows)) {
  1302. return $out;
  1303. }
  1304. foreach ($rows as $r) {
  1305. if (!is_array($r)) {
  1306. continue;
  1307. }
  1308. $sid = (int)($r['scydgy_id'] ?? 0);
  1309. $cn = trim((string)($r['company_name'] ?? ''));
  1310. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1311. continue;
  1312. }
  1313. if (!isset($out[$sid])) {
  1314. $out[$sid] = [];
  1315. }
  1316. if (!in_array($cn, $out[$sid], true)) {
  1317. $out[$sid][] = $cn;
  1318. }
  1319. }
  1320. return $out;
  1321. }
  1322. /**
  1323. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1324. *
  1325. * @param string[] $names
  1326. */
  1327. protected function formatNotifySupplierDisplay(array $names): string
  1328. {
  1329. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1330. return trim((string)$n);
  1331. }, $names))));
  1332. if ($names === []) {
  1333. return '';
  1334. }
  1335. sort($names, SORT_STRING);
  1336. return implode('、', $names);
  1337. }
  1338. /**
  1339. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1340. *
  1341. * @param int[] $scydgyIds
  1342. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1343. */
  1344. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1345. {
  1346. $out = [];
  1347. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1348. if ($scydgyIds === []) {
  1349. return $out;
  1350. }
  1351. try {
  1352. $rows = Db::table('purchase_order_detail')
  1353. ->where('scydgy_id', 'in', $scydgyIds)
  1354. ->field('scydgy_id,company_name,amount')
  1355. ->select();
  1356. } catch (\Throwable $e) {
  1357. $rows = [];
  1358. }
  1359. if (!is_array($rows)) {
  1360. return $out;
  1361. }
  1362. foreach ($rows as $r) {
  1363. if (!is_array($r)) {
  1364. continue;
  1365. }
  1366. $sid = (int)($r['scydgy_id'] ?? 0);
  1367. $cn = trim((string)($r['company_name'] ?? ''));
  1368. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1369. continue;
  1370. }
  1371. if (!isset($out[$sid])) {
  1372. $out[$sid] = ['all' => [], 'quoted' => []];
  1373. }
  1374. $out[$sid]['all'][$cn] = true;
  1375. $am = trim((string)($r['amount'] ?? ''));
  1376. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1377. $out[$sid]['quoted'][$cn] = true;
  1378. }
  1379. }
  1380. return $out;
  1381. }
  1382. /**
  1383. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1384. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1385. */
  1386. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1387. {
  1388. $merged = ['all' => [], 'quoted' => []];
  1389. foreach ($buckets as $b) {
  1390. if (!is_array($b)) {
  1391. continue;
  1392. }
  1393. foreach ($b['all'] ?? [] as $cn => $_) {
  1394. $merged['all'][$cn] = true;
  1395. }
  1396. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1397. $merged['quoted'][$cn] = true;
  1398. }
  1399. }
  1400. return $merged;
  1401. }
  1402. /**
  1403. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1404. */
  1405. protected function formatQuotedSupplierLines(array $bucket): string
  1406. {
  1407. $all = array_keys($bucket['all'] ?? []);
  1408. if ($all === []) {
  1409. return '';
  1410. }
  1411. sort($all, SORT_STRING);
  1412. $lines = [];
  1413. foreach ($all as $cn) {
  1414. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1415. $lines[] = $cn . '(' . $status . ')';
  1416. }
  1417. return implode("\n", $lines);
  1418. }
  1419. /**
  1420. * @param int[] $scydgyIds
  1421. * @return array<int, string>
  1422. */
  1423. protected function loadQuotedSupplierSummaryByScydgyIds(array $scydgyIds): array
  1424. {
  1425. $out = [];
  1426. foreach ($this->loadQuotedSupplierBucketByScydgyIds($scydgyIds) as $sid => $bucket) {
  1427. $text = $this->formatQuotedSupplierLines($bucket);
  1428. if ($text !== '') {
  1429. $out[$sid] = $text;
  1430. }
  1431. }
  1432. return $out;
  1433. }
  1434. /**
  1435. * 审核弹窗:按供应商汇总报价明细
  1436. *
  1437. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1438. * @return array<int, array<string, mixed>>
  1439. */
  1440. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  1441. {
  1442. $sids = [];
  1443. foreach ($bundle['pos'] ?? [] as $po) {
  1444. if (!is_array($po)) {
  1445. continue;
  1446. }
  1447. $sid = (int)($po['scydgy_id'] ?? 0);
  1448. if ($this->isValidScydgyRowId($sid)) {
  1449. $sids[$sid] = true;
  1450. }
  1451. }
  1452. if ($sids === []) {
  1453. return [];
  1454. }
  1455. $gymcMap = [];
  1456. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1457. if (!is_array($mr)) {
  1458. continue;
  1459. }
  1460. $gid = $this->extractScydgyRowId($mr);
  1461. if ($this->isValidScydgyRowId($gid)) {
  1462. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1463. }
  1464. }
  1465. foreach ($bundle['pos'] ?? [] as $po) {
  1466. if (!is_array($po)) {
  1467. continue;
  1468. }
  1469. $gid = (int)($po['scydgy_id'] ?? 0);
  1470. if ($this->isValidScydgyRowId($gid)) {
  1471. $nm = trim((string)($po['CGYMC'] ?? ''));
  1472. if ($nm !== '') {
  1473. $gymcMap[$gid] = $nm;
  1474. }
  1475. }
  1476. }
  1477. try {
  1478. $detailsQuery = Db::table('purchase_order_detail')
  1479. ->where('scydgy_id', 'in', array_keys($sids));
  1480. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1481. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  1482. } catch (\Throwable $e) {
  1483. try {
  1484. $detailsQuery = Db::table('purchase_order_detail')
  1485. ->where('scydgy_id', 'in', array_keys($sids));
  1486. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1487. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  1488. } catch (\Throwable $e2) {
  1489. $details = [];
  1490. }
  1491. }
  1492. if (!is_array($details)) {
  1493. $details = [];
  1494. }
  1495. $byCompany = [];
  1496. foreach ($details as $d) {
  1497. if (!is_array($d)) {
  1498. continue;
  1499. }
  1500. $cn = trim((string)($d['company_name'] ?? ''));
  1501. if ($cn === '') {
  1502. continue;
  1503. }
  1504. if (!isset($byCompany[$cn])) {
  1505. $ph = trim((string)($d['phone'] ?? ''));
  1506. $username = trim((string)($d['username'] ?? ''));
  1507. if ($username === '') {
  1508. $username = $this->resolveCustomerContactName($ph, $cn);
  1509. }
  1510. $byCompany[$cn] = [
  1511. 'name' => $cn,
  1512. 'email' => trim((string)($d['email'] ?? '')),
  1513. 'phone' => $ph,
  1514. 'username' => $username,
  1515. 'has_quote' => false,
  1516. 'lines' => [],
  1517. ];
  1518. }
  1519. $sid = (int)($d['scydgy_id'] ?? 0);
  1520. $am = trim((string)($d['amount'] ?? ''));
  1521. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1522. if ($gymc === '') {
  1523. $gymc = '工序';
  1524. }
  1525. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1526. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1527. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1528. $deliveryShow = $deliveryRaw;
  1529. }
  1530. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1531. $deliveryFilled = ($deliveryShow !== '');
  1532. $byCompany[$cn]['lines'][] = [
  1533. 'cgymc' => $gymc,
  1534. 'amount' => $am,
  1535. 'amount_show' => $amountFilled ? $am : '',
  1536. 'amount_filled' => $amountFilled,
  1537. 'delivery' => $deliveryRaw,
  1538. 'delivery_show' => $deliveryFilled ? $deliveryShow : '',
  1539. 'delivery_filled' => $deliveryFilled,
  1540. 'status_name' => trim((string)($d['status_name'] ?? '')),
  1541. 'is_quoted' => $amountFilled,
  1542. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  1543. ];
  1544. }
  1545. foreach ($byCompany as $cn => $g) {
  1546. $total = count($g['lines']);
  1547. $quoted = 0;
  1548. foreach ($g['lines'] as $ln) {
  1549. $am = trim((string)($ln['amount'] ?? ''));
  1550. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1551. $quoted++;
  1552. }
  1553. }
  1554. $byCompany[$cn]['has_quote'] = $total > 0 && $quoted === $total;
  1555. }
  1556. return array_values($byCompany);
  1557. }
  1558. /**
  1559. * 确认供应商弹窗:通知对象(不含报价,仅工序与联系方式)
  1560. *
  1561. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1562. * @return array<int, array<string, mixed>>
  1563. */
  1564. protected function loadAuditSupplierNotifyGroups(array $bundle): array
  1565. {
  1566. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  1567. $out = [];
  1568. foreach ($groups as $g) {
  1569. if (!is_array($g)) {
  1570. continue;
  1571. }
  1572. $processNames = [];
  1573. foreach ($g['lines'] ?? [] as $ln) {
  1574. if (!is_array($ln)) {
  1575. continue;
  1576. }
  1577. $n = trim((string)($ln['cgymc'] ?? ''));
  1578. if ($n !== '' && !in_array($n, $processNames, true)) {
  1579. $processNames[] = $n;
  1580. }
  1581. }
  1582. $out[] = [
  1583. 'name' => trim((string)($g['name'] ?? '')),
  1584. 'email' => trim((string)($g['email'] ?? '')),
  1585. 'phone' => trim((string)($g['phone'] ?? '')),
  1586. 'username' => trim((string)($g['username'] ?? '')),
  1587. 'process_names' => $processNames,
  1588. 'process_text' => implode('、', $processNames),
  1589. ];
  1590. }
  1591. return $out;
  1592. }
  1593. /**
  1594. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  1595. *
  1596. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1597. * @return array<int, array<string, mixed>>
  1598. */
  1599. protected function loadConfirmSupplierPickGroups(array $bundle): array
  1600. {
  1601. $sids = [];
  1602. $poIdMap = [];
  1603. foreach ($bundle['pos'] ?? [] as $po) {
  1604. if (!is_array($po)) {
  1605. continue;
  1606. }
  1607. $sid = (int)($po['scydgy_id'] ?? 0);
  1608. if ($this->isValidScydgyRowId($sid)) {
  1609. $sids[$sid] = true;
  1610. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  1611. }
  1612. }
  1613. if ($sids === []) {
  1614. return [];
  1615. }
  1616. $gymcMap = [];
  1617. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1618. if (!is_array($mr)) {
  1619. continue;
  1620. }
  1621. $gid = $this->extractScydgyRowId($mr);
  1622. if ($this->isValidScydgyRowId($gid)) {
  1623. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1624. }
  1625. }
  1626. foreach ($bundle['pos'] ?? [] as $po) {
  1627. if (!is_array($po)) {
  1628. continue;
  1629. }
  1630. $gid = (int)($po['scydgy_id'] ?? 0);
  1631. if ($this->isValidScydgyRowId($gid)) {
  1632. $nm = trim((string)($po['CGYMC'] ?? ''));
  1633. if ($nm !== '') {
  1634. $gymcMap[$gid] = $nm;
  1635. }
  1636. }
  1637. }
  1638. try {
  1639. $details = Db::table('purchase_order_detail')
  1640. ->where('scydgy_id', 'in', array_keys($sids))
  1641. ->order('company_name', 'asc')
  1642. ->order('id', 'asc')
  1643. ->select();
  1644. } catch (\Throwable $e) {
  1645. try {
  1646. $details = Db::table('purchase_order_detail')
  1647. ->where('scydgy_id', 'in', array_keys($sids))
  1648. ->order('company_name', 'asc')
  1649. ->order('ID', 'asc')
  1650. ->select();
  1651. } catch (\Throwable $e2) {
  1652. $details = [];
  1653. }
  1654. }
  1655. if (!is_array($details)) {
  1656. $details = [];
  1657. }
  1658. $byCompany = [];
  1659. foreach ($details as $d) {
  1660. if (!is_array($d)) {
  1661. continue;
  1662. }
  1663. $cn = trim((string)($d['company_name'] ?? ''));
  1664. if ($cn === '') {
  1665. continue;
  1666. }
  1667. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  1668. $sid = (int)($d['scydgy_id'] ?? 0);
  1669. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  1670. continue;
  1671. }
  1672. if (!isset($byCompany[$cn])) {
  1673. $ph = trim((string)($d['phone'] ?? ''));
  1674. $username = trim((string)($d['username'] ?? ''));
  1675. if ($username === '') {
  1676. $username = $this->resolveCustomerContactName($ph, $cn);
  1677. }
  1678. $byCompany[$cn] = [
  1679. 'name' => $cn,
  1680. 'email' => trim((string)($d['email'] ?? '')),
  1681. 'phone' => $ph,
  1682. 'username' => $username,
  1683. 'pick_lines' => [],
  1684. 'detail_picks' => [],
  1685. ];
  1686. }
  1687. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1688. if ($gymc === '') {
  1689. $gymc = '工序';
  1690. }
  1691. $am = trim((string)($d['amount'] ?? ''));
  1692. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1693. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1694. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1695. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1696. $deliveryShow = $deliveryRaw;
  1697. }
  1698. $byCompany[$cn]['pick_lines'][$sid] = [
  1699. 'cgymc' => $gymc,
  1700. 'amount_text' => $amountFilled ? $am : '未填写',
  1701. 'delivery_text' => $deliveryShow !== '' ? $deliveryShow : '未填写',
  1702. 'is_quoted' => $amountFilled,
  1703. ];
  1704. $byCompany[$cn]['detail_picks'][$sid] = [
  1705. 'scydgy_id' => $sid,
  1706. 'detail_id' => $detailId,
  1707. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  1708. 'cgymc' => $gymc,
  1709. ];
  1710. }
  1711. $out = [];
  1712. foreach ($byCompany as $g) {
  1713. $pickLines = $g['pick_lines'] ?? [];
  1714. if (!is_array($pickLines) || $pickLines === []) {
  1715. continue;
  1716. }
  1717. $g['pick_lines'] = array_values($pickLines);
  1718. $detailPicks = $g['detail_picks'] ?? [];
  1719. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  1720. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  1721. unset($g['detail_picks']);
  1722. $out[] = $g;
  1723. }
  1724. return $out;
  1725. }
  1726. /**
  1727. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  1728. * @return array<int, int[]> scydgy_id => detail_id[]
  1729. */
  1730. protected function mapDetailIdsByScydgyId(array $details): array
  1731. {
  1732. $out = [];
  1733. foreach ($details as $d) {
  1734. if (!is_array($d)) {
  1735. continue;
  1736. }
  1737. $sid = (int)($d['scydgy_id'] ?? 0);
  1738. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  1739. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  1740. continue;
  1741. }
  1742. if (!isset($out[$sid])) {
  1743. $out[$sid] = [];
  1744. }
  1745. $out[$sid][] = $pk;
  1746. }
  1747. foreach ($out as $sid => $ids) {
  1748. $out[$sid] = array_values(array_unique($ids));
  1749. }
  1750. return $out;
  1751. }
  1752. /**
  1753. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  1754. *
  1755. * @param array<string, mixed> $dbRow
  1756. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  1757. */
  1758. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  1759. {
  1760. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1761. $r = [
  1762. 'ID' => $sid,
  1763. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  1764. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  1765. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  1766. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  1767. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  1768. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  1769. 'CDW' => $dbRow['CDW'] ?? '',
  1770. 'NGZL' => $dbRow['NGZL'] ?? '',
  1771. 'CDF' => $dbRow['CDF'] ?? '',
  1772. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  1773. 'MBZ' => $dbRow['MBZ'] ?? '',
  1774. 'bwjg' => $dbRow['bwjg'] ?? '',
  1775. 'iStatus' => $dbRow['iStatus'] ?? '',
  1776. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  1777. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  1778. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  1779. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  1780. 'dStamp' => $dbRow['dStamp'] ?? '',
  1781. 'pick_time' => $dbRow['pick_time'] ?? '',
  1782. ];
  1783. if ($sid > 0 && isset($dStampMap[$sid])) {
  1784. $t = trim((string)$dStampMap[$sid]);
  1785. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1786. $r['dStamp'] = $dStampMap[$sid];
  1787. }
  1788. }
  1789. $dsOut = trim((string)($r['dStamp'] ?? ''));
  1790. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  1791. $ct = $dbRow['createtime'];
  1792. if (is_numeric($ct) && (int)$ct > 946684800) {
  1793. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  1794. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  1795. $r['dStamp'] = trim($ct);
  1796. }
  1797. }
  1798. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  1799. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  1800. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  1801. $fallback = trim((string)($r['dStamp'] ?? ''));
  1802. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  1803. $r['dputrecord'] = $fallback;
  1804. }
  1805. }
  1806. if (array_key_exists('id', $dbRow)) {
  1807. $r['purchase_order_id'] = (int)$dbRow['id'];
  1808. }
  1809. if ($sid < 0) {
  1810. $r['_is_manual'] = 1;
  1811. }
  1812. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  1813. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  1814. if ($pickNm !== '') {
  1815. $r['pick_company_name'] = $pickNm;
  1816. $r['picked_supplier_name'] = $pickNm;
  1817. }
  1818. return $r;
  1819. }
  1820. /**
  1821. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  1822. *
  1823. * @return array<int, array<string, mixed>>
  1824. */
  1825. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  1826. {
  1827. $pool = [];
  1828. if (!is_array($dbRows) || $dbRows === []) {
  1829. return $pool;
  1830. }
  1831. $dStampMap = [];
  1832. $sidList = [];
  1833. foreach ($dbRows as $tmpRow) {
  1834. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  1835. $sid = (int)$tmpRow['scydgy_id'];
  1836. if ($sid > 0) {
  1837. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  1838. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  1839. $sidList[$sid] = true;
  1840. }
  1841. }
  1842. }
  1843. }
  1844. if ($sidList !== []) {
  1845. try {
  1846. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  1847. } catch (\Throwable $e) {
  1848. $dStampMap = [];
  1849. }
  1850. }
  1851. foreach ($dbRows as $dbRow) {
  1852. if (!is_array($dbRow)) {
  1853. continue;
  1854. }
  1855. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  1856. }
  1857. return $pool;
  1858. }
  1859. /**
  1860. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  1861. *
  1862. * @param int[] $scydgyIds
  1863. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  1864. */
  1865. protected function OrderDetailSummary(array $scydgyIds)
  1866. {
  1867. $out = [];
  1868. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1869. if ($scydgyIds === []) {
  1870. return $out;
  1871. }
  1872. $list = [];
  1873. try {
  1874. $list = Db::table('purchase_order_detail')
  1875. ->where('scydgy_id', 'in', $scydgyIds)
  1876. ->field('id,scydgy_id,amount,delivery')
  1877. ->select();
  1878. } catch (\Throwable $e) {
  1879. $list = [];
  1880. }
  1881. if (!is_array($list)) {
  1882. return $out;
  1883. }
  1884. foreach ($list as $r) {
  1885. if (!is_array($r)) {
  1886. continue;
  1887. }
  1888. $ids = (int)($r['scydgy_id'] ?? 0);
  1889. if (!$this->isValidScydgyRowId($ids)) {
  1890. continue;
  1891. }
  1892. if (!isset($out[$ids])) {
  1893. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  1894. }
  1895. $out[$ids]['cnt']++;
  1896. $am = $r['amount'] ?? null;
  1897. if ($am !== null && $am !== '') {
  1898. if (!(is_string($am) && trim($am) === '')) {
  1899. $out[$ids]['amt']++;
  1900. }
  1901. }
  1902. $dv = $r['delivery'] ?? null;
  1903. if ($dv !== null && trim((string)$dv) !== '') {
  1904. $out[$ids]['deliv']++;
  1905. }
  1906. }
  1907. return $out;
  1908. }
  1909. /**
  1910. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  1911. *
  1912. * @return array
  1913. */
  1914. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  1915. {
  1916. $strContains = function ($haystack, $needle) {
  1917. if ($needle === '') {
  1918. return false;
  1919. }
  1920. $haystack = (string)$haystack;
  1921. if (function_exists('mb_stripos')) {
  1922. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  1923. }
  1924. return stripos($haystack, $needle) !== false;
  1925. };
  1926. $stripAlias = function ($f) {
  1927. return preg_replace('/^[ab]\./i', '', (string)$f);
  1928. };
  1929. $searchColNames = [];
  1930. foreach (explode(',', $this->searchFields) as $colRaw) {
  1931. $c = $stripAlias(trim($colRaw));
  1932. if ($c !== '') {
  1933. $searchColNames[] = $c;
  1934. }
  1935. }
  1936. $filtered = [];
  1937. foreach ($pool as $r) {
  1938. if (!is_array($r)) {
  1939. continue;
  1940. }
  1941. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  1942. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  1943. if (!$isManual) {
  1944. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  1945. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  1946. continue;
  1947. }
  1948. if ($applyMonthRange) {
  1949. $mo = (int)$m[2];
  1950. if ($mo < 1 || $mo > 12) {
  1951. continue;
  1952. }
  1953. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  1954. $rowMonthStart = $ymRow . '-01 00:00:00';
  1955. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  1956. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  1957. continue;
  1958. }
  1959. }
  1960. } elseif ($applyMonthRange) {
  1961. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  1962. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  1963. $ds = $listTime;
  1964. }
  1965. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  1966. continue;
  1967. }
  1968. $mo = (int)$m[2];
  1969. if ($mo < 1 || $mo > 12) {
  1970. continue;
  1971. }
  1972. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  1973. $rowMonthStart = $ymRow . '-01 00:00:00';
  1974. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  1975. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  1976. continue;
  1977. }
  1978. }
  1979. if ($search !== '') {
  1980. $hitSearch = false;
  1981. foreach ($searchColNames as $c) {
  1982. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  1983. if ($cell !== '' && $strContains($cell, $search)) {
  1984. $hitSearch = true;
  1985. break;
  1986. }
  1987. }
  1988. if (!$hitSearch) {
  1989. continue;
  1990. }
  1991. }
  1992. foreach ($filterArr as $fk => $fv) {
  1993. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  1994. continue;
  1995. }
  1996. if (is_array($fv)) {
  1997. continue;
  1998. }
  1999. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2000. continue;
  2001. }
  2002. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2003. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2004. $field = $stripAlias($fk);
  2005. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2006. $cellStr = trim((string)$cell);
  2007. switch ($sym) {
  2008. case '=':
  2009. if ((string)$cell !== (string)$fv) {
  2010. continue 3;
  2011. }
  2012. break;
  2013. case '<>':
  2014. if ((string)$cell === (string)$fv) {
  2015. continue 3;
  2016. }
  2017. break;
  2018. case 'LIKE':
  2019. case 'NOT LIKE':
  2020. $needle = trim((string)$fv);
  2021. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2022. if ($sym === 'LIKE' && !$hit) {
  2023. continue 3;
  2024. }
  2025. if ($sym === 'NOT LIKE' && $hit) {
  2026. continue 3;
  2027. }
  2028. break;
  2029. case '>':
  2030. case '>=':
  2031. case '<':
  2032. case '<=':
  2033. if (!is_numeric($cell) && $cellStr === '') {
  2034. continue 3;
  2035. }
  2036. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2037. $vv = (float)$fv;
  2038. if ($sym === '>' && !($cv > $vv)) {
  2039. continue 3;
  2040. }
  2041. if ($sym === '>=' && !($cv >= $vv)) {
  2042. continue 3;
  2043. }
  2044. if ($sym === '<' && !($cv < $vv)) {
  2045. continue 3;
  2046. }
  2047. if ($sym === '<=' && !($cv <= $vv)) {
  2048. continue 3;
  2049. }
  2050. break;
  2051. case 'RANGE':
  2052. case 'NOT RANGE':
  2053. case 'BETWEEN':
  2054. case 'NOT BETWEEN':
  2055. case 'BETWEEN TIME':
  2056. case 'NOT BETWEEN TIME':
  2057. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2058. $rawR = str_replace(' - ', ',', $rawR);
  2059. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2060. if (count($arr) < 2) {
  2061. break;
  2062. }
  2063. $lo = $arr[0];
  2064. $hi = $arr[1];
  2065. if ($lo === '' && $hi === '') {
  2066. break;
  2067. }
  2068. $isNot = (strpos($sym, 'NOT') !== false);
  2069. if ($lo === '') {
  2070. $in = ($cellStr !== '' && $cellStr <= $hi);
  2071. if ($isNot ? $in : !$in) {
  2072. continue 3;
  2073. }
  2074. break;
  2075. }
  2076. if ($hi === '') {
  2077. $in = ($cellStr !== '' && $cellStr >= $lo);
  2078. if ($isNot ? $in : !$in) {
  2079. continue 3;
  2080. }
  2081. break;
  2082. }
  2083. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2084. if ($isNot ? $in : !$in) {
  2085. continue 3;
  2086. }
  2087. break;
  2088. case 'NULL':
  2089. case 'IS NULL':
  2090. if ($cell !== null && $cell !== '') {
  2091. continue 3;
  2092. }
  2093. break;
  2094. case 'NOT NULL':
  2095. case 'IS NOT NULL':
  2096. if ($cell === null || $cell === '') {
  2097. continue 3;
  2098. }
  2099. break;
  2100. default:
  2101. break;
  2102. }
  2103. }
  2104. $filtered[] = $r;
  2105. }
  2106. return $filtered;
  2107. }
  2108. /**
  2109. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2110. */
  2111. public function snapshotToProcure()
  2112. {
  2113. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2114. $this->error(__('Invalid parameters'));
  2115. }
  2116. $row = json_decode($this->request->post('row_json', ''), true);
  2117. if (!is_array($row)) {
  2118. $this->error(__('Invalid parameters'));
  2119. }
  2120. try {
  2121. $ids = $this->extractScydgyRowId($row);
  2122. if (!$this->isValidScydgyRowId($ids)) {
  2123. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2124. }
  2125. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2126. $data = [
  2127. 'scydgy_id' => $ids,
  2128. 'CCYDH' => $row['CCYDH'] ?? null,
  2129. 'CYJMC' => $row['CYJMC'] ?? null,
  2130. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2131. 'CDXMC' => $row['CDXMC'] ?? null,
  2132. 'CGYBH' => $row['CGYBH'] ?? null,
  2133. 'CGYMC' => $row['CGYMC'] ?? null,
  2134. 'CDW' => $row['CDW'] ?? null,
  2135. 'NGZL' => $row['NGZL'] ?? null,
  2136. 'CDF' => $row['CDF'] ?? null,
  2137. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2138. 'MBZ' => $row['MBZ'] ?? null,
  2139. 'bwjg' => $row['bwjg'] ?? null,
  2140. 'iStatus' => $row['iStatus'] ?? null,
  2141. 'dStamp' => $row['dStamp'] ?? null,
  2142. 'dputrecord' => $row['dputrecord'] ?? null,
  2143. 'cywyxm' => $row['cywyxm'] ?? null,
  2144. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2145. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2146. ];
  2147. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  2148. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  2149. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  2150. $this->success('操作成功');
  2151. return;
  2152. }
  2153. if ($exists) {
  2154. $upd = $data;
  2155. unset($upd['scydgy_id'], $upd['status']);
  2156. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2157. } else {
  2158. // 新增:不写 status(空/走库默认);仅写创建时间
  2159. $data['createtime'] = date('Y-m-d H:i:s');
  2160. Db::table('purchase_order')->insert($data);
  2161. }
  2162. } catch (\Throwable $e) {
  2163. $this->error($e->getMessage());
  2164. }
  2165. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  2166. $this->success('操作成功');
  2167. }
  2168. /**
  2169. * 未发列表
  2170. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  2171. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  2172. */
  2173. public function completeDirectly()
  2174. {
  2175. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2176. $this->error(__('参数错误'));
  2177. }
  2178. $row = json_decode($this->request->post('row_json', ''), true);
  2179. if (!is_array($row)) {
  2180. $this->error(__('Invalid parameters'));
  2181. }
  2182. $finishRaw = $this->request->post('finish', '1');
  2183. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  2184. try {
  2185. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  2186. $ids = $this->extractScydgyRowId($row);
  2187. if (!$this->isValidScydgyRowId($ids)) {
  2188. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2189. }
  2190. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2191. $data = [
  2192. 'scydgy_id' => $ids,
  2193. 'CCYDH' => $row['CCYDH'] ?? null,
  2194. 'CYJMC' => $row['CYJMC'] ?? null,
  2195. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2196. 'CDXMC' => $row['CDXMC'] ?? null,
  2197. 'CGYBH' => $row['CGYBH'] ?? null,
  2198. 'CGYMC' => $row['CGYMC'] ?? null,
  2199. 'CDW' => $row['CDW'] ?? null,
  2200. 'NGZL' => $row['NGZL'] ?? null,
  2201. 'CDF' => $row['CDF'] ?? null,
  2202. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2203. 'MBZ' => $row['MBZ'] ?? null,
  2204. 'bwjg' => $row['bwjg'] ?? null,
  2205. 'iStatus' => $row['iStatus'] ?? null,
  2206. 'dStamp' => $row['dStamp'] ?? null,
  2207. 'dputrecord' => $row['dputrecord'] ?? null,
  2208. 'cywyxm' => $row['cywyxm'] ?? null,
  2209. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2210. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2211. ];
  2212. if ($asComplete) {
  2213. // 主表 status 为 varchar 时统一写 '1',档案 procuremenarchive 按 status=1 查询
  2214. $data['status'] = '1';
  2215. }
  2216. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  2217. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  2218. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  2219. $this->success('操作成功');
  2220. return;
  2221. }
  2222. if ($exists) {
  2223. $upd = $data;
  2224. unset($upd['scydgy_id']);
  2225. if (!$asComplete) {
  2226. unset($upd['status']);
  2227. }
  2228. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2229. } else {
  2230. // 新增:不写 status;完结时 $data 已含 status=1
  2231. $data['createtime'] = date('Y-m-d H:i:s');
  2232. Db::table('purchase_order')->insert($data);
  2233. }
  2234. } catch (\Throwable $e) {
  2235. $this->error($e->getMessage());
  2236. }
  2237. $poIdLog = null;
  2238. try {
  2239. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2240. if (is_array($rpo)) {
  2241. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2242. $poIdLog = $tid > 0 ? $tid : null;
  2243. }
  2244. } catch (\Throwable $e) {
  2245. $poIdLog = null;
  2246. }
  2247. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  2248. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  2249. if ($asComplete) {
  2250. $this->addOrderLog(
  2251. $ids,
  2252. 'mark_complete',
  2253. '点击「完结」,已标记为已完结',
  2254. $poIdLog
  2255. );
  2256. try {
  2257. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  2258. if ($pdfPublicPath === '') {
  2259. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  2260. }
  2261. } catch (\Throwable $e) {
  2262. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  2263. }
  2264. } else {
  2265. $this->addOrderLog(
  2266. $ids,
  2267. 'save_qty_price',
  2268. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  2269. $poIdLog
  2270. );
  2271. }
  2272. $this->success("操作成功");
  2273. }
  2274. /**
  2275. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  2276. *
  2277. * @param array<int, array> $rows 引用传递当前页行
  2278. */
  2279. protected function mergePurchaseOrder(array &$rows)
  2280. {
  2281. if ($rows === []) {
  2282. return;
  2283. }
  2284. $ids = [];
  2285. foreach ($rows as $rw) {
  2286. if (!is_array($rw)) {
  2287. continue;
  2288. }
  2289. $id = (int)($rw['ID'] ?? 0);
  2290. if ($id > 0) {
  2291. $ids[$id] = true;
  2292. }
  2293. }
  2294. $idList = array_keys($ids);
  2295. if ($idList === []) {
  2296. return;
  2297. }
  2298. try {
  2299. $list = Db::table('purchase_order')
  2300. ->where('scydgy_id', 'in', $idList)
  2301. ->field('scydgy_id,This_quantity,ceilingPrice')
  2302. ->select();
  2303. } catch (\Throwable $e) {
  2304. return;
  2305. }
  2306. if (!is_array($list)) {
  2307. return;
  2308. }
  2309. $byId = [];
  2310. foreach ($list as $dbRow) {
  2311. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  2312. continue;
  2313. }
  2314. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  2315. }
  2316. foreach ($rows as &$rw) {
  2317. if (!is_array($rw)) {
  2318. continue;
  2319. }
  2320. $sid = (int)($rw['ID'] ?? 0);
  2321. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  2322. continue;
  2323. }
  2324. $db = $byId[$sid];
  2325. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  2326. $rw['This_quantity'] = $db['This_quantity'];
  2327. }
  2328. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  2329. $rw['ceilingPrice'] = $db['ceilingPrice'];
  2330. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  2331. $rw['ceilingPrice'] = $db['ceiling_price'];
  2332. }
  2333. }
  2334. unset($rw);
  2335. }
  2336. /**
  2337. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  2338. */
  2339. public function purchaseConfirmPick()
  2340. {
  2341. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2342. $this->error(__('Invalid parameters'));
  2343. }
  2344. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  2345. if ($batchRaw !== '') {
  2346. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  2347. return;
  2348. }
  2349. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  2350. $sid = (int)$scydgyId;
  2351. if (!$this->isValidScydgyRowId($sid)) {
  2352. $this->error('参数无效');
  2353. }
  2354. $parseIdList = function ($raw) {
  2355. if (is_array($raw)) {
  2356. $arr = $raw;
  2357. } else {
  2358. $decoded = json_decode((string)$raw, true);
  2359. $arr = is_array($decoded) ? $decoded : [];
  2360. }
  2361. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  2362. };
  2363. $selectedRaw = $this->request->post('selected_ids', null);
  2364. if ($selectedRaw === null || $selectedRaw === '') {
  2365. $legacy = (int)$this->request->post('selected_id', 0);
  2366. $selectedIds = $legacy > 0 ? [$legacy] : [];
  2367. } else {
  2368. $selectedIds = $parseIdList($selectedRaw);
  2369. }
  2370. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  2371. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  2372. try {
  2373. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  2374. } catch (\InvalidArgumentException $e) {
  2375. $this->error($e->getMessage());
  2376. } catch (\Throwable $e) {
  2377. $this->error($e->getMessage());
  2378. }
  2379. $this->success('操作成功', '', $result);
  2380. }
  2381. /**
  2382. * 整单采购确认(多道工序一次提交)
  2383. */
  2384. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  2385. {
  2386. $decoded = json_decode($batchRaw, true);
  2387. if (!is_array($decoded) || $decoded === []) {
  2388. $this->error('提交数据无效');
  2389. }
  2390. $picks = [];
  2391. foreach ($decoded as $item) {
  2392. if (!is_array($item)) {
  2393. continue;
  2394. }
  2395. $sid = (int)($item['scydgy_id'] ?? 0);
  2396. if (!$this->isValidScydgyRowId($sid)) {
  2397. continue;
  2398. }
  2399. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  2400. if (!is_array($sel)) {
  2401. $sel = [(int)$sel];
  2402. }
  2403. $unsel = $item['unselected_ids'] ?? [];
  2404. if (!is_array($unsel)) {
  2405. $unsel = json_decode((string)$unsel, true);
  2406. $unsel = is_array($unsel) ? $unsel : [];
  2407. }
  2408. $picks[] = [
  2409. 'scydgy_id' => $sid,
  2410. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  2411. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  2412. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  2413. ];
  2414. }
  2415. if ($picks === []) {
  2416. $this->error('提交数据无效');
  2417. }
  2418. Db::startTrans();
  2419. $results = [];
  2420. try {
  2421. foreach ($picks as $pick) {
  2422. $results[] = $this->runPurchaseConfirmPick(
  2423. (int)$pick['scydgy_id'],
  2424. $pick['selected_ids'],
  2425. $pick['unselected_ids'],
  2426. (int)$pick['purchase_order_id'],
  2427. false
  2428. );
  2429. }
  2430. Db::commit();
  2431. } catch (\Throwable $e) {
  2432. Db::rollback();
  2433. $msg = $e->getMessage();
  2434. $this->error($msg !== '' ? $msg : '提交失败');
  2435. }
  2436. $this->success('操作成功', '', ['batch' => $results]);
  2437. }
  2438. /**
  2439. * @return array<string, mixed>
  2440. */
  2441. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true): array
  2442. {
  2443. $scydgyId = (string)$sid;
  2444. if ($selectedIds === []) {
  2445. throw new \InvalidArgumentException('请至少勾选一条明细');
  2446. }
  2447. $inter = array_intersect($selectedIds, $unselectedIds);
  2448. if ($inter !== []) {
  2449. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  2450. }
  2451. $allIds = $this->purchaseOrderDetail($sid);
  2452. if ($allIds === []) {
  2453. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  2454. }
  2455. foreach ($selectedIds as $id) {
  2456. if (!in_array($id, $allIds, true)) {
  2457. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  2458. }
  2459. }
  2460. foreach ($unselectedIds as $id) {
  2461. if (!in_array($id, $allIds, true)) {
  2462. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  2463. }
  2464. }
  2465. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  2466. sort($union, SORT_NUMERIC);
  2467. $expect = $allIds;
  2468. sort($expect, SORT_NUMERIC);
  2469. if ($union !== $expect) {
  2470. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  2471. }
  2472. if ($manageTransaction) {
  2473. Db::startTrans();
  2474. }
  2475. try {
  2476. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
  2477. $aff = 0;
  2478. try {
  2479. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => 1]);
  2480. } catch (\Throwable $e) {
  2481. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => 1]);
  2482. }
  2483. if ($aff < 1) {
  2484. throw new \Exception('更新选中状态失败');
  2485. }
  2486. if ($purchaseOrderId > 0) {
  2487. $poAff = (int)Db::table('purchase_order')
  2488. ->where('id', $purchaseOrderId)
  2489. ->where('scydgy_id', $sid)
  2490. ->update(['status' => 1]);
  2491. if ($poAff < 1) {
  2492. throw new \Exception('主表订单不存在或与工序行不匹配');
  2493. }
  2494. } else {
  2495. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update(['status' => '1']);
  2496. if ($poAff < 1) {
  2497. throw new \Exception('未找到');
  2498. }
  2499. }
  2500. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  2501. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  2502. if ($manageTransaction) {
  2503. Db::commit();
  2504. }
  2505. } catch (\Throwable $e) {
  2506. if ($manageTransaction) {
  2507. Db::rollback();
  2508. }
  2509. throw $e;
  2510. }
  2511. $poIdFinal = $purchaseOrderId;
  2512. if ($poIdFinal <= 0) {
  2513. try {
  2514. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2515. if (is_array($rpo)) {
  2516. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2517. }
  2518. } catch (\Throwable $e) {
  2519. $poIdFinal = 0;
  2520. }
  2521. }
  2522. $pickNames = [];
  2523. foreach ($selectedIds as $pid) {
  2524. $dr = $this->purchaseOrderDetai($sid, $pid);
  2525. $nm = trim((string)($dr['company_name'] ?? ''));
  2526. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  2527. }
  2528. $this->addOrderLog(
  2529. $sid,
  2530. 'purchase_confirm',
  2531. '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
  2532. $poIdFinal > 0 ? $poIdFinal : null
  2533. );
  2534. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
  2535. $sendSmsSafe = function ($phone, $content) {
  2536. $phone = trim((string)$phone);
  2537. if ($phone === '') {
  2538. return;
  2539. }
  2540. try {
  2541. $this->smsbao($phone, $content);
  2542. } catch (\Throwable $e) {
  2543. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  2544. }
  2545. };
  2546. foreach ($selectedIds as $pid) {
  2547. $dr = $this->purchaseOrderDetai($sid, $pid);
  2548. if (!is_array($dr)) {
  2549. continue;
  2550. }
  2551. $cname = trim((string)($dr['company_name'] ?? ''));
  2552. $ph = trim((string)($dr['phone'] ?? ''));
  2553. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  2554. 'company_name' => $cname,
  2555. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2556. 'phone' => $ph,
  2557. ]));
  2558. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2559. }
  2560. foreach ($unselectedIds as $pid) {
  2561. $dr = $this->purchaseOrderDetai($sid, $pid);
  2562. if (!is_array($dr)) {
  2563. continue;
  2564. }
  2565. $cname = trim((string)($dr['company_name'] ?? ''));
  2566. $ph = trim((string)($dr['phone'] ?? ''));
  2567. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  2568. 'company_name' => $cname,
  2569. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2570. 'phone' => $ph,
  2571. ]));
  2572. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2573. }
  2574. Log::write(sprintf(
  2575. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  2576. $scydgyId,
  2577. $purchaseOrderId,
  2578. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  2579. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  2580. ), 'notice');
  2581. $pdfPublicPath = '';
  2582. try {
  2583. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  2584. } catch (\Throwable $e) {
  2585. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  2586. }
  2587. return [
  2588. 'scydgy_id' => $scydgyId,
  2589. 'purchase_order_id' => $purchaseOrderId,
  2590. 'selected_ids' => $selectedIds,
  2591. 'unselected_ids' => $unselectedIds,
  2592. 'purchase_confirm_pdf' => $pdfPublicPath,
  2593. ];
  2594. }
  2595. /**
  2596. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  2597. *
  2598. * @param int[] $detailIds
  2599. */
  2600. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  2601. {
  2602. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2603. if ($detailIds === []) {
  2604. return;
  2605. }
  2606. $payload = ['status_name' => $statusName];
  2607. try {
  2608. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  2609. } catch (\Throwable $e) {
  2610. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  2611. }
  2612. }
  2613. /**
  2614. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  2615. */
  2616. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  2617. {
  2618. try {
  2619. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  2620. } catch (\Throwable $e) {
  2621. return;
  2622. }
  2623. if (!is_array($rows)) {
  2624. return;
  2625. }
  2626. foreach ($rows as $dr) {
  2627. if (!is_array($dr)) {
  2628. continue;
  2629. }
  2630. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  2631. if ($id <= 0) {
  2632. continue;
  2633. }
  2634. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  2635. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  2636. try {
  2637. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  2638. } catch (\Throwable $e) {
  2639. }
  2640. }
  2641. }
  2642. /**
  2643. * @param array<string, mixed> $detailRow
  2644. */
  2645. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  2646. {
  2647. $am = $detailRow['amount'] ?? null;
  2648. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  2649. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2650. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2651. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2652. }
  2653. /**
  2654. * @return int[]
  2655. */
  2656. protected function purchaseOrderDetail(int $scydgyId): array
  2657. {
  2658. if (!$this->isValidScydgyRowId($scydgyId)) {
  2659. return [];
  2660. }
  2661. try {
  2662. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  2663. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  2664. $list = $listQuery->select();
  2665. } catch (\Throwable $e) {
  2666. return [];
  2667. }
  2668. if (!is_array($list)) {
  2669. return [];
  2670. }
  2671. $ids = [];
  2672. foreach ($list as $r) {
  2673. if (!is_array($r)) {
  2674. continue;
  2675. }
  2676. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  2677. if ($pk > 0) {
  2678. $ids[] = $pk;
  2679. }
  2680. }
  2681. return array_values(array_unique($ids));
  2682. }
  2683. /**
  2684. * 获取当前登录用户信息 [id, 展示名]
  2685. */
  2686. protected function GetUseName(): array
  2687. {
  2688. $id = 0;
  2689. $name = '';
  2690. try {
  2691. if ($this->auth && $this->auth->isLogin()) {
  2692. $u = $this->auth->getUserInfo();
  2693. if (is_array($u)) {
  2694. $id = (int)($u['id'] ?? 0);
  2695. $name = trim((string)($u['nickname'] ?? ''));
  2696. if ($name === '') {
  2697. $name = trim((string)($u['username'] ?? ''));
  2698. }
  2699. }
  2700. }
  2701. } catch (\Throwable $e) {
  2702. }
  2703. if ($name === '') {
  2704. $name = '未知用户';
  2705. }
  2706. return [$id, $name];
  2707. }
  2708. /**
  2709. * 外发采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  2710. */
  2711. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  2712. {
  2713. if (!$this->isValidScydgyRowId($scydgyId) || $content === '') {
  2714. return;
  2715. }
  2716. list($adminId, $adminName) = $this->GetUseName();
  2717. $cut = function ($s, $max) {
  2718. if (function_exists('mb_substr')) {
  2719. return mb_substr($s, 0, $max, 'UTF-8');
  2720. }
  2721. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  2722. };
  2723. try {
  2724. Db::table('purchase_order_oper_log')->insert([
  2725. 'scydgy_id' => $scydgyId,
  2726. 'purchase_order_id' => $purchaseOrderId,
  2727. 'admin_id' => $adminId,
  2728. 'admin_name' => $cut($adminName, 64),
  2729. 'action' => $cut((string)$action, 64),
  2730. 'content' => $cut($content, 1000),
  2731. // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
  2732. 'createtime' => time(),
  2733. ]);
  2734. } catch (\Throwable $e) {
  2735. Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
  2736. }
  2737. }
  2738. /**
  2739. * 按主键取一条
  2740. */
  2741. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  2742. {
  2743. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  2744. return [];
  2745. }
  2746. try {
  2747. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  2748. if (is_array($one)) {
  2749. return $one;
  2750. }
  2751. } catch (\Throwable $e) {
  2752. }
  2753. try {
  2754. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  2755. if (is_array($one)) {
  2756. return $one;
  2757. }
  2758. } catch (\Throwable $e) {
  2759. }
  2760. return [];
  2761. }
  2762. /**
  2763. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  2764. */
  2765. protected function formatProcuremenDetailTime($v): string
  2766. {
  2767. if ($v === null || $v === '') {
  2768. return '';
  2769. }
  2770. if (is_numeric($v) && (int)$v > 946684800) {
  2771. return date('Y-m-d H:i:s', (int)$v);
  2772. }
  2773. $s = trim((string)$v);
  2774. if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
  2775. return $s;
  2776. }
  2777. return '';
  2778. }
  2779. /**
  2780. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  2781. */
  2782. protected function formatDeliveryYmd($v): string
  2783. {
  2784. if ($v === null || $v === '') {
  2785. return '';
  2786. }
  2787. $s = trim((string)$v);
  2788. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  2789. return '';
  2790. }
  2791. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  2792. return $m[1];
  2793. }
  2794. $ts = strtotime($s);
  2795. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  2796. }
  2797. /**
  2798. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  2799. */
  2800. protected function detailRowSupplierAccepted(array $r): bool
  2801. {
  2802. $am = $r['amount'] ?? null;
  2803. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  2804. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  2805. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  2806. return $okAmt && $okDel;
  2807. }
  2808. /**
  2809. * 是否已向外发/供应商下发(有下发明细、已进入审批流或记录下发时间)
  2810. */
  2811. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  2812. {
  2813. if ($detailCount > 0) {
  2814. return true;
  2815. }
  2816. $wf = (int)($main['wflow_status'] ?? 0);
  2817. if ($wf >= 1) {
  2818. return true;
  2819. }
  2820. $pickTime = trim((string)($main['pick_time'] ?? ''));
  2821. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  2822. return true;
  2823. }
  2824. return false;
  2825. }
  2826. /**
  2827. * 下发时间:优先 pick_time,其次首条下发明细时间
  2828. */
  2829. protected function resolveProcuremenIssueTime(array $main, array $details): string
  2830. {
  2831. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  2832. if ($issueTime !== '') {
  2833. return $issueTime;
  2834. }
  2835. foreach ($details as $dr) {
  2836. if (!is_array($dr)) {
  2837. continue;
  2838. }
  2839. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  2840. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  2841. $issueTime = $t;
  2842. }
  2843. }
  2844. if ($issueTime !== '') {
  2845. return $issueTime;
  2846. }
  2847. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  2848. }
  2849. /**
  2850. * 直接点「完结」时间:优先操作记录 mark_complete
  2851. */
  2852. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  2853. {
  2854. if (!$this->isValidScydgyRowId($scydgyId)) {
  2855. return '';
  2856. }
  2857. try {
  2858. $log = Db::table('purchase_order_oper_log')
  2859. ->where('scydgy_id', $scydgyId)
  2860. ->where('action', 'mark_complete')
  2861. ->order('id', 'desc')
  2862. ->find();
  2863. if (is_array($log)) {
  2864. $ct = (int)($log['createtime'] ?? 0);
  2865. if ($ct > 946684800) {
  2866. return date('Y-m-d H:i:s', $ct);
  2867. }
  2868. }
  2869. } catch (\Throwable $e) {
  2870. }
  2871. return '';
  2872. }
  2873. /**
  2874. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  2875. *
  2876. * @param array $main purchase_order 一行
  2877. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  2878. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  2879. */
  2880. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  2881. {
  2882. $issueCnt = count($details);
  2883. $acceptCnt = 0;
  2884. $pickedName = '';
  2885. $pickedTime = '';
  2886. foreach ($details as $dr) {
  2887. if (!is_array($dr)) {
  2888. continue;
  2889. }
  2890. if ($this->detailRowSupplierAccepted($dr)) {
  2891. $acceptCnt++;
  2892. }
  2893. if ((int)($dr['status'] ?? 0) === 1) {
  2894. if ($pickedName === '') {
  2895. $pickedName = trim((string)($dr['company_name'] ?? ''));
  2896. }
  2897. if ($pickedTime === '') {
  2898. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  2899. if ($pickedTime === '') {
  2900. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  2901. }
  2902. }
  2903. }
  2904. }
  2905. $hasMain = $main !== [];
  2906. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  2907. if ($poTime === '') {
  2908. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  2909. }
  2910. $mainStatus = isset($main['status']) ? (int)$main['status'] : 0;
  2911. $wflowStatus = (int)($main['wflow_status'] ?? 0);
  2912. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  2913. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  2914. $auditNotifyTime = '';
  2915. if ($wflowStatus >= 2 || ($wflowStatus === 0 && $issueCnt > 0)) {
  2916. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  2917. if ($this->isValidScydgyRowId($scydgyId)) {
  2918. try {
  2919. $auditLog = Db::table('purchase_order_oper_log')
  2920. ->where('scydgy_id', $scydgyId)
  2921. ->where('action', 'audit_confirm')
  2922. ->order('id', 'desc')
  2923. ->find();
  2924. if (is_array($auditLog)) {
  2925. $ct = (int)($auditLog['createtime'] ?? 0);
  2926. if ($ct > 946684800) {
  2927. $auditNotifyTime = date('Y-m-d H:i:s', $ct);
  2928. }
  2929. }
  2930. } catch (\Throwable $e) {
  2931. }
  2932. }
  2933. if ($auditNotifyTime === '' && $issueTime !== '') {
  2934. $auditNotifyTime = $issueTime;
  2935. }
  2936. }
  2937. $supplierTime = '';
  2938. if ($acceptCnt > 0) {
  2939. foreach ($details as $dr) {
  2940. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  2941. continue;
  2942. }
  2943. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  2944. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  2945. $supplierTime = $t;
  2946. }
  2947. }
  2948. }
  2949. $directComplete = ($mainStatus === 1 && !$issued);
  2950. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  2951. $doneTime = '';
  2952. if ($mainStatus === 1) {
  2953. if ($directComplete) {
  2954. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  2955. }
  2956. if ($doneTime === '') {
  2957. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  2958. }
  2959. if ($doneTime === '') {
  2960. foreach ($details as $dr) {
  2961. if (!is_array($dr)) {
  2962. continue;
  2963. }
  2964. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  2965. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  2966. $doneTime = $t;
  2967. }
  2968. }
  2969. }
  2970. if ($doneTime === '') {
  2971. $doneTime = $poTime;
  2972. }
  2973. }
  2974. if ($directComplete) {
  2975. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  2976. $step1Done = $hasMain;
  2977. $step2Done = false;
  2978. $step3Done = false;
  2979. $step4Done = false;
  2980. $step5Done = false;
  2981. $step6Done = true;
  2982. } else {
  2983. $step1Done = $issued;
  2984. $step2Done = $issued;
  2985. // wflow=1:初选已下发、待审批确认通知;wflow>=2 或旧数据(有明细且 wf=0)视为已通知
  2986. $step3Done = $wflowStatus >= 2 || ($wflowStatus === 0 && $issueCnt > 0);
  2987. $step4Done = $acceptCnt > 0;
  2988. $step5Done = false;
  2989. foreach ($details as $dr) {
  2990. if (is_array($dr) && (int)($dr['status'] ?? 0) === 1) {
  2991. $step5Done = true;
  2992. break;
  2993. }
  2994. }
  2995. $step6Done = $mainStatus === 1;
  2996. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  2997. if ($mainStatus === 1 && $issued) {
  2998. $step3Done = true;
  2999. $step4Done = true;
  3000. $step5Done = true;
  3001. if ($supplierTime === '') {
  3002. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3003. if ($fillT !== '') {
  3004. $supplierTime = $fillT;
  3005. }
  3006. }
  3007. if ($pickedTime === '') {
  3008. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3009. if ($fillT !== '') {
  3010. $pickedTime = $fillT;
  3011. }
  3012. }
  3013. if ($auditNotifyTime === '') {
  3014. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3015. if ($fillT !== '') {
  3016. $auditNotifyTime = $fillT;
  3017. }
  3018. }
  3019. }
  3020. }
  3021. $auditPendingSubtitle = '待确认通知';
  3022. $steps = [
  3023. [
  3024. 'title' => '未发',
  3025. 'subtitle' => '',
  3026. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3027. 'done' => $step1Done,
  3028. ],
  3029. [
  3030. 'title' => '初选下发',
  3031. 'subtitle' => '',
  3032. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3033. 'done' => $step2Done,
  3034. ],
  3035. [
  3036. 'title' => '待审批',
  3037. 'subtitle' => $step3Done ? '' : $auditPendingSubtitle,
  3038. 'time' => $step3Done ? $auditNotifyTime : '',
  3039. 'done' => $step3Done,
  3040. ],
  3041. [
  3042. 'title' => '供应商接单',
  3043. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3044. 'time' => $step4Done ? $supplierTime : '',
  3045. 'done' => $step4Done,
  3046. ],
  3047. [
  3048. 'title' => '采购确认',
  3049. 'subtitle' => $pickedName !== '' ? ('选中供应商:' . $pickedName) : '',
  3050. 'time' => $step5Done ? ($pickedTime !== '' ? $pickedTime : '') : '',
  3051. 'done' => $step5Done,
  3052. ],
  3053. [
  3054. 'title' => '已完结',
  3055. 'subtitle' => '',
  3056. 'time' => $step6Done ? $doneTime : '',
  3057. 'done' => $step6Done,
  3058. ],
  3059. ];
  3060. $currentIdx = count($steps) - 1;
  3061. if (!$directComplete) {
  3062. foreach ($steps as $i => $s) {
  3063. if (!$s['done']) {
  3064. $currentIdx = $i;
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. $nSteps = count($steps);
  3070. foreach ($steps as $idx => &$s) {
  3071. $s['current'] = ($idx === $currentIdx);
  3072. if ($idx === 0) {
  3073. $s['pdf_left_bg'] = '';
  3074. } else {
  3075. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3076. }
  3077. if ($idx >= $nSteps - 1) {
  3078. $s['pdf_right_bg'] = '';
  3079. } else {
  3080. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3081. }
  3082. }
  3083. unset($s);
  3084. $labelMap = [
  3085. 'CCYDH' => '订单号',
  3086. 'CYJMC' => '印件名称',
  3087. 'CCLBMMC' => '承揽部门',
  3088. 'CGYMC' => '工序名称',
  3089. 'CDW' => '单位',
  3090. 'NGZL' => '工作量',
  3091. 'CDF' => '单价',
  3092. 'cGzzxMc' => '工作中心',
  3093. 'MBZ' => '备注',
  3094. 'This_quantity' => '本次数量',
  3095. 'ceilingPrice' => '最高限价',
  3096. ];
  3097. $orderSummary = [];
  3098. foreach ($labelMap as $key => $lab) {
  3099. if (!array_key_exists($key, $main)) {
  3100. continue;
  3101. }
  3102. $val = $main[$key];
  3103. if ($val === null) {
  3104. $val = '';
  3105. } elseif (!is_scalar($val)) {
  3106. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3107. } else {
  3108. $val = (string)$val;
  3109. }
  3110. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3111. }
  3112. $orderSummaryGrid = [];
  3113. $n = count($orderSummary);
  3114. for ($i = 0; $i < $n; $i += 2) {
  3115. $left = $orderSummary[$i];
  3116. $hasRight = ($i + 1) < $n;
  3117. $orderSummaryGrid[] = [
  3118. 'l1' => $left['label'],
  3119. 'v1' => $left['value'],
  3120. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3121. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3122. ];
  3123. }
  3124. return [
  3125. 'steps' => $steps,
  3126. 'orderSummary' => $orderSummary,
  3127. 'orderSummaryGrid' => $orderSummaryGrid,
  3128. 'detailRows' => $details,
  3129. ];
  3130. }
  3131. /**
  3132. * 加载并 assign 外发采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3133. *
  3134. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3135. */
  3136. protected function prepareProcuremenDetailsView(string $ids): array
  3137. {
  3138. $main = [];
  3139. try {
  3140. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3141. $main = is_array($one) ? $one : [];
  3142. } catch (\Throwable $e) {
  3143. $main = [];
  3144. }
  3145. $details = [];
  3146. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3147. if ($mergeRows === []) {
  3148. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3149. if ($mergeRows === [] && $main !== []) {
  3150. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3151. }
  3152. }
  3153. $detailSidList = [];
  3154. $anchorSid = (int)$ids;
  3155. if ($anchorSid !== 0) {
  3156. $detailSidList[$anchorSid] = true;
  3157. }
  3158. foreach ($mergeRows as $mr) {
  3159. if (!is_array($mr)) {
  3160. continue;
  3161. }
  3162. $sid = $this->extractScydgyRowId($mr);
  3163. if ($sid !== 0) {
  3164. $detailSidList[$sid] = true;
  3165. }
  3166. }
  3167. try {
  3168. if ($detailSidList !== []) {
  3169. $details = Db::table('purchase_order_detail')
  3170. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3171. ->order('id', 'asc')
  3172. ->select();
  3173. }
  3174. } catch (\Throwable $e) {
  3175. $details = [];
  3176. }
  3177. if (!is_array($details)) {
  3178. $details = [];
  3179. }
  3180. foreach ($details as &$r) {
  3181. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3182. $r['id'] = $r['ID'];
  3183. }
  3184. if (isset($r['createtime'])) {
  3185. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3186. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3187. } else {
  3188. $r['createtime_text'] = (string)$r['createtime'];
  3189. }
  3190. } else {
  3191. $r['createtime_text'] = '';
  3192. }
  3193. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3194. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3195. }
  3196. unset($r);
  3197. $activeDetails = [];
  3198. foreach ($details as $r) {
  3199. if (is_array($r) && empty($r['is_void'])) {
  3200. $activeDetails[] = $r;
  3201. }
  3202. }
  3203. $operLogs = [];
  3204. try {
  3205. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3206. } catch (\Throwable $e) {
  3207. $operLogs = [];
  3208. }
  3209. if (!is_array($operLogs)) {
  3210. $operLogs = [];
  3211. }
  3212. foreach ($operLogs as &$lg) {
  3213. if (!is_array($lg)) {
  3214. continue;
  3215. }
  3216. $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
  3217. $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
  3218. }
  3219. unset($lg);
  3220. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3221. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3222. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3223. if ($ccydh === '') {
  3224. foreach ($details as $r) {
  3225. if (!is_array($r)) {
  3226. continue;
  3227. }
  3228. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3229. if ($ccydh !== '') {
  3230. break;
  3231. }
  3232. }
  3233. }
  3234. $this->view->assign('ccydh', $ccydh);
  3235. $this->view->assign('steps', $bundle['steps']);
  3236. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3237. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3238. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3239. $this->view->assign('processCount', count($mergeRows));
  3240. $this->view->assign('detailRows', $details);
  3241. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3242. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3243. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3244. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3245. $this->view->assign('operLogs', $operLogs);
  3246. return [
  3247. 'ok' => $main !== [] || $details !== [],
  3248. 'ccydh' => $ccydh,
  3249. ];
  3250. }
  3251. /**
  3252. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3253. */
  3254. public function details()
  3255. {
  3256. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3257. if (is_array($ids)) {
  3258. $ids = isset($ids[0]) ? $ids[0] : '';
  3259. }
  3260. $ids = trim((string)$ids);
  3261. if ($ids === '') {
  3262. $this->error(__('Invalid parameters'));
  3263. }
  3264. $this->assertManualOrderDetailsViewable((int)$ids);
  3265. $this->prepareProcuremenDetailsView($ids);
  3266. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3267. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3268. $this->view->engine->layout(false);
  3269. try {
  3270. return $this->view->fetch('procuremen/details_dialog_shell');
  3271. } finally {
  3272. if ($restoreLayout) {
  3273. $this->view->engine->layout($restoreLayout);
  3274. }
  3275. }
  3276. }
  3277. /**
  3278. * 解析合并审核工序行(订单号须一致,且均未外发)
  3279. *
  3280. * @return array<int, array<string, mixed>>
  3281. */
  3282. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3283. {
  3284. $primary = json_decode($rowJson, true);
  3285. if (!is_array($primary)) {
  3286. $this->error(__('Invalid parameters'));
  3287. }
  3288. $merge = json_decode($mergeRowsJson, true);
  3289. if (!is_array($merge) || $merge === []) {
  3290. $merge = [$primary];
  3291. }
  3292. $seen = [];
  3293. $out = [];
  3294. foreach ($merge as $r) {
  3295. if (!is_array($r)) {
  3296. continue;
  3297. }
  3298. $id = $this->extractScydgyRowId($r);
  3299. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3300. continue;
  3301. }
  3302. $seen[$id] = true;
  3303. $out[] = $r;
  3304. }
  3305. if ($out === []) {
  3306. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3307. }
  3308. $ccydh = null;
  3309. foreach ($out as $r) {
  3310. $dh = trim((string)($r['CCYDH'] ?? ''));
  3311. if ($ccydh === null) {
  3312. $ccydh = $dh;
  3313. } elseif ($dh !== $ccydh) {
  3314. $this->error('合并审核要求所选行的订单号一致');
  3315. }
  3316. }
  3317. $ids = [];
  3318. foreach ($out as $r) {
  3319. $id = $this->extractScydgyRowId($r);
  3320. if ($this->isValidScydgyRowId($id)) {
  3321. $ids[$id] = true;
  3322. }
  3323. }
  3324. $poBySid = [];
  3325. $detCntBySid = [];
  3326. if ($ids !== []) {
  3327. $idList = array_keys($ids);
  3328. try {
  3329. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3330. if (is_array($poList)) {
  3331. foreach ($poList as $po) {
  3332. if (!is_array($po)) {
  3333. continue;
  3334. }
  3335. $sid = (int)($po['scydgy_id'] ?? 0);
  3336. if ($this->isValidScydgyRowId($sid)) {
  3337. $poBySid[$sid] = $po;
  3338. }
  3339. }
  3340. }
  3341. } catch (\Throwable $e) {
  3342. }
  3343. try {
  3344. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  3345. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  3346. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  3347. if (is_array($detRows)) {
  3348. foreach ($detRows as $dr) {
  3349. if (!is_array($dr)) {
  3350. continue;
  3351. }
  3352. $sid = (int)($dr['scydgy_id'] ?? 0);
  3353. if ($this->isValidScydgyRowId($sid)) {
  3354. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3355. }
  3356. }
  3357. }
  3358. } catch (\Throwable $e) {
  3359. }
  3360. }
  3361. foreach ($out as $r) {
  3362. $id = $this->extractScydgyRowId($r);
  3363. if (!$this->isValidScydgyRowId($id)) {
  3364. continue;
  3365. }
  3366. $po = $poBySid[$id] ?? null;
  3367. if (!is_array($po)) {
  3368. continue;
  3369. }
  3370. $wf = (int)($po['wflow_status'] ?? 0);
  3371. $st = $po['status'] ?? null;
  3372. if ($wf >= 1 || $st === 1 || $st === '1') {
  3373. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3374. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3375. }
  3376. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3377. if ($detCnt > 0 && $wf < 1) {
  3378. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3379. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  3380. }
  3381. }
  3382. return $out;
  3383. }
  3384. /**
  3385. * 规范化下发/确认时勾选的供应商
  3386. *
  3387. * @param array<int, mixed> $companies
  3388. * @return array<int, array<string, string>>
  3389. */
  3390. protected function normalizePickCompanies(array $companies): array
  3391. {
  3392. $out = [];
  3393. foreach ($companies as $c) {
  3394. if (!is_array($c)) {
  3395. continue;
  3396. }
  3397. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  3398. if ($name === '') {
  3399. continue;
  3400. }
  3401. $out[] = [
  3402. 'name' => $name,
  3403. 'company_name' => $name,
  3404. 'username' => trim((string)($c['username'] ?? '')),
  3405. 'email' => trim((string)($c['email'] ?? '')),
  3406. 'phone' => trim((string)($c['phone'] ?? '')),
  3407. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  3408. ];
  3409. }
  3410. return $out;
  3411. }
  3412. /**
  3413. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  3414. *
  3415. * @param array<int, array<string, mixed>> $pool
  3416. * @return array<int, array<string, mixed>>
  3417. */
  3418. protected function collapseProcuremenPoolByOrder(array $pool): array
  3419. {
  3420. if ($pool === []) {
  3421. return [];
  3422. }
  3423. $groups = [];
  3424. foreach ($pool as $row) {
  3425. if (!is_array($row)) {
  3426. continue;
  3427. }
  3428. $dh = trim((string)($row['CCYDH'] ?? ''));
  3429. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  3430. if (!isset($groups[$key])) {
  3431. $groups[$key] = [];
  3432. }
  3433. $groups[$key][] = $row;
  3434. }
  3435. $out = [];
  3436. foreach ($groups as $ccydh => $rows) {
  3437. if ($rows === []) {
  3438. continue;
  3439. }
  3440. usort($rows, function ($a, $b) {
  3441. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  3442. });
  3443. $head = $rows[0];
  3444. $gymcList = [];
  3445. foreach ($rows as $r) {
  3446. $g = trim((string)($r['CGYMC'] ?? ''));
  3447. if ($g !== '' && !in_array($g, $gymcList, true)) {
  3448. $gymcList[] = $g;
  3449. }
  3450. }
  3451. $merged = $head;
  3452. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  3453. $merged['process_count'] = count($rows);
  3454. $merged['_order_merge_rows'] = $rows;
  3455. if (count($rows) > 1) {
  3456. $merged['CGYMC'] = implode('、', $gymcList);
  3457. }
  3458. $mergedPickTime = '';
  3459. foreach ($rows as $r) {
  3460. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  3461. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  3462. $mergedPickTime = $t;
  3463. }
  3464. }
  3465. if ($mergedPickTime !== '') {
  3466. $merged['pick_time'] = $mergedPickTime;
  3467. }
  3468. $out[] = $merged;
  3469. }
  3470. usort($out, function ($a, $b) {
  3471. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  3472. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  3473. if ($ta === $tb) {
  3474. $ida = (int)($a['purchase_order_id'] ?? 0);
  3475. $idb = (int)($b['purchase_order_id'] ?? 0);
  3476. if ($ida !== $idb) {
  3477. return $idb <=> $ida;
  3478. }
  3479. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  3480. }
  3481. if ($ta === '') {
  3482. return 1;
  3483. }
  3484. if ($tb === '') {
  3485. return -1;
  3486. }
  3487. return strcmp($tb, $ta);
  3488. });
  3489. return $out;
  3490. }
  3491. /**
  3492. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  3493. *
  3494. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3495. */
  3496. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  3497. {
  3498. $scydgyId = trim($scydgyId);
  3499. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3500. if ($scydgyId === '') {
  3501. return $empty;
  3502. }
  3503. try {
  3504. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3505. } catch (\Throwable $e) {
  3506. $anchor = null;
  3507. }
  3508. if (!is_array($anchor) || (int)($anchor['wflow_status'] ?? 0) !== 1) {
  3509. return $empty;
  3510. }
  3511. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3512. if ($ccydh === '') {
  3513. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  3514. }
  3515. try {
  3516. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('wflow_status', 1)->order('scydgy_id', 'asc')->select();
  3517. } catch (\Throwable $e) {
  3518. $pos = [$anchor];
  3519. }
  3520. if (!is_array($pos) || $pos === []) {
  3521. $pos = [$anchor];
  3522. }
  3523. return [
  3524. 'ccydh' => $ccydh,
  3525. 'pos' => $pos,
  3526. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3527. ];
  3528. }
  3529. /**
  3530. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  3531. */
  3532. protected function purchaseOrderRowInConfirmStage(array $po): bool
  3533. {
  3534. $st = $po['status'] ?? null;
  3535. if ($st === 1 || $st === '1') {
  3536. return false;
  3537. }
  3538. $wf = (int)($po['wflow_status'] ?? 0);
  3539. if ($wf === 2) {
  3540. return true;
  3541. }
  3542. if ($wf === 0) {
  3543. $sid = (int)($po['scydgy_id'] ?? 0);
  3544. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  3545. }
  3546. return false;
  3547. }
  3548. /**
  3549. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  3550. *
  3551. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3552. */
  3553. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  3554. {
  3555. $scydgyId = trim($scydgyId);
  3556. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3557. if ($scydgyId === '') {
  3558. return $empty;
  3559. }
  3560. try {
  3561. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3562. } catch (\Throwable $e) {
  3563. $anchor = null;
  3564. }
  3565. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  3566. return $empty;
  3567. }
  3568. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3569. if ($ccydh === '') {
  3570. return [
  3571. 'ccydh' => '',
  3572. 'pos' => [$anchor],
  3573. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  3574. ];
  3575. }
  3576. try {
  3577. $pos = Db::table('purchase_order')
  3578. ->where('CCYDH', $ccydh)
  3579. ->where('status', 0)
  3580. ->where(function ($q) {
  3581. $q->where('wflow_status', 2)
  3582. ->whereOr(function ($q2) {
  3583. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  3584. });
  3585. })
  3586. ->order('scydgy_id', 'asc')
  3587. ->select();
  3588. } catch (\Throwable $e) {
  3589. $pos = [$anchor];
  3590. }
  3591. if (!is_array($pos) || $pos === []) {
  3592. $pos = [$anchor];
  3593. }
  3594. $pos = array_values(array_filter($pos, function ($po) {
  3595. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  3596. }));
  3597. if ($pos === []) {
  3598. $pos = [$anchor];
  3599. }
  3600. return [
  3601. 'ccydh' => $ccydh,
  3602. 'pos' => $pos,
  3603. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3604. ];
  3605. }
  3606. /**
  3607. * @param array<int, array<string, mixed>> $purchaseOrders
  3608. * @return array<int, array<string, mixed>>
  3609. */
  3610. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  3611. {
  3612. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  3613. $byId = [];
  3614. foreach ($pool as $r) {
  3615. if (!is_array($r)) {
  3616. continue;
  3617. }
  3618. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  3619. if ($this->isValidScydgyRowId($sid)) {
  3620. $byId[$sid] = $r;
  3621. }
  3622. }
  3623. $out = [];
  3624. foreach ($purchaseOrders as $po) {
  3625. if (!is_array($po)) {
  3626. continue;
  3627. }
  3628. $sid = (int)($po['scydgy_id'] ?? 0);
  3629. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  3630. $out[] = $byId[$sid];
  3631. }
  3632. }
  3633. return $out;
  3634. }
  3635. /**
  3636. * 详情 / PDF:同一外发批次下的全部工序行(与确认供应商弹窗一致)
  3637. *
  3638. * @return array<int, array<string, mixed>>
  3639. */
  3640. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  3641. {
  3642. $scydgyId = trim($scydgyId);
  3643. if ($scydgyId === '') {
  3644. return [];
  3645. }
  3646. try {
  3647. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3648. } catch (\Throwable $e) {
  3649. $anchor = null;
  3650. }
  3651. if (!is_array($anchor)) {
  3652. return [];
  3653. }
  3654. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  3655. return [];
  3656. }
  3657. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3658. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  3659. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  3660. try {
  3661. $q = Db::table('purchase_order');
  3662. if ($ccydh !== '') {
  3663. $q->where('CCYDH', $ccydh);
  3664. } else {
  3665. $q->where('scydgy_id', $scydgyId);
  3666. }
  3667. if ($isValidPick) {
  3668. $q->where('pick_time', $pickTime);
  3669. }
  3670. $pos = $q->order('scydgy_id', 'asc')->select();
  3671. } catch (\Throwable $e) {
  3672. $pos = [$anchor];
  3673. }
  3674. if (!is_array($pos) || $pos === []) {
  3675. $pos = [$anchor];
  3676. }
  3677. $pos = array_values(array_filter($pos, function ($po) {
  3678. if (!is_array($po)) {
  3679. return false;
  3680. }
  3681. $mr = $po['mod_rq'] ?? null;
  3682. if ($mr === null || $mr === '') {
  3683. return true;
  3684. }
  3685. $mrs = trim((string)$mr);
  3686. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  3687. }));
  3688. if ($pos === []) {
  3689. $pos = [$anchor];
  3690. }
  3691. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  3692. if ($rows === []) {
  3693. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  3694. }
  3695. return $rows;
  3696. }
  3697. /**
  3698. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  3699. *
  3700. * @param array<int, array<string, mixed>> $mergeRows
  3701. * @return array<int, array<string, mixed>>
  3702. */
  3703. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  3704. {
  3705. $list = array_values($mergeRows);
  3706. $n = count($list);
  3707. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  3708. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  3709. $mergeSame = $n > 1 && $orderKey0 !== '';
  3710. if ($mergeSame) {
  3711. foreach ($list as $rr) {
  3712. if (!is_array($rr)) {
  3713. $mergeSame = false;
  3714. break;
  3715. }
  3716. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  3717. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  3718. $mergeSame = false;
  3719. break;
  3720. }
  3721. }
  3722. }
  3723. $out = [];
  3724. foreach ($list as $idx => $r) {
  3725. if (!is_array($r)) {
  3726. continue;
  3727. }
  3728. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  3729. if (is_scalar($qty)) {
  3730. $qty = trim((string)$qty);
  3731. } else {
  3732. $qty = '';
  3733. }
  3734. if ($qty === '') {
  3735. $gzl = $r['NGZL'] ?? '';
  3736. if (is_scalar($gzl)) {
  3737. $qty = trim((string)$gzl);
  3738. }
  3739. }
  3740. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  3741. $sid = $this->extractScydgyRowId($r);
  3742. $out[] = [
  3743. 'seq' => $idx + 1,
  3744. 'scydgy_id' => $sid,
  3745. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  3746. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  3747. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  3748. 'CDW' => trim((string)($r['CDW'] ?? '')),
  3749. 'NGZL' => $r['NGZL'] ?? '',
  3750. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  3751. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  3752. 'CDF' => trim((string)($r['CDF'] ?? '')),
  3753. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  3754. 'show_order_cells' => !$mergeSame || $idx === 0,
  3755. 'order_rowspan' => $mergeSame ? $n : 1,
  3756. ];
  3757. }
  3758. return $out;
  3759. }
  3760. /**
  3761. * 解析金额/数量(去千分位等非数字字符)
  3762. */
  3763. protected function parseProcuremenMoneyNumber($value): ?float
  3764. {
  3765. if ($value === null || $value === '') {
  3766. return null;
  3767. }
  3768. if (is_numeric($value)) {
  3769. return (float)$value;
  3770. }
  3771. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  3772. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  3773. }
  3774. protected function formatProcuremenMoneyDisplay(?float $amount): string
  3775. {
  3776. if ($amount === null) {
  3777. return '';
  3778. }
  3779. return (string)(int)round($amount);
  3780. }
  3781. /**
  3782. * 列表/详情展示:工作量为 0 时显示空
  3783. */
  3784. protected function formatProcuremenWorkloadDisplay($value): string
  3785. {
  3786. if ($value === null || $value === '') {
  3787. return '';
  3788. }
  3789. $s = trim((string)$value);
  3790. if ($s === '') {
  3791. return '';
  3792. }
  3793. if (is_numeric($s) && (float)$s == 0) {
  3794. return '';
  3795. }
  3796. return $s;
  3797. }
  3798. /**
  3799. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  3800. */
  3801. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  3802. {
  3803. foreach ($details as $d) {
  3804. if (!is_array($d)) {
  3805. continue;
  3806. }
  3807. if (!$this->isPurchaseOrderDetailVoid($d) && (int)($d['status'] ?? 0) === 1) {
  3808. $cn = trim((string)($d['company_name'] ?? ''));
  3809. if ($cn !== '') {
  3810. return $cn;
  3811. }
  3812. }
  3813. }
  3814. return trim((string)($main['pick_company_name'] ?? ''));
  3815. }
  3816. /**
  3817. * 详情报价小计:单价 × 本工序本次数量
  3818. */
  3819. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  3820. {
  3821. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  3822. if ($unit === null) {
  3823. return null;
  3824. }
  3825. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  3826. if ($qty === null || $qty <= 0) {
  3827. return null;
  3828. }
  3829. return $unit * $qty;
  3830. }
  3831. /**
  3832. * 详情页:工序小计 + 供应商分组报价与总计
  3833. *
  3834. * @param array<int, array<string, mixed>> $mergeRows
  3835. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  3836. * @return array{
  3837. * process_rows: array,
  3838. * supplier_groups: array,
  3839. * order_total_text: string,
  3840. * order_total_has: bool,
  3841. * selected_company: string
  3842. * }
  3843. */
  3844. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  3845. {
  3846. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  3847. $qtyBySid = [];
  3848. $gymcBySid = [];
  3849. $orderedSids = [];
  3850. foreach ($mergeRows as $mr) {
  3851. if (!is_array($mr)) {
  3852. continue;
  3853. }
  3854. $sid = $this->extractScydgyRowId($mr);
  3855. if ($sid > 0) {
  3856. $orderedSids[] = $sid;
  3857. }
  3858. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3859. if ($qty === '') {
  3860. $qty = trim((string)($mr['NGZL'] ?? ''));
  3861. }
  3862. $qtyBySid[$sid] = $qty;
  3863. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  3864. }
  3865. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  3866. $detailByCompanySid = [];
  3867. foreach ($details as $d) {
  3868. if (!is_array($d)) {
  3869. continue;
  3870. }
  3871. $cn = trim((string)($d['company_name'] ?? ''));
  3872. $sid = (int)($d['scydgy_id'] ?? 0);
  3873. if ($cn === '' || $sid === 0) {
  3874. continue;
  3875. }
  3876. if (!isset($detailByCompanySid[$cn])) {
  3877. $detailByCompanySid[$cn] = [];
  3878. }
  3879. $detailByCompanySid[$cn][$sid] = $d;
  3880. }
  3881. $supplierGroups = [];
  3882. foreach ($detailByCompanySid as $cn => $bySid) {
  3883. $lines = [];
  3884. $groupTotal = 0.0;
  3885. $groupHas = false;
  3886. $groupVoid = true;
  3887. $usedSids = [];
  3888. $appendLine = function (int $sid, array $d) use (
  3889. &$lines,
  3890. &$groupTotal,
  3891. &$groupHas,
  3892. &$groupVoid,
  3893. $qtyBySid,
  3894. $gymcBySid
  3895. ) {
  3896. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  3897. if (!$isVoid) {
  3898. $groupVoid = false;
  3899. }
  3900. $qtyStr = $qtyBySid[$sid] ?? '';
  3901. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3902. $sub = null;
  3903. if (!$isVoid && $amountNum !== null) {
  3904. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  3905. if ($sub !== null) {
  3906. $groupTotal += $sub;
  3907. $groupHas = true;
  3908. }
  3909. }
  3910. $ct = $d['createtime_text'] ?? '';
  3911. if ($ct === '' && isset($d['createtime'])) {
  3912. $ct = $this->formatProcuremenDetailTime($d['createtime'] ?? null);
  3913. }
  3914. $lines[] = [
  3915. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  3916. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : trim((string)($d['amount'] ?? '')),
  3917. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  3918. 'delivery_ymd' => $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null),
  3919. 'status' => (int)($d['status'] ?? 0),
  3920. 'is_void' => $isVoid,
  3921. 'createtime_text' => $ct,
  3922. ];
  3923. };
  3924. foreach ($orderedSids as $sid) {
  3925. if (!isset($bySid[$sid])) {
  3926. continue;
  3927. }
  3928. $usedSids[$sid] = true;
  3929. $appendLine($sid, $bySid[$sid]);
  3930. }
  3931. foreach ($bySid as $sid => $d) {
  3932. if (isset($usedSids[$sid])) {
  3933. continue;
  3934. }
  3935. $appendLine((int)$sid, $d);
  3936. }
  3937. $supplierGroups[] = [
  3938. 'company_name' => $cn,
  3939. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  3940. 'is_void' => $groupVoid,
  3941. 'lines' => $lines,
  3942. 'line_count' => count($lines),
  3943. 'total_text' => $groupHas ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  3944. 'has_total' => $groupHas,
  3945. ];
  3946. }
  3947. usort($supplierGroups, function ($a, $b) {
  3948. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  3949. return ($a['is_void'] ?? false) ? 1 : -1;
  3950. }
  3951. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  3952. return ($a['is_selected'] ?? false) ? -1 : 1;
  3953. }
  3954. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  3955. });
  3956. return [
  3957. 'process_rows' => $processRows,
  3958. 'supplier_groups' => $supplierGroups,
  3959. 'order_total_text' => '',
  3960. 'order_total_has' => false,
  3961. 'selected_company' => $selectedCompany,
  3962. ];
  3963. }
  3964. /**
  3965. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  3966. */
  3967. protected function buildProcessLinesPlain(array $mergeRows): string
  3968. {
  3969. $lines = [];
  3970. $i = 1;
  3971. foreach ($mergeRows as $r) {
  3972. if (!is_array($r)) {
  3973. continue;
  3974. }
  3975. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3976. $dw = trim((string)($r['CDW'] ?? ''));
  3977. $gzl = trim((string)($r['NGZL'] ?? ''));
  3978. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  3979. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  3980. if ($dw !== '') {
  3981. $parts[] = '单位:' . $dw;
  3982. }
  3983. if ($gzl !== '') {
  3984. $parts[] = '工作量:' . $gzl;
  3985. }
  3986. if ($qty !== '') {
  3987. $parts[] = '本次数量:' . $qty;
  3988. }
  3989. $lines[] = implode(' ', $parts);
  3990. $i++;
  3991. }
  3992. return implode("\n", $lines);
  3993. }
  3994. /**
  3995. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  3996. *
  3997. * @return array<string, string>
  3998. */
  3999. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
  4000. {
  4001. $po = null;
  4002. try {
  4003. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4004. } catch (\Throwable $e) {
  4005. $po = null;
  4006. }
  4007. $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
  4008. $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
  4009. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
  4010. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4011. if (is_array($any)) {
  4012. if ($ccydh === '') {
  4013. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4014. }
  4015. if ($cyjmc === '') {
  4016. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4017. }
  4018. }
  4019. }
  4020. $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
  4021. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4022. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4023. return [
  4024. 'ccydh' => $ccydh,
  4025. 'cyjmc' => $cyjmc,
  4026. 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
  4027. 'process_lines' => $processLines,
  4028. 'process_lines_html' => '',
  4029. ];
  4030. }
  4031. /**
  4032. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4033. */
  4034. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4035. {
  4036. $lines = [];
  4037. if ($ccydh !== '') {
  4038. $lines[] = '订单号:' . $ccydh;
  4039. }
  4040. if ($cyjmc !== '') {
  4041. $lines[] = '印件名称:' . $cyjmc;
  4042. }
  4043. if ($processPlain !== '') {
  4044. $lines[] = $processPlain;
  4045. }
  4046. return implode("\n", $lines);
  4047. }
  4048. /**
  4049. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4050. *
  4051. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4052. */
  4053. protected function buildPlatformLinksPlain(array $detailLinks): string
  4054. {
  4055. $lines = [];
  4056. $i = 1;
  4057. foreach ($detailLinks as $lk) {
  4058. if (!is_array($lk)) {
  4059. continue;
  4060. }
  4061. $url = trim((string)($lk['url'] ?? ''));
  4062. if ($url === '') {
  4063. continue;
  4064. }
  4065. $label = trim((string)($lk['cgymc'] ?? ''));
  4066. if ($label === '') {
  4067. $label = '工序' . $i;
  4068. }
  4069. $lines[] = $label . ':' . $url;
  4070. $i++;
  4071. }
  4072. return implode("\n", $lines);
  4073. }
  4074. /**
  4075. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4076. *
  4077. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4078. */
  4079. protected function buildPlatformLinksHtml(array $detailLinks): string
  4080. {
  4081. $parts = [];
  4082. $i = 1;
  4083. foreach ($detailLinks as $lk) {
  4084. if (!is_array($lk)) {
  4085. continue;
  4086. }
  4087. $url = trim((string)($lk['url'] ?? ''));
  4088. if ($url === '') {
  4089. continue;
  4090. }
  4091. $label = trim((string)($lk['cgymc'] ?? ''));
  4092. if ($label === '') {
  4093. $label = '工序' . $i;
  4094. }
  4095. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4096. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4097. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4098. $i++;
  4099. }
  4100. return implode("<br>\n", $parts);
  4101. }
  4102. /**
  4103. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4104. *
  4105. * @return array<string, mixed>
  4106. */
  4107. protected function loadMailerConfig(): array
  4108. {
  4109. try {
  4110. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4111. } catch (\Throwable $e) {
  4112. $cfg = [];
  4113. }
  4114. return is_array($cfg) ? $cfg : [];
  4115. }
  4116. protected function loadNotifyTemplateRow(string $scene): ?array
  4117. {
  4118. try {
  4119. $row = Db::table('purchase_sms_template')
  4120. ->where('scene', $scene)
  4121. ->where(function ($q) {
  4122. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4123. })
  4124. ->order('id', 'asc')
  4125. ->find();
  4126. } catch (\Throwable $e) {
  4127. return null;
  4128. }
  4129. if (!is_array($row) || $row === []) {
  4130. return null;
  4131. }
  4132. return [
  4133. 'title' => trim((string)($row['title'] ?? '')),
  4134. 'content' => trim((string)($row['content'] ?? '')),
  4135. ];
  4136. }
  4137. /**
  4138. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4139. */
  4140. protected function buildProcessLinesHtml(array $mergeRows): string
  4141. {
  4142. if (count($mergeRows) <= 1) {
  4143. $r = $mergeRows[0] ?? [];
  4144. if (!is_array($r)) {
  4145. return '';
  4146. }
  4147. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4148. $dw = trim((string)($r['CDW'] ?? ''));
  4149. $gzl = trim((string)($r['NGZL'] ?? ''));
  4150. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4151. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4152. if ($dw !== '') {
  4153. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4154. }
  4155. if ($gzl !== '') {
  4156. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4157. }
  4158. if ($qty !== '') {
  4159. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4160. }
  4161. return $html;
  4162. }
  4163. $rows = '';
  4164. $i = 1;
  4165. foreach ($mergeRows as $r) {
  4166. if (!is_array($r)) {
  4167. continue;
  4168. }
  4169. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4170. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4171. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4172. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4173. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4174. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4175. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4176. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4177. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4178. $i++;
  4179. }
  4180. if ($rows === '') {
  4181. return '';
  4182. }
  4183. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4184. . '<thead><tr style="background:#f5f5f5;">'
  4185. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4186. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4187. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4188. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4189. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4190. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4191. }
  4192. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4193. {
  4194. $sysRq = trim($sysRq);
  4195. if ($sysRq === '') {
  4196. if ($required) {
  4197. $this->error('请选择截止时间');
  4198. }
  4199. return '';
  4200. }
  4201. $ts = strtotime($sysRq);
  4202. if ($ts === false || $ts <= 0) {
  4203. $this->error('截止时间格式无效');
  4204. }
  4205. return date('Y-m-d H:i:s', $ts);
  4206. }
  4207. protected function formatProcuremenSysRqForInput($sysRq): string
  4208. {
  4209. $sr = trim((string)$sysRq);
  4210. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4211. return '';
  4212. }
  4213. $ts = strtotime($sr);
  4214. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4215. }
  4216. /**
  4217. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4218. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4219. */
  4220. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4221. {
  4222. $sysRqPost = trim($sysRqPost);
  4223. if ($sysRqPost === '') {
  4224. return $bundle;
  4225. }
  4226. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4227. $pos = $bundle['pos'] ?? [];
  4228. foreach ($pos as $poRow) {
  4229. if (!is_array($poRow)) {
  4230. continue;
  4231. }
  4232. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4233. if (!$this->isValidScydgyRowId($sid)) {
  4234. continue;
  4235. }
  4236. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4237. }
  4238. foreach ($pos as $i => $poRow) {
  4239. if (is_array($pos[$i])) {
  4240. $pos[$i]['sys_rq'] = $sysRqDb;
  4241. }
  4242. }
  4243. $bundle['pos'] = $pos;
  4244. return $bundle;
  4245. }
  4246. /**
  4247. * 写入/更新 purchase_order(单道工序行)
  4248. */
  4249. protected function upsertPurchaseOrderFromRow(
  4250. array $row,
  4251. string $sysRqDb,
  4252. ?int $wflowStatus = null,
  4253. ?string $pickTime = null,
  4254. ?array $exists = null
  4255. ): void {
  4256. $ids = $this->extractScydgyRowId($row);
  4257. if (!$this->isValidScydgyRowId($ids)) {
  4258. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4259. }
  4260. if ($exists === null) {
  4261. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4262. }
  4263. $data = [
  4264. 'scydgy_id' => $ids,
  4265. 'CCYDH' => $row['CCYDH'] ?? null,
  4266. 'CYJMC' => $row['CYJMC'] ?? null,
  4267. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4268. 'CDXMC' => $row['CDXMC'] ?? null,
  4269. 'CGYBH' => $row['CGYBH'] ?? null,
  4270. 'CGYMC' => $row['CGYMC'] ?? null,
  4271. 'CDW' => $row['CDW'] ?? null,
  4272. 'NGZL' => $row['NGZL'] ?? null,
  4273. 'CDF' => $row['CDF'] ?? null,
  4274. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4275. 'MBZ' => $row['MBZ'] ?? null,
  4276. 'bwjg' => $row['bwjg'] ?? null,
  4277. 'iStatus' => $row['iStatus'] ?? null,
  4278. 'dStamp' => $row['dStamp'] ?? null,
  4279. 'dputrecord' => $row['dputrecord'] ?? null,
  4280. 'cywyxm' => $row['cywyxm'] ?? null,
  4281. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4282. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4283. 'status' => 0,
  4284. 'sys_rq' => $sysRqDb,
  4285. ];
  4286. if ($wflowStatus !== null) {
  4287. $data['wflow_status'] = $wflowStatus;
  4288. }
  4289. if ($pickTime !== null && $pickTime !== '') {
  4290. $data['pick_time'] = $pickTime;
  4291. $data['pick_company_name'] = '';
  4292. }
  4293. if ($exists) {
  4294. $upd = $data;
  4295. unset($upd['scydgy_id']);
  4296. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4297. } else {
  4298. $data['createtime'] = date('Y-m-d H:i:s');
  4299. Db::table('purchase_order')->insert($data);
  4300. }
  4301. }
  4302. /**
  4303. * 外发下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4304. *
  4305. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4306. */
  4307. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4308. {
  4309. $toDb = function ($value) {
  4310. if ($value === null) {
  4311. return null;
  4312. }
  4313. if (is_scalar($value)) {
  4314. return $value;
  4315. }
  4316. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4317. };
  4318. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4319. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4320. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4321. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4322. if ($username === '') {
  4323. $username = $this->resolveCustomerContactName($phone, $companyName);
  4324. }
  4325. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4326. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  4327. }
  4328. if ($phone === '') {
  4329. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  4330. }
  4331. $detailLinks = [];
  4332. foreach ($mergeRows as $row) {
  4333. if (!is_array($row)) {
  4334. continue;
  4335. }
  4336. $sid = $this->extractScydgyRowId($row);
  4337. $detailId = 0;
  4338. if ($skipExisting) {
  4339. try {
  4340. $existsQuery = Db::table('purchase_order_detail')
  4341. ->where('scydgy_id', $sid)
  4342. ->where('company_name', $companyName);
  4343. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  4344. $exists = $existsQuery->find();
  4345. } catch (\Throwable $e) {
  4346. $exists = null;
  4347. }
  4348. if (is_array($exists)) {
  4349. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  4350. }
  4351. }
  4352. if ($detailId <= 0) {
  4353. $one = [
  4354. 'scydgy_id' => $toDb($sid),
  4355. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  4356. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  4357. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  4358. 'username' => $username !== '' ? $username : null,
  4359. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  4360. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  4361. 'createtime' => date('Y-m-d H:i:s'),
  4362. 'status' => 0,
  4363. 'status_name' => '未提交',
  4364. ];
  4365. Db::table('purchase_order_detail')->insert($one);
  4366. $detailId = (int)Db::getLastInsID();
  4367. }
  4368. $mprocUrl = '';
  4369. if ($buildMobileLinks && $detailId > 0) {
  4370. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  4371. }
  4372. $detailLinks[] = [
  4373. 'detail_id' => $detailId,
  4374. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  4375. 'url' => $mprocUrl,
  4376. ];
  4377. }
  4378. return $detailLinks;
  4379. }
  4380. /**
  4381. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  4382. * @return array<string, mixed>
  4383. */
  4384. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  4385. {
  4386. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4387. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4388. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4389. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  4390. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  4391. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  4392. $isMerge = !empty($ctx['is_merge']);
  4393. $contactName = trim((string)($c['username'] ?? ''));
  4394. if ($contactName === '') {
  4395. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  4396. }
  4397. $notifyVars = [
  4398. 'company_name' => $companyName,
  4399. 'contact_name' => $contactName,
  4400. 'phone' => $phone,
  4401. 'email' => $toEmail,
  4402. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  4403. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  4404. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  4405. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  4406. 'deadline' => (string)($ctx['deadline'] ?? ''),
  4407. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  4408. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  4409. 'platform_url' => $platformUrl,
  4410. 'platform_links' => $platformLinksPlain,
  4411. 'platform_links_html' => $platformLinksHtml,
  4412. ];
  4413. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  4414. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  4415. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4416. return [
  4417. 'company_name' => $companyName,
  4418. 'phone' => $phone,
  4419. 'email' => $toEmail,
  4420. 'sms_content' => $smsContent,
  4421. 'mail_plain' => $mailPlain,
  4422. 'mail_body' => $mailBody,
  4423. 'notify_vars' => $notifyVars,
  4424. 'detail_links' => $detailLinks,
  4425. ];
  4426. }
  4427. /**
  4428. * 确认供应商 — 向选定一家发送短信/邮件(第二步)
  4429. *
  4430. * @param array<string, mixed> $chosen
  4431. * @param array<int, array<string, mixed>> $mergeRows
  4432. * @param array{ccydh:string, pos:array} $bundle
  4433. */
  4434. protected function sendAuditSupplierConfirmNotify(array $chosen, array $mergeRows, array $bundle): void
  4435. {
  4436. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, true, true);
  4437. }
  4438. /**
  4439. * @param array<string, mixed> $chosen
  4440. * @param array<int, array<string, mixed>> $mergeRows
  4441. * @param array{ccydh:string, pos:array} $bundle
  4442. */
  4443. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  4444. {
  4445. if (!$sendSms && !$sendEmail) {
  4446. return;
  4447. }
  4448. $companyName = trim((string)($chosen['name'] ?? ''));
  4449. $phone = trim((string)($chosen['phone'] ?? ''));
  4450. $toEmail = trim((string)($chosen['email'] ?? ''));
  4451. if ($companyName === '') {
  4452. throw new \Exception('供应商名称无效');
  4453. }
  4454. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  4455. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  4456. }
  4457. if ($sendSms && $phone === '') {
  4458. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  4459. }
  4460. $sids = [];
  4461. foreach ($mergeRows as $mr) {
  4462. if (!is_array($mr)) {
  4463. continue;
  4464. }
  4465. $sid = $this->extractScydgyRowId($mr);
  4466. if ($this->isValidScydgyRowId($sid)) {
  4467. $sids[$sid] = true;
  4468. }
  4469. }
  4470. if ($sids === []) {
  4471. throw new \Exception('未找到工序行,无法发送通知');
  4472. }
  4473. $sysRqNotify = '';
  4474. $pos = $bundle['pos'] ?? [];
  4475. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  4476. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  4477. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  4478. $ts = strtotime($sr);
  4479. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  4480. }
  4481. }
  4482. try {
  4483. $detailsQuery = Db::table('purchase_order_detail')
  4484. ->where('scydgy_id', 'in', array_keys($sids))
  4485. ->where('company_name', $companyName);
  4486. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4487. $details = $detailsQuery->order('id', 'asc')->select();
  4488. } catch (\Throwable $e) {
  4489. $details = [];
  4490. }
  4491. if (!is_array($details) || $details === []) {
  4492. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  4493. try {
  4494. $detailsQuery = Db::table('purchase_order_detail')
  4495. ->where('scydgy_id', 'in', array_keys($sids))
  4496. ->where('company_name', $companyName);
  4497. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4498. $details = $detailsQuery->order('id', 'asc')->select();
  4499. } catch (\Throwable $e) {
  4500. $details = [];
  4501. }
  4502. }
  4503. if (!is_array($details) || $details === []) {
  4504. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  4505. }
  4506. $detailLinks = [];
  4507. foreach ($details as $d) {
  4508. if (!is_array($d)) {
  4509. continue;
  4510. }
  4511. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4512. if ($detailId <= 0) {
  4513. continue;
  4514. }
  4515. $sid = (int)($d['scydgy_id'] ?? 0);
  4516. $gymc = '';
  4517. foreach ($mergeRows as $mr) {
  4518. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  4519. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  4520. break;
  4521. }
  4522. }
  4523. $detailLinks[] = [
  4524. 'detail_id' => $detailId,
  4525. 'cgymc' => $gymc,
  4526. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  4527. ];
  4528. }
  4529. if ($detailLinks === []) {
  4530. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  4531. }
  4532. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  4533. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  4534. if ($sendEmail) {
  4535. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  4536. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  4537. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  4538. }
  4539. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  4540. $mailConfig = $this->loadMailerConfig();
  4541. if (!$this->isProcuremenNotifyDryRun()) {
  4542. if (empty($mailConfig['host'])) {
  4543. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  4544. }
  4545. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  4546. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  4547. }
  4548. }
  4549. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  4550. }
  4551. if ($sendSms) {
  4552. $this->issueSendSupplierSms($notifyBundle);
  4553. }
  4554. }
  4555. /**
  4556. * @param array<int, array<string, mixed>> $quoteGroups
  4557. * @return array<int, array<string, mixed>>
  4558. */
  4559. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  4560. {
  4561. $names = [];
  4562. if (is_string($companiesJson) && $companiesJson !== '') {
  4563. $decoded = json_decode($companiesJson, true);
  4564. if (is_array($decoded)) {
  4565. foreach ($decoded as $nm) {
  4566. $nm = trim((string)$nm);
  4567. if ($nm !== '') {
  4568. $names[] = $nm;
  4569. }
  4570. }
  4571. }
  4572. }
  4573. $names = array_values(array_unique($names));
  4574. if ($names === [] && $selectedCompany !== '') {
  4575. $names = [$selectedCompany];
  4576. }
  4577. if ($names === []) {
  4578. return $quoteGroups;
  4579. }
  4580. $targets = [];
  4581. foreach ($quoteGroups as $g) {
  4582. if (!is_array($g)) {
  4583. continue;
  4584. }
  4585. $cn = trim((string)($g['name'] ?? ''));
  4586. if ($cn !== '' && in_array($cn, $names, true)) {
  4587. $targets[] = $g;
  4588. }
  4589. }
  4590. return $targets;
  4591. }
  4592. /**
  4593. * @return array{pos:array, merge_rows:array, bundle:array}
  4594. */
  4595. protected function loadAuditResendBundle(string $scydgyId): array
  4596. {
  4597. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  4598. $pos = $bundle['pos'];
  4599. $mergeRows = $bundle['merge_rows'];
  4600. if ($pos === [] || $mergeRows === []) {
  4601. $this->error('该订单不在待确认供应商状态');
  4602. }
  4603. $sysRqDb = '';
  4604. if (isset($pos[0]) && is_array($pos[0])) {
  4605. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  4606. }
  4607. foreach ($pos as $i => $poRow) {
  4608. if (is_array($pos[$i]) && $sysRqDb !== '') {
  4609. $pos[$i]['sys_rq'] = $sysRqDb;
  4610. }
  4611. }
  4612. $bundle['pos'] = $pos;
  4613. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  4614. }
  4615. /**
  4616. * @param array<int, array<string, mixed>> $targets
  4617. */
  4618. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  4619. {
  4620. if ($targets === []) {
  4621. $this->error('未找到可通知的供应商');
  4622. }
  4623. $notifyErrors = [];
  4624. try {
  4625. $this->notifyDryRunPreview = [];
  4626. foreach ($targets as $g) {
  4627. if (!is_array($g)) {
  4628. continue;
  4629. }
  4630. $cname = trim((string)($g['name'] ?? ''));
  4631. if ($cname === '') {
  4632. continue;
  4633. }
  4634. $chosen = [
  4635. 'name' => $cname,
  4636. 'company_name' => $cname,
  4637. 'email' => trim((string)($g['email'] ?? '')),
  4638. 'phone' => trim((string)($g['phone'] ?? '')),
  4639. 'username' => trim((string)($g['username'] ?? '')),
  4640. ];
  4641. try {
  4642. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  4643. } catch (\Throwable $e) {
  4644. $notifyErrors[] = $cname . ':' . $e->getMessage();
  4645. }
  4646. }
  4647. } catch (\Throwable $e) {
  4648. $this->error('通知发送失败:' . $e->getMessage());
  4649. }
  4650. if ($notifyErrors !== []) {
  4651. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  4652. }
  4653. if ($this->isProcuremenNotifyDryRun()) {
  4654. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  4655. 'notify_dry_run' => true,
  4656. 'notify_preview' => $this->notifyDryRunPreview,
  4657. ]);
  4658. }
  4659. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  4660. }
  4661. /**
  4662. * 外发下发 — 写入下发明细并拼好短信/邮件内容(供第二步发送)
  4663. *
  4664. * @return array<string, mixed>
  4665. */
  4666. protected function issueBuildSupplierNotifyBundle(array $c, array $mergeRows, array $ctx): array
  4667. {
  4668. $detailLinks = $this->issuePersistSupplierDetails($c, $mergeRows);
  4669. return $this->composeSupplierNotifyBundle($c, $ctx, $detailLinks);
  4670. }
  4671. /**
  4672. * 外发下发 — 发送短信(一家供应商)
  4673. *
  4674. * @param array<string, mixed> $bundle issueBuildSupplierNotifyBundle 返回值
  4675. */
  4676. protected function issueSendSupplierSms(array $bundle): void
  4677. {
  4678. $companyName = (string)($bundle['company_name'] ?? '');
  4679. $phone = (string)($bundle['phone'] ?? '');
  4680. $smsContent = (string)($bundle['sms_content'] ?? '');
  4681. $this->logIssueNotifyDebug('短信', [
  4682. 'company' => $companyName,
  4683. 'phone' => $phone,
  4684. 'sms_content' => $smsContent,
  4685. ]);
  4686. if ($this->isProcuremenNotifyDryRun()) {
  4687. $this->recordNotifyDryRunPreview([
  4688. 'scene' => 'issue_sms',
  4689. 'company_name' => $companyName,
  4690. 'phone' => $phone,
  4691. 'sms_content' => $smsContent,
  4692. ]);
  4693. return;
  4694. }
  4695. $this->smsbao($phone, $smsContent);
  4696. }
  4697. /**
  4698. * 外发下发 — 发送邮件(一家供应商)
  4699. *
  4700. * @param array<string, mixed> $bundle
  4701. * @param array<string, mixed> $mailConfig
  4702. */
  4703. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  4704. {
  4705. $companyName = (string)($bundle['company_name'] ?? '');
  4706. $toEmail = (string)($bundle['email'] ?? '');
  4707. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  4708. $mailBody = (string)($bundle['mail_body'] ?? '');
  4709. $this->logIssueNotifyDebug('邮件', [
  4710. 'company' => $companyName,
  4711. 'email' => $toEmail,
  4712. 'mail_subject' => $mailSubject,
  4713. 'mail_body' => $mailPlain,
  4714. ]);
  4715. if ($this->isProcuremenNotifyDryRun()) {
  4716. $this->recordNotifyDryRunPreview([
  4717. 'scene' => 'issue_email',
  4718. 'company_name' => $companyName,
  4719. 'email' => $toEmail,
  4720. 'mail_subject' => $mailSubject,
  4721. 'mail_body' => $mailPlain,
  4722. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  4723. 'notify_vars' => $bundle['notify_vars'] ?? [],
  4724. 'detail_links' => $bundle['detail_links'] ?? [],
  4725. ]);
  4726. return;
  4727. }
  4728. $mail = new PHPMailer(true);
  4729. $mail->isSMTP();
  4730. $mail->Host = $mailConfig['host'];
  4731. $mail->SMTPAuth = true;
  4732. $mail->Username = $mailConfig['addr'];
  4733. $mail->Password = $mailConfig['pass'];
  4734. $mail->SMTPSecure = $mailConfig['security'];
  4735. $mail->Port = $mailConfig['port'];
  4736. $mail->CharSet = $mailConfig['charset'];
  4737. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  4738. $mail->addAddress($toEmail, $companyName);
  4739. $mail->isHTML(true);
  4740. $mail->Subject = $mailSubject;
  4741. $mail->Body = $mailBody;
  4742. $mail->send();
  4743. }
  4744. /**
  4745. * 外发下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  4746. *
  4747. * @param array<int, array<string, mixed>> $mergeRows
  4748. * @return array<string, mixed>
  4749. */
  4750. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  4751. {
  4752. $head = $mergeRows[0] ?? [];
  4753. $isMerge = count($mergeRows) > 1;
  4754. return [
  4755. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  4756. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  4757. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  4758. 'is_merge' => $isMerge,
  4759. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  4760. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  4761. 'deadline' => $sysRqNotify,
  4762. ];
  4763. }
  4764. /**
  4765. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  4766. *
  4767. * @param array<string, mixed> $data
  4768. */
  4769. protected function logIssueNotifyDebug(string $type, array $data): void
  4770. {
  4771. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  4772. return;
  4773. }
  4774. Log::write('[外发下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  4775. }
  4776. /**
  4777. * 外发下发弹窗(选多家供应商并通知)
  4778. */
  4779. public function pickReview()
  4780. {
  4781. if ($this->request->isPost()) {
  4782. $this->error('请使用弹窗内「确认下发」提交');
  4783. }
  4784. $this->view->assign('pickMode', 1);
  4785. return $this->view->fetch('procuremen/review');
  4786. }
  4787. /**
  4788. * 外发新增(独立页面)
  4789. */
  4790. public function add()
  4791. {
  4792. if ($this->request->isPost()) {
  4793. $params = $this->request->post('row/a');
  4794. if (!is_array($params)) {
  4795. $this->error(__('Parameter %s can not be empty', ''));
  4796. }
  4797. [, $adminName] = $this->GetUseName();
  4798. $params['cywyxm'] = $adminName;
  4799. try {
  4800. $sid = $this->saveManualPickOrder($params);
  4801. } catch (\InvalidArgumentException $e) {
  4802. $this->error($e->getMessage());
  4803. } catch (\Throwable $e) {
  4804. $this->error($e->getMessage());
  4805. }
  4806. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  4807. }
  4808. [, $adminName] = $this->GetUseName();
  4809. $this->view->assign('adminNickname', $adminName);
  4810. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  4811. return $this->view->fetch();
  4812. }
  4813. /**
  4814. * 业务员外发新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  4815. */
  4816. public function rfqlist()
  4817. {
  4818. $this->relationSearch = false;
  4819. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  4820. $this->request->filter(['strip_tags', 'trim']);
  4821. if ($this->request->isAjax()) {
  4822. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  4823. $limit = max(10, min(500, (int)$limit));
  4824. $applyFilters = function ($query) use ($where) {
  4825. $query->where('scydgy_id', '<', 0);
  4826. $query->whereRaw(
  4827. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  4828. );
  4829. if (!$this->auth->isSuperAdmin()) {
  4830. [, $adminName] = $this->GetUseName();
  4831. $query->where('cywyxm', $adminName);
  4832. }
  4833. if (!empty($where)) {
  4834. $query->where($where);
  4835. }
  4836. };
  4837. $countQuery = Db::table('purchase_order');
  4838. $applyFilters($countQuery);
  4839. $total = (int)$countQuery->count();
  4840. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  4841. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  4842. $listQuery = Db::table('purchase_order');
  4843. $applyFilters($listQuery);
  4844. $rows = $listQuery
  4845. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  4846. ->order($sortField, $orderDir)
  4847. ->limit($offset, $limit)
  4848. ->select();
  4849. if (!is_array($rows)) {
  4850. $rows = [];
  4851. }
  4852. $out = [];
  4853. foreach ($rows as $r) {
  4854. if (!is_array($r)) {
  4855. continue;
  4856. }
  4857. $sid = (int)($r['scydgy_id'] ?? 0);
  4858. if ($sid >= 0) {
  4859. continue;
  4860. }
  4861. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  4862. if ($createdText === '') {
  4863. $createdText = trim((string)($r['dStamp'] ?? ''));
  4864. }
  4865. $out[] = [
  4866. 'id' => (int)($r['id'] ?? 0),
  4867. 'scydgy_id' => $sid,
  4868. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4869. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4870. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  4871. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4872. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  4873. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  4874. 'createtime' => $r['createtime'] ?? null,
  4875. 'createtime_text' => $createdText,
  4876. ];
  4877. }
  4878. return json(['total' => $total, 'rows' => $out]);
  4879. }
  4880. [, $adminName] = $this->GetUseName();
  4881. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  4882. $this->view->assign('adminNickname', $adminName);
  4883. return $this->view->fetch('procuremen/rfqlist');
  4884. }
  4885. /**
  4886. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  4887. */
  4888. public function rfqlistDetails()
  4889. {
  4890. return $this->details();
  4891. }
  4892. /**
  4893. * 手工新增工序详情:业务员只看本人;超管及外发流程岗位可看全部
  4894. */
  4895. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  4896. {
  4897. if ($scydgyId >= 0) {
  4898. return;
  4899. }
  4900. try {
  4901. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4902. } catch (\Throwable $e) {
  4903. $po = null;
  4904. }
  4905. if (!is_array($po)) {
  4906. $this->error('订单不存在');
  4907. }
  4908. $modRq = trim((string)($po['mod_rq'] ?? ''));
  4909. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  4910. $this->error('订单不存在');
  4911. }
  4912. if ($this->auth->isSuperAdmin()) {
  4913. return;
  4914. }
  4915. [, $adminName] = $this->GetUseName();
  4916. $cywy = trim((string)($po['cywyxm'] ?? ''));
  4917. if ($cywy !== '' && $cywy === $adminName) {
  4918. return;
  4919. }
  4920. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  4921. try {
  4922. if ($this->auth->check($rule)) {
  4923. return;
  4924. }
  4925. } catch (\Throwable $e) {
  4926. }
  4927. }
  4928. $this->error('无权查看该订单');
  4929. }
  4930. /**
  4931. * @deprecated 使用 {@see assertManualOrderDetailsViewable}
  4932. */
  4933. protected function assertRfqRowViewable(int $scydgyId): void
  4934. {
  4935. $this->assertManualOrderDetailsViewable($scydgyId);
  4936. }
  4937. /**
  4938. * 手工新增外发工序进度文案
  4939. */
  4940. protected function formatProcuremenRfqProgressText(array $row): string
  4941. {
  4942. $st = trim((string)($row['status'] ?? ''));
  4943. // status=1 才表示主单已完结;status=0 为流程进行中(与详情 buildProcuremenDetailsViewData 一致)
  4944. if ($st === '1') {
  4945. return '已完结';
  4946. }
  4947. $wf = (int)($row['wflow_status'] ?? 0);
  4948. if ($wf === 2) {
  4949. return '待采购确认';
  4950. }
  4951. if ($wf === 1) {
  4952. return '待确认供应商';
  4953. }
  4954. $sid = (int)($row['scydgy_id'] ?? 0);
  4955. if ($sid < 0) {
  4956. try {
  4957. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  4958. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  4959. $detCnt = (int)$detCntQuery->count();
  4960. if ($detCnt > 0) {
  4961. return '已下发待确认';
  4962. }
  4963. } catch (\Throwable $e) {
  4964. }
  4965. }
  4966. return '待外发下发';
  4967. }
  4968. /**
  4969. * 外发初选列表 — 批量软删除
  4970. */
  4971. public function pickDelete()
  4972. {
  4973. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4974. $this->error(__('Invalid parameters'));
  4975. }
  4976. $rowsRaw = $this->request->post('rows_json', '[]');
  4977. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  4978. if (!is_array($rows) || $rows === []) {
  4979. $this->error('请至少勾选一条工序');
  4980. }
  4981. $done = 0;
  4982. Db::startTrans();
  4983. try {
  4984. foreach ($rows as $row) {
  4985. if (!is_array($row)) {
  4986. continue;
  4987. }
  4988. $this->softDeleteProcuremenPickRow($row);
  4989. $done++;
  4990. }
  4991. if ($done < 1) {
  4992. throw new \Exception('没有可删除的工序');
  4993. }
  4994. Db::commit();
  4995. } catch (\InvalidArgumentException $e) {
  4996. Db::rollback();
  4997. $this->error($e->getMessage());
  4998. } catch (\Throwable $e) {
  4999. Db::rollback();
  5000. $this->error($e->getMessage());
  5001. }
  5002. $this->success('已删除 ' . $done . ' 条工序');
  5003. }
  5004. /**
  5005. * 外发下发 — 手工新增工序(弹窗)
  5006. */
  5007. public function pickAdd()
  5008. {
  5009. if ($this->request->isPost()) {
  5010. $params = $this->request->post('row/a');
  5011. if (!is_array($params)) {
  5012. $this->error(__('Parameter %s can not be empty', ''));
  5013. }
  5014. try {
  5015. $sid = $this->saveManualPickOrder($params);
  5016. } catch (\InvalidArgumentException $e) {
  5017. $this->error($e->getMessage());
  5018. } catch (\Throwable $e) {
  5019. $this->error($e->getMessage());
  5020. }
  5021. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5022. }
  5023. return $this->view->fetch('procuremen/pick_add');
  5024. }
  5025. /**
  5026. * 外发下发提交 — 弹窗「确认下发」→ POST procuremen/picksubmit
  5027. */
  5028. public function pickSubmit()
  5029. {
  5030. if (!$this->request->isPost()) {
  5031. $this->error(__('Invalid parameters'));
  5032. }
  5033. // ---------- 接口订单数据 ----------
  5034. $rowJson = $this->request->post('row_json', '');
  5035. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5036. $companiesJson = $this->request->post('companies_json', '[]');
  5037. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5038. $companies = json_decode($companiesJson, true);
  5039. if (!is_array($companies)) {
  5040. $this->error('供应商数据无效');
  5041. }
  5042. $issueCompanies = $this->normalizePickCompanies($companies);
  5043. if ($issueCompanies === []) {
  5044. $this->error('请至少选择一家合作供应商');
  5045. }
  5046. $issueNameLabels = [];
  5047. foreach ($issueCompanies as $pc) {
  5048. $issueNameLabels[] = $pc['name'];
  5049. }
  5050. $issueNamesSummary = implode('、', $issueNameLabels);
  5051. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5052. if ($sysRq === '') {
  5053. $this->error('请选择截止时间');
  5054. }
  5055. $sysRqTs = strtotime($sysRq);
  5056. if ($sysRqTs === false || $sysRqTs <= 0) {
  5057. $this->error('截止时间格式无效');
  5058. }
  5059. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5060. $isMerge = count($mergeRows) > 1;
  5061. $logMsg = ($isMerge ? '合并外发初选(' . count($mergeRows) . ' 道工序)' : '外发初选')
  5062. . ',通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5063. $issueTime = date('Y-m-d H:i:s');
  5064. $logSidList = [];
  5065. foreach ($mergeRows as $row) {
  5066. if (!is_array($row)) {
  5067. continue;
  5068. }
  5069. $sid = $this->extractScydgyRowId($row);
  5070. if ($this->isValidScydgyRowId($sid)) {
  5071. $logSidList[$sid] = true;
  5072. }
  5073. }
  5074. $existingBySid = [];
  5075. if ($logSidList !== []) {
  5076. try {
  5077. $existingRows = Db::table('purchase_order')
  5078. ->where('scydgy_id', 'in', array_keys($logSidList))
  5079. ->select();
  5080. if (is_array($existingRows)) {
  5081. foreach ($existingRows as $poRow) {
  5082. if (!is_array($poRow)) {
  5083. continue;
  5084. }
  5085. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5086. if ($this->isValidScydgyRowId($sid)) {
  5087. $existingBySid[$sid] = $poRow;
  5088. }
  5089. }
  5090. }
  5091. } catch (\Throwable $e) {
  5092. $existingBySid = [];
  5093. }
  5094. }
  5095. Db::startTrans();
  5096. try {
  5097. // ---------- 主表 wflow_status=1;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5098. foreach ($mergeRows as $row) {
  5099. if (!is_array($row)) {
  5100. continue;
  5101. }
  5102. $sid = $this->extractScydgyRowId($row);
  5103. $this->upsertPurchaseOrderFromRow(
  5104. $row,
  5105. $sysRqDb,
  5106. 1,
  5107. $issueTime,
  5108. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5109. );
  5110. }
  5111. foreach ($issueCompanies as $c) {
  5112. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5113. }
  5114. Db::commit();
  5115. } catch (\Throwable $e) {
  5116. Db::rollback();
  5117. $this->error($e->getMessage());
  5118. }
  5119. $poIdBySid = [];
  5120. if ($logSidList !== []) {
  5121. try {
  5122. $poIdBySid = Db::table('purchase_order')
  5123. ->where('scydgy_id', 'in', array_keys($logSidList))
  5124. ->column('id', 'scydgy_id');
  5125. } catch (\Throwable $e) {
  5126. $poIdBySid = [];
  5127. }
  5128. }
  5129. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5130. if ($logSidList !== []) {
  5131. list($adminId, $adminName) = $this->GetUseName();
  5132. $cut = function ($s, $max) {
  5133. if (function_exists('mb_substr')) {
  5134. return mb_substr($s, 0, $max, 'UTF-8');
  5135. }
  5136. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5137. };
  5138. $logRows = [];
  5139. $seenLogSid = [];
  5140. foreach ($mergeRows as $row) {
  5141. if (!is_array($row)) {
  5142. continue;
  5143. }
  5144. $ids = $this->extractScydgyRowId($row);
  5145. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5146. continue;
  5147. }
  5148. $seenLogSid[$ids] = true;
  5149. $poIdLog = null;
  5150. if (isset($poIdBySid[$ids])) {
  5151. $tid = (int)$poIdBySid[$ids];
  5152. $poIdLog = $tid > 0 ? $tid : null;
  5153. }
  5154. $logRows[] = [
  5155. 'scydgy_id' => $ids,
  5156. 'purchase_order_id' => $poIdLog,
  5157. 'admin_id' => $adminId,
  5158. 'admin_name' => $cut($adminName, 64),
  5159. 'action' => $cut('issue_submit', 64),
  5160. 'content' => $cut($logMsg, 1000),
  5161. 'createtime' => time(),
  5162. ];
  5163. }
  5164. if ($logRows !== []) {
  5165. try {
  5166. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5167. } catch (\Throwable $e) {
  5168. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5169. }
  5170. }
  5171. }
  5172. $notifyErrors = [];
  5173. $posNotify = [];
  5174. if ($logSidList !== []) {
  5175. try {
  5176. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5177. } catch (\Throwable $e) {
  5178. $posNotify = [];
  5179. }
  5180. }
  5181. if (!is_array($posNotify)) {
  5182. $posNotify = [];
  5183. }
  5184. foreach ($posNotify as $i => $prow) {
  5185. if (is_array($posNotify[$i])) {
  5186. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5187. }
  5188. }
  5189. $ccydhPick = '';
  5190. foreach ($mergeRows as $row) {
  5191. if (!is_array($row)) {
  5192. continue;
  5193. }
  5194. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5195. if ($ccydhPick !== '') {
  5196. break;
  5197. }
  5198. }
  5199. $notifyBundleBase = [
  5200. 'ccydh' => $ccydhPick,
  5201. 'pos' => $posNotify,
  5202. 'merge_rows' => $mergeRows,
  5203. ];
  5204. try {
  5205. $this->notifyDryRunPreview = [];
  5206. foreach ($issueCompanies as $c) {
  5207. if (!is_array($c)) {
  5208. continue;
  5209. }
  5210. $cname = trim((string)($c['name'] ?? ''));
  5211. if ($cname === '') {
  5212. continue;
  5213. }
  5214. try {
  5215. $this->sendAuditSupplierConfirmNotify($c, $mergeRows, $notifyBundleBase);
  5216. } catch (\Throwable $e) {
  5217. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5218. }
  5219. }
  5220. } catch (\Throwable $e) {
  5221. $this->error('通知发送失败:' . $e->getMessage());
  5222. }
  5223. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5224. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5225. }
  5226. if ($this->isProcuremenNotifyDryRun()) {
  5227. $this->success('【演练模式】已保存并生成通知预览', '', [
  5228. 'notify_dry_run' => true,
  5229. 'notify_preview' => $this->notifyDryRunPreview,
  5230. ]);
  5231. }
  5232. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「外发审批下发」确认供应商');
  5233. }
  5234. /**
  5235. * 确认供应商弹窗
  5236. */
  5237. public function auditIssue()
  5238. {
  5239. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5240. if (is_array($ids)) {
  5241. $ids = isset($ids[0]) ? $ids[0] : '';
  5242. }
  5243. $ids = trim((string)$ids);
  5244. if ($ids === '') {
  5245. $this->error(__('Invalid parameters'));
  5246. }
  5247. if ($this->request->isPost()) {
  5248. $this->error('请使用弹窗内「确认」提交');
  5249. }
  5250. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5251. $pos = $bundle['pos'];
  5252. if ($pos === []) {
  5253. $this->error('该订单不在待确认供应商状态');
  5254. }
  5255. $po = $pos[0];
  5256. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5257. if ($quoteGroups === []) {
  5258. $this->error('暂无下发明细,请确认该订单已在「外发初选」完成下发');
  5259. }
  5260. $pickedName = '';
  5261. foreach ($pos as $poRow) {
  5262. if (!is_array($poRow)) {
  5263. continue;
  5264. }
  5265. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5266. if ($pn !== '') {
  5267. $pickedName = $pn;
  5268. break;
  5269. }
  5270. }
  5271. $this->view->assign('po', $po);
  5272. $this->view->assign('scydgyId', $ids);
  5273. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5274. $mergeRows = $bundle['merge_rows'];
  5275. $this->view->assign('processRows', $mergeRows);
  5276. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5277. $this->view->assign('processCount', count($mergeRows));
  5278. $this->view->assign('quoteGroups', $quoteGroups);
  5279. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5280. $this->view->assign('pickedCompanyName', $pickedName);
  5281. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5282. return $this->view->fetch('procuremen/audit_issue');
  5283. }
  5284. /**
  5285. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5286. */
  5287. public function auditSubmit()
  5288. {
  5289. if (!$this->request->isPost()) {
  5290. $this->error(__('Invalid parameters'));
  5291. }
  5292. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5293. if ($scydgyId === '') {
  5294. $this->error('参数无效');
  5295. }
  5296. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5297. $pos = $bundle['pos'];
  5298. $mergeRows = $bundle['merge_rows'];
  5299. if ($pos === [] || $mergeRows === []) {
  5300. $this->error('该订单不在待确认供应商状态');
  5301. }
  5302. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5303. if ($quoteGroups === []) {
  5304. $this->error('暂无供应商报价,请确认已完成外发初选通知');
  5305. }
  5306. $companyName = trim((string)$this->request->post('selected_company', ''));
  5307. if ($companyName === '') {
  5308. $this->error('请选择一家供应商');
  5309. }
  5310. $matched = null;
  5311. foreach ($quoteGroups as $g) {
  5312. if (!is_array($g)) {
  5313. continue;
  5314. }
  5315. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5316. $matched = $g;
  5317. break;
  5318. }
  5319. }
  5320. if ($matched === null) {
  5321. $this->error('所选供应商不在本单报价列表中');
  5322. }
  5323. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5324. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5325. $procCnt = count($mergeRows);
  5326. $logMsg = '确认供应商(订单' . ($ccydhLog !== '' ? $ccydhLog : '')
  5327. . ($procCnt > 1 ? ',' . $procCnt . ' 道工序' : '')
  5328. . '),选定:' . $companyName;
  5329. Db::startTrans();
  5330. try {
  5331. foreach ($pos as $poRow) {
  5332. if (!is_array($poRow)) {
  5333. continue;
  5334. }
  5335. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5336. if (!$this->isValidScydgyRowId($sid)) {
  5337. continue;
  5338. }
  5339. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5340. 'wflow_status' => 2,
  5341. 'status' => 0,
  5342. 'pick_company_name' => $companyName,
  5343. 'sys_rq' => $sysRqDb,
  5344. ]);
  5345. }
  5346. Db::commit();
  5347. } catch (\Throwable $e) {
  5348. Db::rollback();
  5349. $this->error($e->getMessage());
  5350. }
  5351. foreach ($pos as $poRow) {
  5352. if (!is_array($poRow)) {
  5353. continue;
  5354. }
  5355. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5356. if (!$this->isValidScydgyRowId($sid)) {
  5357. continue;
  5358. }
  5359. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  5360. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  5361. }
  5362. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  5363. }
  5364. /**
  5365. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  5366. */
  5367. public function auditResendSms()
  5368. {
  5369. if (!$this->request->isPost()) {
  5370. $this->error(__('Invalid parameters'));
  5371. }
  5372. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5373. if ($scydgyId === '') {
  5374. $this->error('参数无效');
  5375. }
  5376. $loaded = $this->loadAuditResendBundle($scydgyId);
  5377. $mergeRows = $loaded['merge_rows'];
  5378. $bundle = $loaded['bundle'];
  5379. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5380. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5381. if ($quoteGroups === []) {
  5382. $this->error('暂无可通知的供应商');
  5383. }
  5384. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5385. $companiesJson = (string)$this->request->post('companies_json', '');
  5386. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5387. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  5388. }
  5389. /**
  5390. * 确认供应商 — 二次发送邮件(可选单家/批量)
  5391. */
  5392. public function auditResendEmail()
  5393. {
  5394. if (!$this->request->isPost()) {
  5395. $this->error(__('Invalid parameters'));
  5396. }
  5397. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5398. if ($scydgyId === '') {
  5399. $this->error('参数无效');
  5400. }
  5401. $loaded = $this->loadAuditResendBundle($scydgyId);
  5402. $mergeRows = $loaded['merge_rows'];
  5403. $bundle = $loaded['bundle'];
  5404. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5405. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5406. if ($quoteGroups === []) {
  5407. $this->error('暂无可通知的供应商');
  5408. }
  5409. $companiesJson = (string)$this->request->post('companies_json', '');
  5410. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5411. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5412. if ($companiesJson === '' && $selectedCompany === '') {
  5413. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  5414. }
  5415. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  5416. }
  5417. /**
  5418. * 废弃单个订单 bundle(退回外发初选,明细归档留痕)
  5419. *
  5420. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5421. * @return array<int, true> 已处理的 scydgy_id 集合
  5422. */
  5423. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回外发初选'): array
  5424. {
  5425. $pos = $bundle['pos'] ?? [];
  5426. if (!is_array($pos) || $pos === []) {
  5427. return [];
  5428. }
  5429. $sids = [];
  5430. foreach ($pos as $poRow) {
  5431. if (!is_array($poRow)) {
  5432. continue;
  5433. }
  5434. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5435. if ($this->isValidScydgyRowId($sid)) {
  5436. $sids[$sid] = true;
  5437. }
  5438. }
  5439. if ($sids === []) {
  5440. return [];
  5441. }
  5442. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5443. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '') . $logSuffix;
  5444. Db::table('purchase_order')
  5445. ->where('scydgy_id', 'in', array_keys($sids))
  5446. ->update([
  5447. 'wflow_status' => 0,
  5448. 'status' => 0,
  5449. 'pick_company_name' => '',
  5450. 'pick_time' => null,
  5451. 'sys_rq' => null,
  5452. 'mod_rq' => null,
  5453. ]);
  5454. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  5455. foreach (array_keys($sids) as $sid) {
  5456. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  5457. }
  5458. return $sids;
  5459. }
  5460. /**
  5461. * 废弃单个审批订单 bundle(退回外发初选,明细归档留痕)
  5462. *
  5463. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5464. * @return array<int, true> 已处理的 scydgy_id 集合
  5465. */
  5466. protected function abandonAuditOrderBundle(array $bundle): array
  5467. {
  5468. return $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  5469. }
  5470. /**
  5471. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  5472. *
  5473. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5474. */
  5475. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  5476. {
  5477. $scydgyId = trim($scydgyId);
  5478. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5479. if ($scydgyId === '') {
  5480. return $empty;
  5481. }
  5482. try {
  5483. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5484. } catch (\Throwable $e) {
  5485. $anchor = null;
  5486. }
  5487. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  5488. return $empty;
  5489. }
  5490. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5491. if ($ccydh === '') {
  5492. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5493. }
  5494. try {
  5495. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5496. $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
  5497. $pos = $query->order('scydgy_id', 'asc')->select();
  5498. } catch (\Throwable $e) {
  5499. $pos = [$anchor];
  5500. }
  5501. if (!is_array($pos) || $pos === []) {
  5502. $pos = [$anchor];
  5503. }
  5504. return [
  5505. 'ccydh' => $ccydh,
  5506. 'pos' => $pos,
  5507. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5508. ];
  5509. }
  5510. protected function purchaseOrderRowIsCompleted(array $po): bool
  5511. {
  5512. $st = $po['status'] ?? null;
  5513. if ($st === 1 || $st === '1') {
  5514. return true;
  5515. }
  5516. if (is_string($st) && trim($st) === '1') {
  5517. return true;
  5518. }
  5519. return is_numeric($st) && (int)$st === 1;
  5520. }
  5521. /**
  5522. * 废弃订单 — 退回外发初选重新询价(支持单条或批量)
  5523. */
  5524. public function auditAbandon()
  5525. {
  5526. if (!$this->request->isPost()) {
  5527. $this->error(__('Invalid parameters'));
  5528. }
  5529. $anchorIds = [];
  5530. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5531. if ($batchRaw !== '') {
  5532. $decoded = json_decode($batchRaw, true);
  5533. if (is_array($decoded)) {
  5534. foreach ($decoded as $id) {
  5535. $s = trim((string)$id);
  5536. if ($s !== '') {
  5537. $anchorIds[] = $s;
  5538. }
  5539. }
  5540. }
  5541. }
  5542. if ($anchorIds === []) {
  5543. $single = trim((string)$this->request->post('scydgy_id', ''));
  5544. if ($single !== '') {
  5545. $anchorIds[] = $single;
  5546. }
  5547. }
  5548. if ($anchorIds === []) {
  5549. $this->error('请至少选择一条订单');
  5550. }
  5551. $processedCcydh = [];
  5552. $doneOrders = 0;
  5553. $allSids = [];
  5554. Db::startTrans();
  5555. try {
  5556. foreach ($anchorIds as $anchorId) {
  5557. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  5558. if (($bundle['pos'] ?? []) === []) {
  5559. continue;
  5560. }
  5561. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5562. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5563. if (isset($processedCcydh[$dedupeKey])) {
  5564. continue;
  5565. }
  5566. $processedCcydh[$dedupeKey] = true;
  5567. $sids = $this->abandonAuditOrderBundle($bundle);
  5568. if ($sids === []) {
  5569. continue;
  5570. }
  5571. $doneOrders++;
  5572. foreach (array_keys($sids) as $sid) {
  5573. $allSids[(int)$sid] = true;
  5574. }
  5575. }
  5576. if ($doneOrders < 1) {
  5577. throw new \Exception('所选订单均不在待确认供应商状态');
  5578. }
  5579. Db::commit();
  5580. } catch (\Throwable $e) {
  5581. Db::rollback();
  5582. $this->error($e->getMessage());
  5583. }
  5584. $this->pickHiddenScydgySetCache = null;
  5585. $msg = $doneOrders > 1
  5586. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回外发初选,历史下发与操作记录已保留')
  5587. : '已退回外发初选,请重新选择供应商下发(历史记录已保留)';
  5588. $this->success($msg);
  5589. }
  5590. /**
  5591. * 历史存证 — 已完结订单重新下发,退回外发初选(支持单条或批量)
  5592. */
  5593. public function archiveAbandon()
  5594. {
  5595. if (!$this->request->isPost()) {
  5596. $this->error(__('Invalid parameters'));
  5597. }
  5598. $anchorIds = [];
  5599. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5600. if ($batchRaw !== '') {
  5601. $decoded = json_decode($batchRaw, true);
  5602. if (is_array($decoded)) {
  5603. foreach ($decoded as $id) {
  5604. $s = trim((string)$id);
  5605. if ($s !== '') {
  5606. $anchorIds[] = $s;
  5607. }
  5608. }
  5609. }
  5610. }
  5611. if ($anchorIds === []) {
  5612. $single = trim((string)$this->request->post('scydgy_id', ''));
  5613. if ($single !== '') {
  5614. $anchorIds[] = $single;
  5615. }
  5616. }
  5617. if ($anchorIds === []) {
  5618. $this->error('请至少选择一条订单');
  5619. }
  5620. $processedCcydh = [];
  5621. $doneOrders = 0;
  5622. Db::startTrans();
  5623. try {
  5624. foreach ($anchorIds as $anchorId) {
  5625. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  5626. if (($bundle['pos'] ?? []) === []) {
  5627. continue;
  5628. }
  5629. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5630. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5631. if (isset($processedCcydh[$dedupeKey])) {
  5632. continue;
  5633. }
  5634. $processedCcydh[$dedupeKey] = true;
  5635. $sids = $this->abandonOrderBundleToPick(
  5636. $bundle,
  5637. 'archive_abandon',
  5638. ',从历史存证退回外发初选'
  5639. );
  5640. if ($sids === []) {
  5641. continue;
  5642. }
  5643. $doneOrders++;
  5644. }
  5645. if ($doneOrders < 1) {
  5646. throw new \Exception('所选订单均不是已完结状态');
  5647. }
  5648. Db::commit();
  5649. } catch (\Throwable $e) {
  5650. Db::rollback();
  5651. $this->error($e->getMessage());
  5652. }
  5653. $this->pickHiddenScydgySetCache = null;
  5654. $msg = $doneOrders > 1
  5655. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回外发初选,历史记录已保留')
  5656. : '已退回外发初选,请重新选择供应商下发(历史记录已保留)';
  5657. $this->success($msg);
  5658. }
  5659. /**
  5660. * 采购终审 — 审批驳回(退回外发审批下发,不发送短信)
  5661. */
  5662. public function purchaseApprovalReject()
  5663. {
  5664. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5665. $this->error(__('Invalid parameters'));
  5666. }
  5667. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5668. $decoded = json_decode($batchRaw, true);
  5669. if (!is_array($decoded) || $decoded === []) {
  5670. $this->error('提交数据无效');
  5671. }
  5672. Db::startTrans();
  5673. try {
  5674. foreach ($decoded as $item) {
  5675. if (!is_array($item)) {
  5676. continue;
  5677. }
  5678. $sid = (int)($item['scydgy_id'] ?? 0);
  5679. if (!$this->isValidScydgyRowId($sid)) {
  5680. continue;
  5681. }
  5682. $this->runPurchaseApprovalRejectForSid($sid);
  5683. }
  5684. Db::commit();
  5685. } catch (\Throwable $e) {
  5686. Db::rollback();
  5687. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  5688. }
  5689. $this->success('已驳回并退回「外发审批下发」');
  5690. }
  5691. /**
  5692. * @throws \Exception
  5693. */
  5694. protected function runPurchaseApprovalRejectForSid(int $sid): void
  5695. {
  5696. $allIds = $this->purchaseOrderDetail($sid);
  5697. if ($allIds === []) {
  5698. throw new \Exception('未找到下发明细');
  5699. }
  5700. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5701. 'wflow_status' => 1,
  5702. 'status' => 0,
  5703. 'pick_company_name' => '',
  5704. ]);
  5705. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
  5706. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  5707. $poId = 0;
  5708. try {
  5709. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5710. if (is_array($po)) {
  5711. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  5712. }
  5713. } catch (\Throwable $e) {
  5714. }
  5715. $this->addOrderLog($sid, 'purchase_reject', '采购终审驳回,退回外发审批下发', $poId > 0 ? $poId : null);
  5716. }
  5717. /**
  5718. * 审核弹窗(旧入口,POST 已关闭)
  5719. */
  5720. public function review()
  5721. {
  5722. if ($this->request->isPost()) {
  5723. $this->error('请使用第一步「外发下发」通知供应商,再在「确认供应商」中选定一家');
  5724. }
  5725. $this->view->assign('pickMode', 0);
  5726. return $this->view->fetch('procuremen/review');
  5727. }
  5728. /**
  5729. * 审核弹窗获取公司列表
  5730. */
  5731. public function reviewCompanies()
  5732. {
  5733. if (!$this->request->isAjax()) {
  5734. $this->error(__('Invalid parameters'));
  5735. }
  5736. $list = [];
  5737. try {
  5738. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  5739. $rows = Db::table('customer')
  5740. ->where(function ($q) {
  5741. $q->where('status', 1)
  5742. ->whereOr('status', '1')
  5743. ->whereOr('status', '')
  5744. ->whereNull('status');
  5745. })
  5746. ->order('id', 'desc')
  5747. ->select();
  5748. } catch (\Throwable $e) {
  5749. $this->success('', '', []);
  5750. return;
  5751. }
  5752. if (!is_array($rows)) {
  5753. $this->success('', '', []);
  5754. return;
  5755. }
  5756. $detailColCandidates = [
  5757. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  5758. 'company_detail', 'company_desc', 'address',
  5759. ];
  5760. foreach ($rows as $row) {
  5761. if (!is_array($row)) {
  5762. continue;
  5763. }
  5764. $norm = [];
  5765. foreach ($row as $k => $v) {
  5766. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  5767. }
  5768. $row = $norm;
  5769. $st = $row['status'] ?? '';
  5770. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  5771. continue;
  5772. }
  5773. $id = isset($row['id']) ? (string)$row['id'] : '';
  5774. $companyName = '';
  5775. foreach (['company_name', 'name'] as $nk) {
  5776. if (!empty($row[$nk])) {
  5777. $companyName = trim((string)$row[$nk]);
  5778. break;
  5779. }
  5780. }
  5781. $username = '';
  5782. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  5783. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  5784. $username = trim((string)$row[$uk]);
  5785. break;
  5786. }
  5787. }
  5788. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  5789. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  5790. if ($phone === '' && isset($row['account'])) {
  5791. $phone = trim((string)$row['account']);
  5792. }
  5793. if ($phone === '' && isset($row['mobile'])) {
  5794. $phone = trim((string)$row['mobile']);
  5795. }
  5796. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  5797. if ($email === '' && $phone === '') {
  5798. continue;
  5799. }
  5800. $category = '';
  5801. foreach (['company_type', 'category', 'type_name'] as $ck) {
  5802. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  5803. $category = trim((string)$row[$ck]);
  5804. break;
  5805. }
  5806. }
  5807. $detail = '';
  5808. foreach ($detailColCandidates as $dk) {
  5809. if (!isset($row[$dk])) {
  5810. continue;
  5811. }
  5812. $dv = trim((string)$row[$dk]);
  5813. if ($dv !== '') {
  5814. $detail = $dv;
  5815. break;
  5816. }
  5817. }
  5818. $list[] = [
  5819. 'id' => $id,
  5820. 'name' => $companyName,
  5821. 'company_name' => $companyName,
  5822. 'username' => $username,
  5823. 'email' => $email,
  5824. 'phone' => $phone,
  5825. 'category' => $category,
  5826. 'company_type' => $category,
  5827. 'detail' => $detail,
  5828. ];
  5829. }
  5830. $this->success('', '', $list);
  5831. }
  5832. /**
  5833. * 采购确认-下发明细弹窗:
  5834. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  5835. */
  5836. public function outward_detail()
  5837. {
  5838. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5839. if (is_array($ids)) {
  5840. $ids = isset($ids[0]) ? $ids[0] : '';
  5841. }
  5842. $ids = trim((string)$ids);
  5843. if ($ids === '') {
  5844. $this->error(__('Invalid parameters'));
  5845. }
  5846. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  5847. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  5848. $wffTab = 'all';
  5849. }
  5850. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  5851. $purchaseOrderId = 0;
  5852. $po = null;
  5853. try {
  5854. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5855. if (is_array($po)) {
  5856. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  5857. }
  5858. } catch (\Throwable $e) {
  5859. $purchaseOrderId = 0;
  5860. $po = null;
  5861. }
  5862. if (!$isPurchaseConfirm && is_array($po)) {
  5863. $wf = (int)($po['wflow_status'] ?? 0);
  5864. $st = trim((string)($po['status'] ?? ''));
  5865. $isDone = ($st === '1' || $st === 1);
  5866. if ($wf === 2 && !$isDone) {
  5867. $isPurchaseConfirm = true;
  5868. }
  5869. }
  5870. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  5871. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5872. $confirmProcessCount = 1;
  5873. $confirmPickGroups = [];
  5874. $processDisplayRows = [];
  5875. $allDetailsBySid = [];
  5876. $requiredSidList = [];
  5877. $sidList = [$ids];
  5878. if ($isPurchaseConfirm) {
  5879. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  5880. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  5881. if ($mergeRows !== []) {
  5882. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5883. }
  5884. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  5885. if ($confirmBundle['pos'] !== []) {
  5886. $sidList = [];
  5887. foreach ($confirmBundle['pos'] as $poRow) {
  5888. if (!is_array($poRow)) {
  5889. continue;
  5890. }
  5891. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5892. if (!$this->isValidScydgyRowId($sid)) {
  5893. continue;
  5894. }
  5895. $sidList[] = (string)$sid;
  5896. $requiredSidList[] = $sid;
  5897. }
  5898. }
  5899. if ($sidList === []) {
  5900. $sidList = [$ids];
  5901. $requiredSidList = [(int)$ids];
  5902. }
  5903. $confirmProcessCount = max(1, count($requiredSidList));
  5904. if (is_array($po) && $purchaseOrderId <= 0) {
  5905. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  5906. }
  5907. }
  5908. $rows = [];
  5909. try {
  5910. if (count($sidList) === 1) {
  5911. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  5912. } else {
  5913. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  5914. }
  5915. } catch (\Throwable $e) {
  5916. $rows = [];
  5917. }
  5918. if ($isPurchaseConfirm) {
  5919. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  5920. }
  5921. foreach ($rows as &$r) {
  5922. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5923. $r['id'] = $r['ID'];
  5924. }
  5925. if (isset($r['createtime'])) {
  5926. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5927. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5928. } else {
  5929. $r['createtime_text'] = (string)$r['createtime'];
  5930. }
  5931. } else {
  5932. $r['createtime_text'] = '';
  5933. }
  5934. }
  5935. unset($r);
  5936. $pickedCompanyName = '';
  5937. if ($isPurchaseConfirm) {
  5938. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  5939. if (!is_array($poRow)) {
  5940. continue;
  5941. }
  5942. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5943. if ($pn !== '') {
  5944. $pickedCompanyName = $pn;
  5945. break;
  5946. }
  5947. }
  5948. }
  5949. $this->view->assign('rows', $rows ?: []);
  5950. $this->view->assign('rowCount', count($rows ?: []));
  5951. $this->view->assign('scydgyId', $ids);
  5952. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  5953. $this->view->assign('headTitle', $headTitle);
  5954. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  5955. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  5956. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  5957. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  5958. $this->view->assign('processDisplayRows', $processDisplayRows);
  5959. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  5960. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  5961. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  5962. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  5963. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  5964. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  5965. if ($isPurchaseConfirm) {
  5966. return $this->view->fetch();
  5967. }
  5968. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5969. $this->view->engine->layout(false);
  5970. try {
  5971. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  5972. $this->view->assign('dialogBody', $bodyHtml);
  5973. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  5974. } finally {
  5975. if ($restoreLayout) {
  5976. $this->view->engine->layout($restoreLayout);
  5977. }
  5978. }
  5979. }
  5980. /**
  5981. * 月度导出记录表(不存在时自动创建)
  5982. */
  5983. protected function ensurePurchaseMonthExportLogTable(): void
  5984. {
  5985. try {
  5986. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  5987. } catch (\Throwable $e) {
  5988. Db::execute(
  5989. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  5990. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  5991. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  5992. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  5993. `admin_name` varchar(64) NOT NULL DEFAULT '',
  5994. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  5995. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  5996. `createtime` int(10) unsigned DEFAULT NULL,
  5997. PRIMARY KEY (`id`),
  5998. KEY `idx_ym` (`ym`),
  5999. KEY `idx_ct` (`createtime`)
  6000. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度外发明细导出记录'"
  6001. );
  6002. }
  6003. }
  6004. /**
  6005. * 按月份导出:已完结且采购确认已选定供应商(明细 status=1),与列表「已完结」∩「已选中」一致。
  6006. * 表头固定 8 列(与历史「外发明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6007. */
  6008. public function export_month_outward()
  6009. {
  6010. $this->request->filter(['strip_tags', 'trim']);
  6011. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6012. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6013. $ym = date('Y-m');
  6014. }
  6015. $monthStart = $ym . '-01 00:00:00';
  6016. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  6017. $dbRows = [];
  6018. try {
  6019. $query = Db::table('purchase_order');
  6020. $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
  6021. $dbRows = $query->select();
  6022. } catch (\Throwable $e) {
  6023. $dbRows = [];
  6024. }
  6025. if (!is_array($dbRows)) {
  6026. $dbRows = [];
  6027. }
  6028. $pickedSidSet = $this->loadScydgyIdsWithPickedSupplierDetail();
  6029. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($pickedSidSet) {
  6030. if (!is_array($dbRow)) {
  6031. return false;
  6032. }
  6033. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  6034. if ($sid <= 0 && isset($dbRow['SCYDGY_ID'])) {
  6035. $sid = (int)$dbRow['SCYDGY_ID'];
  6036. }
  6037. return $sid > 0 && isset($pickedSidSet[$sid]);
  6038. }));
  6039. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6040. $filtered = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], 'pick_time');
  6041. $mainBySid = [];
  6042. foreach ($filtered as $rw) {
  6043. if (!is_array($rw)) {
  6044. continue;
  6045. }
  6046. $rid = (int)($rw['ID'] ?? 0);
  6047. if ($rid > 0) {
  6048. $mainBySid[$rid] = $rw;
  6049. }
  6050. }
  6051. if ($mainBySid === []) {
  6052. $detailRows = [];
  6053. } else {
  6054. try {
  6055. $detailRows = Db::table('purchase_order_detail')
  6056. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6057. ->where('status', 1)
  6058. ->order('CCYDH', 'asc')
  6059. ->order('company_name', 'asc')
  6060. ->order('id', 'asc')
  6061. ->select();
  6062. } catch (\Throwable $e) {
  6063. try {
  6064. $detailRows = Db::table('purchase_order_detail')
  6065. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6066. ->where('status', 1)
  6067. ->order('CCYDH', 'asc')
  6068. ->order('company_name', 'asc')
  6069. ->order('ID', 'asc')
  6070. ->select();
  6071. } catch (\Throwable $e2) {
  6072. $detailRows = [];
  6073. }
  6074. }
  6075. }
  6076. if (!is_array($detailRows)) {
  6077. $detailRows = [];
  6078. }
  6079. $exportLines = [];
  6080. foreach ($detailRows as $dr) {
  6081. if (!is_array($dr)) {
  6082. continue;
  6083. }
  6084. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6085. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6086. continue;
  6087. }
  6088. $m = $mainBySid[$sid];
  6089. $exportLines[] = [
  6090. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6091. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6092. 'company_name' => (string)($dr['company_name'] ?? ''),
  6093. 'CDF' => (string)($m['CDF'] ?? ''),
  6094. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6095. 'gx' => $this->procuremenExportGxText($m),
  6096. 'detail' => $dr,
  6097. ];
  6098. }
  6099. $groups = [];
  6100. foreach ($exportLines as $line) {
  6101. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6102. if (!isset($groups[$k])) {
  6103. $groups[$k] = [];
  6104. }
  6105. $groups[$k][] = $line;
  6106. }
  6107. ksort($groups, SORT_STRING);
  6108. $spreadsheet = new Spreadsheet();
  6109. $sheet = $spreadsheet->getActiveSheet();
  6110. $sheet->setTitle('外发明细');
  6111. $mon = (int)substr($ym, 5, 2);
  6112. $sheet->mergeCells('A1:H1');
  6113. $sheet->setCellValue('A1', $mon . '月外发明细');
  6114. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6115. $sheet->getStyle('A1')->getAlignment()
  6116. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6117. ->setVertical(Alignment::VERTICAL_CENTER);
  6118. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6119. $col = 'A';
  6120. foreach ($headers as $h) {
  6121. $sheet->setCellValue($col . '2', $h);
  6122. $col++;
  6123. }
  6124. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6125. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6126. $rowNum = 3;
  6127. $sumSubtotalCounts = 0;
  6128. $grandAmount = 0.0;
  6129. if ($groups === []) {
  6130. $sheet->mergeCells('A3:H3');
  6131. $sheet->setCellValue('A3', '(当月暂无符合条件的外发明细)');
  6132. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6133. $rowNum = 4;
  6134. } else {
  6135. foreach ($groups as $items) {
  6136. if ($items === []) {
  6137. continue;
  6138. }
  6139. $groupLineCount = count($items);
  6140. $subAmount = 0.0;
  6141. $i = 0;
  6142. foreach ($items as $line) {
  6143. $i++;
  6144. $dr = $line['detail'];
  6145. $amt = $this->procuremenExportAmount($dr);
  6146. $subAmount += $amt;
  6147. $sheet->setCellValue('A' . $rowNum, $i);
  6148. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6149. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6150. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6151. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6152. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6153. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6154. $sheet->setCellValue('H' . $rowNum, $amt);
  6155. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6156. $rowNum++;
  6157. }
  6158. $sumSubtotalCounts += $groupLineCount;
  6159. $grandAmount += $subAmount;
  6160. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  6161. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6162. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6163. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6164. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  6165. ->setVertical(Alignment::VERTICAL_CENTER);
  6166. $rowNum++;
  6167. }
  6168. }
  6169. $sheet->setCellValue('A' . $rowNum, '总计');
  6170. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6171. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6172. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6173. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6174. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  6175. $lastRow = $rowNum;
  6176. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6177. 'borders' => [
  6178. 'allBorders' => [
  6179. 'borderStyle' => Border::BORDER_THIN,
  6180. 'color' => ['rgb' => '000000'],
  6181. ],
  6182. ],
  6183. ]);
  6184. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6185. if ($lastRow >= 3) {
  6186. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6187. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6188. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6189. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6190. }
  6191. $sheet->getColumnDimension('A')->setWidth(7);
  6192. $sheet->getColumnDimension('B')->setWidth(16);
  6193. $sheet->getColumnDimension('C')->setWidth(52);
  6194. $sheet->getColumnDimension('D')->setWidth(32);
  6195. $sheet->getColumnDimension('E')->setWidth(12);
  6196. $sheet->getColumnDimension('F')->setWidth(44);
  6197. $sheet->getColumnDimension('G')->setWidth(26);
  6198. $sheet->getColumnDimension('H')->setWidth(13);
  6199. $sheet->getRowDimension(1)->setRowHeight(28);
  6200. $fileBase = '外发明细_' . str_replace('-', '', $ym);
  6201. $filename = $fileBase . '.xlsx';
  6202. try {
  6203. $this->ensurePurchaseMonthExportLogTable();
  6204. list($adminId, $adminName) = $this->GetUseName();
  6205. Db::table('purchase_month_export_log')->insert([
  6206. 'ym' => $ym,
  6207. 'admin_id' => (int)$adminId,
  6208. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6209. 'row_count' => count($exportLines),
  6210. 'total_amount' => round($grandAmount, 2),
  6211. 'createtime' => time(),
  6212. ]);
  6213. } catch (\Throwable $e) {
  6214. Log::write('month export log: ' . $e->getMessage(), 'error');
  6215. }
  6216. if (ob_get_length()) {
  6217. ob_end_clean();
  6218. }
  6219. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  6220. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6221. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6222. header('Cache-Control: max-age=0');
  6223. $writer = new Xlsx($spreadsheet);
  6224. $writer->save('php://output');
  6225. $spreadsheet->disconnectWorksheets();
  6226. unset($spreadsheet);
  6227. exit;
  6228. }
  6229. /**
  6230. * 导出用:工序列文案
  6231. */
  6232. protected function procuremenExportGxText(array $r)
  6233. {
  6234. $a = trim((string)($r['CDXMC'] ?? ''));
  6235. $b = trim((string)($r['CGYMC'] ?? ''));
  6236. if ($a !== '' && $b !== '') {
  6237. return $a . ':' . $b;
  6238. }
  6239. return $a !== '' ? $a : $b;
  6240. }
  6241. /**
  6242. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6243. */
  6244. protected function procuremenExportAmount(array $r)
  6245. {
  6246. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6247. if (!array_key_exists($k, $r)) {
  6248. continue;
  6249. }
  6250. $v = $r[$k];
  6251. if ($v === null || $v === '') {
  6252. continue;
  6253. }
  6254. if (is_numeric($v)) {
  6255. return (float)$v;
  6256. }
  6257. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  6258. if ($v !== '' && is_numeric($v)) {
  6259. return (float)$v;
  6260. }
  6261. }
  6262. return 0.0;
  6263. }
  6264. /**
  6265. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  6266. */
  6267. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  6268. {
  6269. $s = trim($ccydh);
  6270. if ($s === '') {
  6271. return 'ORDER';
  6272. }
  6273. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  6274. $s = trim($s, '._-');
  6275. if ($s === '') {
  6276. return 'ORDER';
  6277. }
  6278. if (function_exists('mb_substr')) {
  6279. return mb_substr($s, 0, 80, 'UTF-8');
  6280. }
  6281. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  6282. }
  6283. /**
  6284. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  6285. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  6286. *
  6287. * @return array{objectKey: string, webPath: string}
  6288. */
  6289. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  6290. {
  6291. $sid = (int)$scydgyId;
  6292. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  6293. $y = date('Y');
  6294. $m = date('m');
  6295. $d = date('d');
  6296. $basename = $safeOrder . '_' . $sid . '.pdf';
  6297. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  6298. return [
  6299. 'objectKey' => $objectKey,
  6300. 'webPath' => '/' . $objectKey,
  6301. ];
  6302. }
  6303. /**
  6304. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  6305. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  6306. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  6307. *
  6308. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  6309. */
  6310. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  6311. {
  6312. if (!$this->isValidScydgyRowId($scydgyId)) {
  6313. return '';
  6314. }
  6315. $ids = trim((string)$scydgyId);
  6316. $prep = $this->prepareProcuremenDetailsView($ids);
  6317. if (!$prep['ok']) {
  6318. return '';
  6319. }
  6320. $ccydh = $prep['ccydh'];
  6321. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  6322. $objectKey = $paths['objectKey'];
  6323. $webPath = $paths['webPath'];
  6324. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  6325. $this->view->assign([
  6326. 'pdf_export' => 1,
  6327. 'pdfMetaLine' => $meta,
  6328. ]);
  6329. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  6330. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6331. $this->view->engine->layout(false);
  6332. try {
  6333. $html = $this->view->fetch('procuremen/details_pdf_shell');
  6334. } catch (\Throwable $e) {
  6335. if ($restoreLayout) {
  6336. $this->view->engine->layout($restoreLayout);
  6337. }
  6338. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  6339. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6340. return '';
  6341. }
  6342. if ($restoreLayout) {
  6343. $this->view->engine->layout($restoreLayout);
  6344. }
  6345. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6346. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  6347. if (!is_dir($tempDir)) {
  6348. @mkdir($tempDir, 0755, true);
  6349. }
  6350. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  6351. try {
  6352. $mpdf = new \Mpdf\Mpdf([
  6353. 'mode' => 'utf-8',
  6354. 'format' => 'A4',
  6355. 'margin_left' => 12,
  6356. 'margin_right' => 12,
  6357. 'margin_top' => 14,
  6358. 'margin_bottom' => 14,
  6359. 'tempDir' => $tempDir,
  6360. 'autoScriptToLang' => true,
  6361. 'autoLangToFont' => true,
  6362. ]);
  6363. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  6364. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  6365. $mpdf->SetBasePath('http://127.0.0.1/');
  6366. $mpdf->WriteHTML($html);
  6367. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  6368. } catch (\Throwable $e) {
  6369. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  6370. if (is_file($tempPdf)) {
  6371. @unlink($tempPdf);
  6372. }
  6373. return '';
  6374. }
  6375. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  6376. if ($ossUrl !== '') {
  6377. @unlink($tempPdf);
  6378. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6379. return $ossUrl;
  6380. }
  6381. $pi = pathinfo($objectKey);
  6382. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  6383. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  6384. if ($baseFile === '') {
  6385. @unlink($tempPdf);
  6386. return '';
  6387. }
  6388. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  6389. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  6390. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  6391. @unlink($tempPdf);
  6392. return '';
  6393. }
  6394. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  6395. if (!@copy($tempPdf, $fullPath)) {
  6396. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  6397. @unlink($tempPdf);
  6398. return '';
  6399. }
  6400. @unlink($tempPdf);
  6401. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6402. return $webPath;
  6403. }
  6404. /**
  6405. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  6406. */
  6407. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  6408. {
  6409. if ($scydgyId <= 0 || $webPath === '') {
  6410. return;
  6411. }
  6412. try {
  6413. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  6414. } catch (\Throwable $e) {
  6415. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  6416. }
  6417. }
  6418. /**
  6419. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  6420. *
  6421. * @param array<string, string> $vars
  6422. * @return array<string, string>
  6423. */
  6424. protected function normalizeSmsTemplateVars(array $vars): array
  6425. {
  6426. $out = [];
  6427. foreach ($vars as $k => $v) {
  6428. $out[(string)$k] = trim((string)$v);
  6429. }
  6430. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  6431. $out['contact_name'] = $out['company_name'];
  6432. }
  6433. return $out;
  6434. }
  6435. /**
  6436. * 按手机号或公司名称查 customer 表联系人姓名
  6437. */
  6438. protected function resolveCustomerContactName(string $phone, string $companyName): string
  6439. {
  6440. $phone = trim($phone);
  6441. $companyName = trim($companyName);
  6442. try {
  6443. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  6444. $row = Db::table('customer')
  6445. ->where(function ($q) use ($phone) {
  6446. $q->where('phone', $phone)->whereOr('account', $phone);
  6447. })
  6448. ->order('id', 'asc')
  6449. ->find();
  6450. if (is_array($row)) {
  6451. $nm = trim((string)($row['username'] ?? ''));
  6452. if ($nm !== '') {
  6453. return $nm;
  6454. }
  6455. }
  6456. }
  6457. if ($companyName !== '') {
  6458. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  6459. if (is_array($row)) {
  6460. return trim((string)($row['username'] ?? ''));
  6461. }
  6462. }
  6463. } catch (\Throwable $e) {
  6464. }
  6465. return '';
  6466. }
  6467. /**
  6468. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  6469. */
  6470. protected function plainTextToHtmlEmailBody(string $text): string
  6471. {
  6472. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  6473. $parts = explode("\n", $text);
  6474. $out = [];
  6475. foreach ($parts as $line) {
  6476. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  6477. $out[] = $line;
  6478. } else {
  6479. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  6480. }
  6481. }
  6482. return implode("<br>\n", $out);
  6483. }
  6484. /**
  6485. * 短信场景:去掉链接类变量,避免误填 URL
  6486. *
  6487. * @param array<string, string> $vars
  6488. * @return array<string, string>
  6489. */
  6490. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  6491. {
  6492. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  6493. return $vars;
  6494. }
  6495. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  6496. $vars[$k] = '';
  6497. }
  6498. return $vars;
  6499. }
  6500. /**
  6501. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  6502. *
  6503. * @param array<string, string> $vars
  6504. */
  6505. protected function renderNotifyTemplate(string $scene, array $vars): string
  6506. {
  6507. $vars = $this->normalizeSmsTemplateVars($vars);
  6508. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  6509. $row = $this->loadNotifyTemplateRow($scene);
  6510. if ($row === null) {
  6511. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6512. }
  6513. $tpl = trim((string)($row['content'] ?? ''));
  6514. if ($tpl === '') {
  6515. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6516. }
  6517. foreach ($vars as $k => $v) {
  6518. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  6519. }
  6520. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  6521. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  6522. return $tpl;
  6523. }
  6524. protected function resolveProcuremenEmailSubject(string $scene): string
  6525. {
  6526. $map = [
  6527. 'review_email' => '您有新的外发加工订单',
  6528. ];
  6529. $subject = trim((string)($map[$scene] ?? ''));
  6530. if ($subject === '') {
  6531. $this->error('未配置邮件主题:' . $scene);
  6532. }
  6533. return $subject;
  6534. }
  6535. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  6536. {
  6537. $map = [
  6538. 'review_email' => '外发下发-邮箱',
  6539. 'review_sms' => '外发下发-短信',
  6540. 'confirm_ok' => '采购确认-通过',
  6541. 'confirm_fail' => '采购确认-未通过',
  6542. ];
  6543. $label = $map[$scene] ?? $scene;
  6544. if ($titleRequired) {
  6545. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  6546. }
  6547. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  6548. }
  6549. /** @deprecated 使用 renderNotifyTemplate */
  6550. protected function renderSmsTemplate(string $scene, array $vars): string
  6551. {
  6552. return $this->renderNotifyTemplate($scene, $vars);
  6553. }
  6554. /**
  6555. * 是否开启外发通知演练(不发真实短信/邮件)
  6556. */
  6557. protected function isProcuremenNotifyDryRun(): bool
  6558. {
  6559. return (bool)Config::get('procuremen_notify_dry_run');
  6560. }
  6561. /**
  6562. * @param array<string, mixed> $payload
  6563. */
  6564. protected function recordNotifyDryRunPreview(array $payload): void
  6565. {
  6566. $this->notifyDryRunPreview[] = $payload;
  6567. Log::write('[外发通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6568. }
  6569. /**
  6570. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  6571. * @throws \Exception
  6572. */
  6573. protected function smsbao($phone, $content)
  6574. {
  6575. if ($this->isProcuremenNotifyDryRun()) {
  6576. $this->recordNotifyDryRunPreview([
  6577. 'scene' => 'sms_only',
  6578. 'phone' => $phone,
  6579. 'sms_content' => $content,
  6580. ]);
  6581. return;
  6582. }
  6583. $statusStr = [
  6584. '0' => '短信发送成功',
  6585. '-1' => '参数不全',
  6586. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  6587. '30' => '密码错误',
  6588. '40' => '账号不存在',
  6589. '41' => '余额不足',
  6590. '42' => '帐户已过期',
  6591. '43' => 'IP地址限制',
  6592. '50' => '内容含有敏感词',
  6593. ];
  6594. $smsapi = 'http://api.smsbao.com/';
  6595. $user = 'zhuwei123';
  6596. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  6597. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  6598. $result = @file_get_contents($sendurl);
  6599. if ($result === false) {
  6600. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  6601. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  6602. }
  6603. $result = trim((string)$result);
  6604. if ($result !== '0') {
  6605. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  6606. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  6607. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  6608. }
  6609. }
  6610. }