Procuremen.php 285 KB

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