Procuremen.php 332 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898
  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 think\Cache;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Style\Border;
  15. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  17. use think\Db;
  18. use think\Log;
  19. class Procuremen extends Backend
  20. {
  21. /**
  22. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  23. */
  24. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  25. /**
  26. * Procuremen模型对象
  27. * @var \app\admin\model\Procuremen
  28. */
  29. protected $model = null;
  30. /**
  31. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  32. */
  33. protected $notifyDryRunPreview = [];
  34. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  35. protected $procuremenRedisCache = null;
  36. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  37. protected $pickHiddenScydgySetCache = null;
  38. /** 邮件发送日志表结构已就绪缓存键 */
  39. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  40. /**
  41. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  42. * @var array
  43. */
  44. protected $noNeedRight = [
  45. 'pickreview', 'review', 'reviewcompanies',
  46. ];
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \app\admin\model\Procuremen;
  51. $this->maybeMigrateLegacyWflowStatusText();
  52. $this->assignProcuremenAuthConfig();
  53. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  54. $this->ensurePurchaseEmailSendLogTableOnce();
  55. }
  56. }
  57. /**
  58. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  59. */
  60. protected function maybeMigrateLegacyWflowStatusText(): void
  61. {
  62. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  63. if (is_file($flagFile)) {
  64. return;
  65. }
  66. $map = [
  67. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  68. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  69. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  70. '3' => ProcuremenStatus::WFLOW_APPROVED,
  71. ];
  72. try {
  73. foreach ($map as $num => $text) {
  74. Db::table('purchase_order')
  75. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  76. ->update(['wflow_status' => $text]);
  77. }
  78. @file_put_contents($flagFile, date('c'));
  79. } catch (\Throwable $e) {
  80. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  81. }
  82. }
  83. /**
  84. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  85. *
  86. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  87. */
  88. protected function hasProcuremenPerm(array $actions): bool
  89. {
  90. foreach ($actions as $action) {
  91. $action = strtolower(trim((string)$action));
  92. if ($action === '') {
  93. continue;
  94. }
  95. if (strpos($action, 'procuremen/') !== 0) {
  96. $action = 'procuremen/' . $action;
  97. }
  98. if ($this->auth->check($action)) {
  99. return true;
  100. }
  101. }
  102. $suffixes = [];
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. $action = preg_replace('#^procuremen/#', '', $action);
  106. if ($action !== '') {
  107. $suffixes[$action] = true;
  108. }
  109. }
  110. if ($suffixes === []) {
  111. return false;
  112. }
  113. try {
  114. foreach ($this->auth->getRuleList() as $rule) {
  115. $rule = strtolower((string)$rule);
  116. if (strpos($rule, 'procuremen/') !== 0) {
  117. continue;
  118. }
  119. foreach (array_keys($suffixes) as $suffix) {
  120. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  121. return true;
  122. }
  123. }
  124. }
  125. } catch (\Throwable $e) {
  126. }
  127. return false;
  128. }
  129. /**
  130. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  131. *
  132. * @param string[] $actions
  133. */
  134. protected function hasProcuremenPermStrict(array $actions): bool
  135. {
  136. foreach ($actions as $action) {
  137. $action = strtolower(trim((string)$action));
  138. if ($action === '') {
  139. continue;
  140. }
  141. if (strpos($action, 'procuremen/') !== 0) {
  142. $action = 'procuremen/' . $action;
  143. }
  144. if ($this->auth->check($action)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. /**
  151. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  152. *
  153. * @param string[] $titles
  154. */
  155. protected function authHasAssignedRuleTitle(array $titles): bool
  156. {
  157. $titles = array_values(array_filter(array_map('trim', $titles)));
  158. if ($titles === []) {
  159. return false;
  160. }
  161. try {
  162. $ids = $this->auth->getRuleIds();
  163. if (in_array('*', $ids, true)) {
  164. return true;
  165. }
  166. if ($ids === []) {
  167. return false;
  168. }
  169. $rows = Db::name('auth_rule')
  170. ->where('status', 'normal')
  171. ->whereIn('id', $ids)
  172. ->column('title');
  173. foreach ($rows as $title) {
  174. $t = trim((string)$title);
  175. if ($t !== '' && in_array($t, $titles, true)) {
  176. return true;
  177. }
  178. }
  179. } catch (\Throwable $e) {
  180. }
  181. return false;
  182. }
  183. protected function procuremenCanPickDelete(): bool
  184. {
  185. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  186. return true;
  187. }
  188. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  189. }
  190. protected function procuremenCanComplete(): bool
  191. {
  192. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  193. return true;
  194. }
  195. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  196. }
  197. protected function procuremenCanDispatch(): bool
  198. {
  199. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  200. }
  201. /**
  202. * 前端按钮显隐(Config.procuremenAuth)
  203. */
  204. protected function assignProcuremenAuthConfig(): void
  205. {
  206. $authMap = [
  207. 'pickreview' => $this->procuremenCanDispatch(),
  208. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  209. 'pickdelete' => $this->procuremenCanPickDelete(),
  210. 'completedirectly' => $this->procuremenCanComplete(),
  211. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  212. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  213. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  214. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  215. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  216. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  217. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  218. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  219. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  220. 'details' => $this->hasProcuremenPerm(['details']),
  221. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  222. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  223. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  224. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  225. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  228. 'add' => $this->hasProcuremenPerm(['add']),
  229. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  230. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  231. ];
  232. $this->assignconfig('procuremenAuth', $authMap);
  233. }
  234. /**
  235. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  236. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  237. *
  238. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  239. */
  240. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  241. {
  242. static $mprocCfgLoaded = false;
  243. if (!$mprocCfgLoaded) {
  244. $mprocCfgLoaded = true;
  245. if (is_file(APP_PATH . 'extra/mproc.php')) {
  246. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  247. }
  248. }
  249. $eid = (int)$purchaseOrderDetailId;
  250. $base = $this->resolveMprocMobilePublicBaseUrl();
  251. if ($base === '') {
  252. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  253. }
  254. $path = trim((string)Config::get('mproc.mobile_index_path'));
  255. if ($path === '') {
  256. $path = '/index.php/index/index/index';
  257. } else {
  258. $path = '/' . ltrim($path, '/');
  259. }
  260. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  261. if ($eid > 0) {
  262. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  263. }
  264. return $base . $path . '?main_tab=orders';
  265. }
  266. /**
  267. * 邮件/短信外链:须为带点的公网域名
  268. */
  269. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  270. {
  271. $u = trim((string)$baseUrl);
  272. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  273. return false;
  274. }
  275. $host = parse_url($u, PHP_URL_HOST);
  276. if (!is_string($host) || $host === '') {
  277. return false;
  278. }
  279. if (strcasecmp($host, 'localhost') === 0) {
  280. return false;
  281. }
  282. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  283. return false;
  284. }
  285. if (strpos($host, '.') === false) {
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * 解析用于协助邮件/短信的手机端站点根
  292. */
  293. protected function resolveMprocMobilePublicBaseUrl()
  294. {
  295. $candidates = [];
  296. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  297. $candidates[] = trim((string)Config::get('site.indexurl'));
  298. $cdn = trim((string)Config::get('site.cdnurl'));
  299. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  300. $candidates[] = rtrim($cdn, '/');
  301. }
  302. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  303. $candidates[] = $reqBase;
  304. foreach ($candidates as $c) {
  305. if ($c === '') {
  306. continue;
  307. }
  308. $c = rtrim($c, '/');
  309. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  310. return $c;
  311. }
  312. }
  313. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  314. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  315. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  316. return $reqBase;
  317. }
  318. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  319. return '';
  320. }
  321. /**
  322. * 获取 Redis 中 procuremen_redis
  323. */
  324. protected function ProcuremenRedis(): array
  325. {
  326. if ($this->procuremenRedisCache !== null) {
  327. return $this->procuremenRedisCache;
  328. }
  329. try {
  330. $redis = redis();
  331. $raw = $redis->get('procuremen_redis');
  332. if ($raw === false || $raw === '') {
  333. $this->procuremenRedisCache = [];
  334. return $this->procuremenRedisCache;
  335. }
  336. $decoded = json_decode($raw, true);
  337. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  338. $this->procuremenRedisCache = [];
  339. return $this->procuremenRedisCache;
  340. }
  341. $this->procuremenRedisCache = $decoded['data'];
  342. return $this->procuremenRedisCache;
  343. } catch (\Throwable $e) {
  344. $this->procuremenRedisCache = [];
  345. return $this->procuremenRedisCache;
  346. }
  347. }
  348. /**
  349. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  350. *
  351. * @return array<int, array<string, mixed>>
  352. */
  353. protected function procuremenFetchErpPoolFromDb(): array
  354. {
  355. try {
  356. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  357. $endTime = date('Y-m-d 23:59:59');
  358. $list = Db::table('scydgy')
  359. ->alias('a')
  360. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  361. ->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')
  362. ->where([
  363. 'a.bwjg' => 1,
  364. 'a.iEndBz' => 0,
  365. 'a.iType' => 0,
  366. 'a.iStatus' => 10,
  367. ])
  368. ->where('a.dStamp', '>=', $startTime)
  369. ->where('a.dStamp', '<=', $endTime)
  370. ->order('a.dStamp', 'desc')
  371. ->select();
  372. if (!is_array($list)) {
  373. return [];
  374. }
  375. try {
  376. $redis = redis();
  377. $payload = [
  378. 'code' => 200,
  379. 'msg' => 'success',
  380. 'data' => $list,
  381. ];
  382. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  383. $this->procuremenRedisCache = $list;
  384. } catch (\Throwable $e) {
  385. }
  386. return $list;
  387. } catch (\Throwable $e) {
  388. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  389. return [];
  390. }
  391. }
  392. /**
  393. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  394. *
  395. * @return array<int, array<string, mixed>>
  396. */
  397. protected function procuremenEnsureRedisPool(): array
  398. {
  399. $pool = $this->ProcuremenRedis();
  400. if (is_array($pool) && $pool !== []) {
  401. return $pool;
  402. }
  403. static $warmed = false;
  404. if ($warmed) {
  405. return is_array($pool) ? $pool : [];
  406. }
  407. $warmed = true;
  408. return $this->procuremenFetchErpPoolFromDb();
  409. }
  410. /**
  411. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  412. *
  413. * @param array<string, mixed> $row
  414. */
  415. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  416. {
  417. $t = $this->procuremenRowListSortTime($row, $primary);
  418. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  419. return null;
  420. }
  421. $mo = (int)$m[2];
  422. if ($mo < 1 || $mo > 12) {
  423. return null;
  424. }
  425. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  426. }
  427. /**
  428. * @param array<int, array{year:string, months:array}> $sidebar
  429. * @return array<int, array{year:string, months:array}>
  430. */
  431. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return $sidebar;
  436. }
  437. foreach ($sidebar as $block) {
  438. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  439. continue;
  440. }
  441. foreach ($block['months'] as $item) {
  442. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  443. return $sidebar;
  444. }
  445. }
  446. }
  447. $y = substr($ym, 0, 4);
  448. $mo = (int)substr($ym, 5, 2);
  449. $sidebar[] = [
  450. 'year' => $y,
  451. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  452. ];
  453. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  454. }
  455. /**
  456. * @param array<int, array{year:string, months:array}> $sidebar
  457. * @return string[]
  458. */
  459. protected function flattenProcuremenSidebarYms(array $sidebar): array
  460. {
  461. $yms = [];
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (!is_array($item)) {
  468. continue;
  469. }
  470. $ym = trim((string)($item['ym'] ?? ''));
  471. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  472. $yms[$ym] = true;
  473. }
  474. }
  475. }
  476. return array_keys($yms);
  477. }
  478. /**
  479. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  480. */
  481. protected function GetIndexYearMonths()
  482. {
  483. $ymSet = [];
  484. $pool = $this->procuremenEnsureRedisPool();
  485. foreach ($pool as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. foreach ($this->loadPickManualOrderRows() as $r) {
  495. if (!is_array($r)) {
  496. continue;
  497. }
  498. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  499. if ($ym !== null) {
  500. $ymSet[$ym] = true;
  501. }
  502. }
  503. $ymList = array_keys($ymSet);
  504. if ($ymList === []) {
  505. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  506. }
  507. return $this->buildYearMonthSidebar($ymList);
  508. }
  509. /**
  510. * @param string[] $ymList 形如 2026-06
  511. * @return array<int, array{year:string, months:array}>
  512. */
  513. protected function buildYearMonthSidebar(array $ymList): array
  514. {
  515. rsort($ymList, SORT_STRING);
  516. $byYear = [];
  517. foreach ($ymList as $ym) {
  518. $y = substr($ym, 0, 4);
  519. $mo = (int)substr($ym, 5, 2);
  520. if (!isset($byYear[$y])) {
  521. $byYear[$y] = [];
  522. }
  523. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  524. }
  525. krsort($byYear, SORT_NUMERIC);
  526. foreach ($byYear as $y => $items) {
  527. usort($byYear[$y], function ($a, $b) {
  528. return strcmp($b['ym'], $a['ym']);
  529. });
  530. }
  531. $sidebar = [];
  532. foreach ($byYear as $y => $months) {
  533. $sidebar[] = ['year' => $y, 'months' => $months];
  534. }
  535. return $sidebar;
  536. }
  537. /**
  538. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  539. */
  540. protected function GetIssuedOrderYearMonths(string $stage): array
  541. {
  542. $ymSet = [];
  543. try {
  544. $query = Db::table('purchase_order');
  545. $this->applyPurchaseOrderNotDeletedWhere($query);
  546. if ($stage === 'audit') {
  547. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  548. } elseif ($stage === 'confirm') {
  549. $this->applyPurchaseOrderConfirmStageWhere($query);
  550. } else {
  551. return $this->GetIndexYearMonths();
  552. }
  553. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  554. if (is_array($rows)) {
  555. foreach ($rows as $r) {
  556. if (!is_array($r)) {
  557. continue;
  558. }
  559. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  560. if ($ym !== null) {
  561. $ymSet[$ym] = true;
  562. }
  563. }
  564. }
  565. } catch (\Throwable $e) {
  566. $ymSet = [];
  567. }
  568. $ymList = array_keys($ymSet);
  569. if ($ymList === []) {
  570. $def = $this->resolveProcuremenDefaultYm($stage);
  571. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  577. */
  578. protected function resolveProcuremenDefaultYm(string $stage): string
  579. {
  580. if ($stage === 'pick') {
  581. return date('Y-m');
  582. }
  583. try {
  584. $query = Db::table('purchase_order');
  585. $this->applyPurchaseOrderNotDeletedWhere($query);
  586. if ($stage === 'audit') {
  587. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  588. } elseif ($stage === 'confirm') {
  589. $this->applyPurchaseOrderConfirmStageWhere($query);
  590. } else {
  591. return date('Y-m');
  592. }
  593. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  594. if ($latest === null || $latest === '') {
  595. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  596. }
  597. $t = $this->formatProcuremenDetailTime($latest);
  598. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  599. return $m[1] . '-' . $m[2];
  600. }
  601. } catch (\Throwable $e) {
  602. }
  603. return date('Y-m');
  604. }
  605. protected function applyPurchaseOrderNotDeletedWhere($query): void
  606. {
  607. $query->whereRaw(
  608. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  609. );
  610. }
  611. /**
  612. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  613. */
  614. protected function applyPurchaseOrderConfirmStageWhere($query): void
  615. {
  616. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  617. $quoted = [];
  618. foreach ($vals as $v) {
  619. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  620. }
  621. if ($quoted === []) {
  622. $query->whereRaw('1 = 0');
  623. return;
  624. }
  625. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  626. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  627. }
  628. /**
  629. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  630. *
  631. * @param array<string, mixed> $row
  632. * @return array<string, mixed>
  633. */
  634. protected function normalizePurchaseOrderListTimeRow(array $row): array
  635. {
  636. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  637. $pick = trim((string)($row['pick_time'] ?? ''));
  638. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  639. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  640. $t = trim((string)($row[$key] ?? ''));
  641. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  642. $row['pick_time'] = $t;
  643. break;
  644. }
  645. }
  646. }
  647. return $row;
  648. }
  649. /**
  650. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  651. */
  652. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  653. {
  654. if (!in_array($stage, ['audit', 'confirm'], true)) {
  655. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  656. }
  657. if ($pool === []) {
  658. $def = $this->resolveProcuremenDefaultYm($stage);
  659. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  660. }
  661. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  662. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  663. return false;
  664. }
  665. $monthStart = $ym . '-01 00:00:00';
  666. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  667. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  668. return $probe !== [];
  669. };
  670. if ($tryYm($requestedYm)) {
  671. return $requestedYm;
  672. }
  673. $fallback = $this->resolveProcuremenDefaultYm($stage);
  674. if ($tryYm($fallback)) {
  675. return $fallback;
  676. }
  677. $bestYm = '';
  678. $bestTime = '';
  679. foreach ($pool as $row) {
  680. if (!is_array($row)) {
  681. continue;
  682. }
  683. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  684. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  685. continue;
  686. }
  687. $ymRow = $m[1];
  688. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  689. $bestTime = $t;
  690. $bestYm = $ymRow;
  691. }
  692. }
  693. if ($bestYm !== '') {
  694. return $bestYm;
  695. }
  696. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  697. }
  698. protected function isPurchaseOrderDetailVoid(array $row): bool
  699. {
  700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  701. return true;
  702. }
  703. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  704. }
  705. /**
  706. * 仅当前有效下发明细(排除废弃归档)
  707. */
  708. protected function applyActivePurchaseOrderDetailWhere($query): void
  709. {
  710. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  711. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  712. }
  713. /**
  714. * @param array<string, mixed> $detailRow
  715. */
  716. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  717. {
  718. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  719. return false;
  720. }
  721. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  722. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  723. }
  724. /**
  725. * 废弃退回初选:下发明细标记归档,不物理删除
  726. *
  727. * @param array<int, int|string> $scydgyIds
  728. */
  729. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  730. {
  731. $ids = [];
  732. foreach ($scydgyIds as $sid) {
  733. $n = (int)$sid;
  734. if ($this->isValidScydgyRowId($n) || $n < 0) {
  735. $ids[$n] = true;
  736. }
  737. }
  738. if ($ids === []) {
  739. return;
  740. }
  741. $void = ProcuremenStatus::POD_VOID;
  742. Db::table('purchase_order_detail')
  743. ->where('scydgy_id', 'in', array_keys($ids))
  744. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  745. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  746. ->update([
  747. 'status' => $void,
  748. 'status_name' => $void,
  749. ]);
  750. }
  751. /**
  752. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  753. */
  754. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  755. {
  756. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  757. $norm = function (string $col) use ($p): string {
  758. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  759. };
  760. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  761. $parts = [];
  762. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  763. if ($key === 'createtime') {
  764. $parts[] = $createtime;
  765. } else {
  766. $parts[] = $norm($key);
  767. }
  768. }
  769. return 'COALESCE(' . implode(', ', $parts) . ')';
  770. }
  771. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  772. {
  773. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  774. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  775. }
  776. /**
  777. * @return array<int, array<string, mixed>>
  778. */
  779. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  780. {
  781. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  782. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  783. try {
  784. $query = Db::table('purchase_order')->field($fields);
  785. $this->applyPurchaseOrderNotDeletedWhere($query);
  786. if ($stage === 'audit') {
  787. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  788. } elseif ($stage === 'confirm') {
  789. $this->applyPurchaseOrderConfirmStageWhere($query);
  790. } else {
  791. return [];
  792. }
  793. $query->order('pick_time', 'desc')->order('id', 'desc');
  794. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  795. $monthStart = $ym . '-01 00:00:00';
  796. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  797. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  798. }
  799. $rows = $query->select();
  800. } catch (\Throwable $e) {
  801. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  802. $rows = [];
  803. }
  804. return is_array($rows) ? $rows : [];
  805. }
  806. /**
  807. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  808. */
  809. protected function resolveProcuremenListStage(): string
  810. {
  811. $tab = trim((string)$this->request->request('wff_tab', ''));
  812. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  813. return $tab;
  814. }
  815. $action = strtolower((string)$this->request->action());
  816. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  817. return $action;
  818. }
  819. return 'pick';
  820. }
  821. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  822. {
  823. $rootTrue = rtrim((string)$this->request->root(true), '/');
  824. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  825. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  826. $indexPhpRoot = $rootTrue . '/index.php';
  827. }
  828. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  829. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  830. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  831. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  832. $this->view->assign('defaultYm', $defaultYm);
  833. $this->view->assign('sidebarYearMonths', $sidebar);
  834. $this->view->assign('procuremenStage', $stage);
  835. $this->view->assign('procuremenPageTitle', $pageTitle);
  836. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  837. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  838. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  839. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  840. }
  841. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  842. public function pick()
  843. {
  844. $this->request->filter(['strip_tags', 'trim']);
  845. if (!$this->request->isAjax()) {
  846. $this->assignProcuremenListPage('pick', '协助下发');
  847. return $this->view->fetch('procuremen/index');
  848. }
  849. return $this->index();
  850. }
  851. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  852. public function audit()
  853. {
  854. $this->request->filter(['strip_tags', 'trim']);
  855. if (!$this->request->isAjax()) {
  856. $this->assignProcuremenListPage('audit', '确认供应商');
  857. return $this->view->fetch('procuremen/index');
  858. }
  859. return $this->index();
  860. }
  861. /** 采购确认(定标) */
  862. public function confirm()
  863. {
  864. $this->request->filter(['strip_tags', 'trim']);
  865. if (!$this->request->isAjax()) {
  866. $this->assignProcuremenListPage('confirm', '采购确认');
  867. return $this->view->fetch('procuremen/index');
  868. }
  869. return $this->index();
  870. }
  871. /**
  872. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  873. */
  874. public function index()
  875. {
  876. $this->request->filter(['strip_tags', 'trim']);
  877. if (!$this->request->isAjax()) {
  878. $this->assignProcuremenListPage('pick', '协助下发');
  879. return $this->view->fetch('procuremen/index');
  880. }
  881. if ($this->request->request('keyField')) {
  882. return $this->selectpage();
  883. }
  884. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  885. $limit = max(10, min(500, (int)$limit));
  886. $ym = $this->request->request('ym', '');
  887. $ym = is_string($ym) ? trim($ym) : '';
  888. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  889. $wffTab = $this->resolveProcuremenListStage();
  890. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  891. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  892. ? $this->resolveProcuremenDefaultYm($wffTab)
  893. : date('Y-m');
  894. }
  895. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  896. $ym = date('Y-m');
  897. }
  898. $monthStart = $ym . '-01 00:00:00';
  899. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  900. $search = trim((string)$this->request->get('search', ''));
  901. $hasActiveSearch = ($search !== '');
  902. if (!$hasActiveSearch) {
  903. $filterStr = $this->request->get('filter', '');
  904. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  905. $arr = json_decode($filterStr, true);
  906. if (is_array($arr) && count($arr) > 0) {
  907. foreach ($arr as $v) {
  908. if (is_array($v)) {
  909. if (array_filter($v, function ($x) {
  910. return $x !== '' && $x !== null;
  911. })) {
  912. $hasActiveSearch = true;
  913. break;
  914. }
  915. } elseif ($v !== '' && $v !== null) {
  916. $hasActiveSearch = true;
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. }
  923. $applyMonthRange = !$hasActiveSearch;
  924. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  925. $opArr = (array)json_decode($this->request->get('op', ''), true);
  926. try {
  927. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  928. if ($wffTab === 'audit') {
  929. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  930. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  931. );
  932. } elseif ($wffTab === 'confirm') {
  933. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  934. if ($dbRows === []) {
  935. try {
  936. $dbRows = Db::table('purchase_order')
  937. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  938. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  939. ->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%\')')
  940. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  941. ->order('pick_time', 'desc')->order('id', 'desc')
  942. ->select();
  943. } catch (\Throwable $e) {
  944. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  945. $dbRows = [];
  946. }
  947. }
  948. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  949. if ($pool === []) {
  950. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  951. }
  952. } else {
  953. $pool = $this->procuremenEnsureRedisPool();
  954. if (!is_array($pool)) {
  955. $pool = [];
  956. }
  957. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  958. $hideSet = $this->loadPickHiddenScydgySet();
  959. if ($pool !== [] && $hideSet !== []) {
  960. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  961. if (!is_array($r)) {
  962. return false;
  963. }
  964. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  965. return $id <= 0 || !isset($hideSet[$id]);
  966. }));
  967. }
  968. $manualPool = $this->loadPickManualOrderRows();
  969. if ($manualPool !== []) {
  970. $pool = array_merge($pool, $manualPool);
  971. }
  972. if ($pool === []) {
  973. return json([
  974. 'total' => 0,
  975. 'rows' => [],
  976. ]);
  977. }
  978. }
  979. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  980. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  981. $monthStart = $ym . '-01 00:00:00';
  982. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  983. }
  984. $filtered = $this->filterProcuremenIndexPool(
  985. $pool,
  986. $monthStart,
  987. $monthEnd,
  988. $applyMonthRange,
  989. $search,
  990. $filterArr,
  991. $opArr,
  992. $listTimePrimary
  993. );
  994. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  995. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  996. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  997. }
  998. $sortField = 'ID';
  999. if (is_string($sort) && $sort !== '') {
  1000. $parts = explode(',', $sort);
  1001. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1002. if ($sortField === '') {
  1003. $sortField = 'ID';
  1004. }
  1005. }
  1006. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1007. $nFiltered = count($filtered);
  1008. if ($nFiltered > 1) {
  1009. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1010. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1011. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1012. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1013. if ($ta === $tb) {
  1014. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1015. }
  1016. if ($ta === '') {
  1017. return 1;
  1018. }
  1019. if ($tb === '') {
  1020. return -1;
  1021. }
  1022. return strcmp($ta, $tb) * $ord;
  1023. });
  1024. } elseif ($sortField === 'ID') {
  1025. $sortKeys = [];
  1026. foreach ($filtered as $i => $row) {
  1027. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1028. }
  1029. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1030. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1031. } elseif ($sortField === 'CCYDH') {
  1032. usort($filtered, function ($a, $b) use ($ord) {
  1033. $sa = trim((string)($a['CCYDH'] ?? ''));
  1034. $sb = trim((string)($b['CCYDH'] ?? ''));
  1035. if ($sa === $sb) {
  1036. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1037. }
  1038. if ($sa === '') {
  1039. return 1;
  1040. }
  1041. if ($sb === '') {
  1042. return -1;
  1043. }
  1044. return strcmp($sa, $sb) * $ord;
  1045. });
  1046. } else {
  1047. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1048. $va = $a[$sortField] ?? null;
  1049. $vb = $b[$sortField] ?? null;
  1050. $sa = (string)$va;
  1051. $sb = (string)$vb;
  1052. if ($sa === $sb) {
  1053. return 0;
  1054. }
  1055. return strcmp($sa, $sb) * $ord;
  1056. });
  1057. }
  1058. }
  1059. $offset = max(0, (int)$offset);
  1060. $limit = max(1, (int)$limit);
  1061. $rows = array_slice($filtered, $offset, $limit);
  1062. foreach ($rows as &$rw) {
  1063. if (!is_array($rw)) {
  1064. continue;
  1065. }
  1066. $rid = (int)($rw['ID'] ?? 0);
  1067. $rw['_iss_out'] = ($wffTab !== 'pick');
  1068. }
  1069. unset($rw);
  1070. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1071. $idList = [];
  1072. foreach ($rows as $rw) {
  1073. if (!is_array($rw)) {
  1074. continue;
  1075. }
  1076. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1077. foreach ($rw['_order_merge_rows'] as $mr) {
  1078. $mid = (int)($mr['ID'] ?? 0);
  1079. if ($this->isValidScydgyRowId($mid)) {
  1080. $idList[$mid] = true;
  1081. }
  1082. }
  1083. }
  1084. $id = (int)($rw['ID'] ?? 0);
  1085. if ($this->isValidScydgyRowId($id)) {
  1086. $idList[$id] = true;
  1087. }
  1088. }
  1089. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1090. foreach ($rows as &$rw) {
  1091. if (!is_array($rw)) {
  1092. continue;
  1093. }
  1094. $mergeIds = [];
  1095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1096. foreach ($rw['_order_merge_rows'] as $mr) {
  1097. $mid = (int)($mr['ID'] ?? 0);
  1098. if ($this->isValidScydgyRowId($mid)) {
  1099. $mergeIds[$mid] = true;
  1100. }
  1101. }
  1102. }
  1103. $rid = (int)($rw['ID'] ?? 0);
  1104. if ($this->isValidScydgyRowId($rid)) {
  1105. $mergeIds[$rid] = true;
  1106. }
  1107. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1108. $rw['po_detail_count'] = $s['cnt'];
  1109. $rw['po_amount_fill_cnt'] = $s['amt'];
  1110. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1111. }
  1112. unset($rw);
  1113. }
  1114. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1115. $idList = [];
  1116. foreach ($rows as $rw) {
  1117. if (!is_array($rw)) {
  1118. continue;
  1119. }
  1120. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1121. foreach ($rw['_order_merge_rows'] as $mr) {
  1122. $mid = (int)($mr['ID'] ?? 0);
  1123. if ($this->isValidScydgyRowId($mid)) {
  1124. $idList[$mid] = true;
  1125. }
  1126. }
  1127. }
  1128. $id = (int)($rw['ID'] ?? 0);
  1129. if ($this->isValidScydgyRowId($id)) {
  1130. $idList[$id] = true;
  1131. }
  1132. }
  1133. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1134. foreach ($rows as &$rw) {
  1135. if (!is_array($rw)) {
  1136. continue;
  1137. }
  1138. $mergeIds = [];
  1139. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1140. foreach ($rw['_order_merge_rows'] as $mr) {
  1141. $mid = (int)($mr['ID'] ?? 0);
  1142. if ($this->isValidScydgyRowId($mid)) {
  1143. $mergeIds[$mid] = true;
  1144. }
  1145. }
  1146. }
  1147. $rid = (int)($rw['ID'] ?? 0);
  1148. if ($this->isValidScydgyRowId($rid)) {
  1149. $mergeIds[$rid] = true;
  1150. }
  1151. $buckets = [];
  1152. foreach (array_keys($mergeIds) as $mid) {
  1153. if (isset($quoteBucket[$mid])) {
  1154. $buckets[] = $quoteBucket[$mid];
  1155. }
  1156. }
  1157. $supplierText = $buckets !== []
  1158. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1159. : '';
  1160. if ($wffTab === 'confirm') {
  1161. $rw['picked_supplier_name'] = $supplierText;
  1162. } else {
  1163. $rw['notify_supplier_text'] = $supplierText;
  1164. }
  1165. }
  1166. unset($rw);
  1167. }
  1168. if ($wffTab === 'all' && count($rows) > 0) {
  1169. $this->mergePurchaseOrder($rows);
  1170. }
  1171. if ($wffTab === 'pick' && count($rows) > 0) {
  1172. $this->mergePurchaseOrder($rows);
  1173. }
  1174. foreach ($rows as &$rwClean) {
  1175. if (is_array($rwClean)) {
  1176. unset($rwClean['_order_merge_rows']);
  1177. if (array_key_exists('NGZL', $rwClean)) {
  1178. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1179. }
  1180. }
  1181. }
  1182. unset($rwClean);
  1183. return json([
  1184. 'total' => count($filtered),
  1185. 'rows' => $rows,
  1186. 'activeYm' => $ym,
  1187. ]);
  1188. } catch (\Throwable $e) {
  1189. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1190. return json([
  1191. 'total' => 0,
  1192. 'rows' => [],
  1193. ]);
  1194. }
  1195. }
  1196. /**
  1197. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1198. *
  1199. * @return array<int, true>
  1200. */
  1201. protected function loadPickHiddenScydgySet(): array
  1202. {
  1203. if ($this->pickHiddenScydgySetCache !== null) {
  1204. return $this->pickHiddenScydgySetCache;
  1205. }
  1206. $hideSet = [];
  1207. try {
  1208. $poIds = Db::table('purchase_order')
  1209. ->where(function ($q) {
  1210. $q->whereIn('wflow_status', array_merge(
  1211. ProcuremenStatus::wflowPendingConfirmValues(),
  1212. ProcuremenStatus::wflowPendingApprovalValues()
  1213. ))
  1214. ->whereOr(function ($q1) {
  1215. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1216. })
  1217. ->whereOr(function ($q2) {
  1218. $q2->whereNotNull('pick_time')
  1219. ->where('pick_time', '<>', '')
  1220. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1221. })
  1222. ->whereOr(function ($q3) {
  1223. $q3->whereNotNull('mod_rq')
  1224. ->where('mod_rq', '<>', '')
  1225. ->where('mod_rq', 'not like', '0000-00-00%');
  1226. });
  1227. })
  1228. ->column('scydgy_id');
  1229. if (is_array($poIds)) {
  1230. foreach ($poIds as $pid) {
  1231. $k = (int)$pid;
  1232. if ($k !== 0) {
  1233. $hideSet[$k] = true;
  1234. }
  1235. }
  1236. }
  1237. } catch (\Throwable $e) {
  1238. }
  1239. try {
  1240. $detIdsQuery = Db::table('purchase_order_detail');
  1241. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1242. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1243. if (is_array($detIds)) {
  1244. foreach ($detIds as $pid) {
  1245. $k = (int)$pid;
  1246. if ($this->isValidScydgyRowId($k)) {
  1247. $hideSet[$k] = true;
  1248. }
  1249. }
  1250. }
  1251. } catch (\Throwable $e) {
  1252. }
  1253. $this->pickHiddenScydgySetCache = $hideSet;
  1254. return $hideSet;
  1255. }
  1256. /**
  1257. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1258. *
  1259. * @return array<int, array<string, mixed>>
  1260. */
  1261. protected function loadPickManualOrderRows(): array
  1262. {
  1263. try {
  1264. $dbRows = Db::table('purchase_order')
  1265. ->where('scydgy_id', '<', 0)
  1266. ->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%\')')
  1267. ->order('scydgy_id', 'asc')
  1268. ->select();
  1269. } catch (\Throwable $e) {
  1270. try {
  1271. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1272. } catch (\Throwable $e2) {
  1273. return [];
  1274. }
  1275. }
  1276. if (!is_array($dbRows) || $dbRows === []) {
  1277. return [];
  1278. }
  1279. $detailSidSet = [];
  1280. try {
  1281. $negIds = [];
  1282. foreach ($dbRows as $dbRow) {
  1283. if (!is_array($dbRow)) {
  1284. continue;
  1285. }
  1286. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1287. if ($sid < 0) {
  1288. $negIds[$sid] = true;
  1289. }
  1290. }
  1291. if ($negIds !== []) {
  1292. $detQuery = Db::table('purchase_order_detail')
  1293. ->where('scydgy_id', 'in', array_keys($negIds));
  1294. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1295. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1296. if (is_array($detRows)) {
  1297. foreach ($detRows as $did) {
  1298. $detailSidSet[(int)$did] = true;
  1299. }
  1300. }
  1301. }
  1302. } catch (\Throwable $e) {
  1303. }
  1304. $pool = [];
  1305. foreach ($dbRows as $dbRow) {
  1306. if (!is_array($dbRow)) {
  1307. continue;
  1308. }
  1309. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1310. if ($sid >= 0) {
  1311. continue;
  1312. }
  1313. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1314. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1315. continue;
  1316. }
  1317. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1318. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1319. continue;
  1320. }
  1321. if (isset($detailSidSet[$sid])) {
  1322. continue;
  1323. }
  1324. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1325. $r['_is_manual'] = 1;
  1326. $pool[] = $r;
  1327. }
  1328. return $pool;
  1329. }
  1330. /**
  1331. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1332. */
  1333. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1334. {
  1335. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1336. foreach ($keys as $k) {
  1337. $t = trim((string)($row[$k] ?? ''));
  1338. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1339. return $t;
  1340. }
  1341. }
  1342. return '';
  1343. }
  1344. /**
  1345. * 分配手工新增工序行 ID(负数递减)
  1346. */
  1347. protected function allocateManualScydgyId(): int
  1348. {
  1349. try {
  1350. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1351. $min = (int)$min;
  1352. return $min < 0 ? $min - 1 : -1;
  1353. } catch (\Throwable $e) {
  1354. return -1;
  1355. }
  1356. }
  1357. /**
  1358. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1359. */
  1360. protected function allocateManualOrderCcydh(): string
  1361. {
  1362. $prefix = 'YW' . date('Ymd');
  1363. $maxSeq = 0;
  1364. try {
  1365. $rows = Db::table('purchase_order')
  1366. ->where('CCYDH', 'like', $prefix . '%')
  1367. ->column('CCYDH');
  1368. if (is_array($rows)) {
  1369. foreach ($rows as $ccydh) {
  1370. $ccydh = trim((string)$ccydh);
  1371. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1372. $maxSeq = max($maxSeq, (int)$m[1]);
  1373. }
  1374. }
  1375. }
  1376. } catch (\Throwable $e) {
  1377. }
  1378. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1379. }
  1380. /**
  1381. * purchase_order.mod_rq 是否有有效软删除时间
  1382. */
  1383. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1384. {
  1385. $t = trim((string)$modRq);
  1386. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1387. }
  1388. /**
  1389. * 列表行 → purchase_order 写入字段
  1390. *
  1391. * @return array<string, mixed>
  1392. */
  1393. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1394. {
  1395. return [
  1396. 'scydgy_id' => $scydgyId,
  1397. 'CCYDH' => $row['CCYDH'] ?? null,
  1398. 'CYJMC' => $row['CYJMC'] ?? null,
  1399. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1400. 'CDXMC' => $row['CDXMC'] ?? null,
  1401. 'CGYBH' => $row['CGYBH'] ?? null,
  1402. 'CGYMC' => $row['CGYMC'] ?? null,
  1403. 'CDW' => $row['CDW'] ?? null,
  1404. 'NGZL' => $row['NGZL'] ?? null,
  1405. 'CDF' => $row['CDF'] ?? null,
  1406. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1407. 'MBZ' => $row['MBZ'] ?? null,
  1408. 'bwjg' => $row['bwjg'] ?? null,
  1409. 'iStatus' => $row['iStatus'] ?? null,
  1410. 'dStamp' => $row['dStamp'] ?? null,
  1411. 'dputrecord' => $row['dputrecord'] ?? null,
  1412. 'cywyxm' => $row['cywyxm'] ?? null,
  1413. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1414. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1415. ];
  1416. }
  1417. /**
  1418. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1419. *
  1420. * @return array{po:?array<string,mixed>, hidden:bool}
  1421. */
  1422. protected function resolvePickRowPoContext(int $sid): array
  1423. {
  1424. $po = null;
  1425. try {
  1426. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1427. if (is_array($found)) {
  1428. $po = $found;
  1429. }
  1430. } catch (\Throwable $e) {
  1431. }
  1432. $hideSet = $this->loadPickHiddenScydgySet();
  1433. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1434. }
  1435. /**
  1436. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1437. */
  1438. protected function assertPickRowCanDelete(int $sid, array $row): void
  1439. {
  1440. $ctx = $this->resolvePickRowPoContext($sid);
  1441. $po = $ctx['po'];
  1442. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1443. return;
  1444. }
  1445. if (is_array($po)) {
  1446. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1447. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1448. }
  1449. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1450. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1451. }
  1452. }
  1453. if ($ctx['hidden']) {
  1454. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1455. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1456. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1457. }
  1458. }
  1459. /**
  1460. * 初选直接完结前校验
  1461. */
  1462. protected function assertPickRowCanComplete(int $sid, array $row): void
  1463. {
  1464. $ctx = $this->resolvePickRowPoContext($sid);
  1465. $po = $ctx['po'];
  1466. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1467. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1468. }
  1469. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1470. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1471. }
  1472. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1473. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1474. }
  1475. }
  1476. /**
  1477. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1478. */
  1479. protected function softDeleteProcuremenPickRow(array $row): void
  1480. {
  1481. $sid = $this->extractScydgyRowId($row);
  1482. if (!$this->isValidScydgyRowId($sid)) {
  1483. throw new \InvalidArgumentException('无效的行主键');
  1484. }
  1485. $this->assertPickRowCanDelete($sid, $row);
  1486. $po = $this->resolvePickRowPoContext($sid)['po'];
  1487. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1488. return;
  1489. }
  1490. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1491. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1492. }
  1493. $now = date('Y-m-d H:i:s');
  1494. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1495. if (is_array($exists)) {
  1496. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1497. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1498. } else {
  1499. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1500. $data['mod_rq'] = $now;
  1501. $data['createtime'] = $now;
  1502. Db::table('purchase_order')->insert($data);
  1503. $poIdLog = (int)Db::getLastInsID();
  1504. }
  1505. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1506. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1507. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1508. if ($gymcLog !== '') {
  1509. $logTail .= ' / ' . $gymcLog;
  1510. }
  1511. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1512. }
  1513. /**
  1514. * 手工新增协助工序(写入 purchase_order)
  1515. *
  1516. * @param array<string, mixed> $params
  1517. * @return int scydgy_id
  1518. */
  1519. protected function saveManualPickOrder(array $params): int
  1520. {
  1521. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1522. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1523. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1524. if ($ccydh === '') {
  1525. $ccydh = $this->allocateManualOrderCcydh();
  1526. }
  1527. $now = date('Y-m-d H:i:s');
  1528. $sid = $this->allocateManualScydgyId();
  1529. $data = [
  1530. 'scydgy_id' => $sid,
  1531. 'CCYDH' => $ccydh,
  1532. 'CYJMC' => $cyjmc,
  1533. 'CGYMC' => $cgymc,
  1534. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1535. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1536. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1537. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1538. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1539. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1540. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1541. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1542. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1543. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1544. 'createtime' => $now,
  1545. 'dStamp' => $now,
  1546. 'dputrecord' => $now,
  1547. ];
  1548. Db::table('purchase_order')->insert($data);
  1549. $poId = (int)Db::getLastInsID();
  1550. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1551. return $sid;
  1552. }
  1553. protected function formatProcuremenRowLabel(array $row): string
  1554. {
  1555. $dh = trim((string)($row['CCYDH'] ?? ''));
  1556. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1557. if ($dh !== '' && $gymc !== '') {
  1558. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1559. }
  1560. if ($dh !== '') {
  1561. return '订单「' . $dh . '」';
  1562. }
  1563. if ($gymc !== '') {
  1564. return '工序「' . $gymc . '」';
  1565. }
  1566. $id = $this->extractScydgyRowId($row);
  1567. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1568. }
  1569. /**
  1570. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1571. */
  1572. protected function extractScydgyRowId(array $row): int
  1573. {
  1574. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1575. }
  1576. protected function isValidScydgyRowId(int $id): bool
  1577. {
  1578. return ProcuremenGuard::isValidScydgyId($id);
  1579. }
  1580. protected function isManualScydgyRowId(int $id): bool
  1581. {
  1582. return $id < 0;
  1583. }
  1584. /**
  1585. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1586. *
  1587. * @param int[] $scydgyIds
  1588. * @return array<int, string[]>
  1589. */
  1590. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1591. {
  1592. $out = [];
  1593. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1594. if ($scydgyIds === []) {
  1595. return $out;
  1596. }
  1597. try {
  1598. $rows = Db::table('purchase_order_detail')
  1599. ->where('scydgy_id', 'in', $scydgyIds)
  1600. ->field('scydgy_id,company_name')
  1601. ->order('company_name', 'asc')
  1602. ->select();
  1603. } catch (\Throwable $e) {
  1604. $rows = [];
  1605. }
  1606. if (!is_array($rows)) {
  1607. return $out;
  1608. }
  1609. foreach ($rows as $r) {
  1610. if (!is_array($r)) {
  1611. continue;
  1612. }
  1613. $sid = (int)($r['scydgy_id'] ?? 0);
  1614. $cn = trim((string)($r['company_name'] ?? ''));
  1615. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1616. continue;
  1617. }
  1618. if (!isset($out[$sid])) {
  1619. $out[$sid] = [];
  1620. }
  1621. if (!in_array($cn, $out[$sid], true)) {
  1622. $out[$sid][] = $cn;
  1623. }
  1624. }
  1625. return $out;
  1626. }
  1627. /**
  1628. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1629. *
  1630. * @param string[] $names
  1631. */
  1632. protected function formatNotifySupplierDisplay(array $names): string
  1633. {
  1634. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1635. return trim((string)$n);
  1636. }, $names))));
  1637. if ($names === []) {
  1638. return '';
  1639. }
  1640. sort($names, SORT_STRING);
  1641. return implode("\n", $names);
  1642. }
  1643. /**
  1644. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1645. *
  1646. * @param int[] $scydgyIds
  1647. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1648. */
  1649. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1650. {
  1651. $out = [];
  1652. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1653. if ($scydgyIds === []) {
  1654. return $out;
  1655. }
  1656. try {
  1657. $rows = Db::table('purchase_order_detail')
  1658. ->where('scydgy_id', 'in', $scydgyIds)
  1659. ->field('scydgy_id,company_name,amount')
  1660. ->select();
  1661. } catch (\Throwable $e) {
  1662. $rows = [];
  1663. }
  1664. if (!is_array($rows)) {
  1665. return $out;
  1666. }
  1667. foreach ($rows as $r) {
  1668. if (!is_array($r)) {
  1669. continue;
  1670. }
  1671. $sid = (int)($r['scydgy_id'] ?? 0);
  1672. $cn = trim((string)($r['company_name'] ?? ''));
  1673. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1674. continue;
  1675. }
  1676. if (!isset($out[$sid])) {
  1677. $out[$sid] = ['all' => [], 'quoted' => []];
  1678. }
  1679. $out[$sid]['all'][$cn] = true;
  1680. $am = trim((string)($r['amount'] ?? ''));
  1681. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1682. $out[$sid]['quoted'][$cn] = true;
  1683. }
  1684. }
  1685. return $out;
  1686. }
  1687. /**
  1688. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1689. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1690. */
  1691. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1692. {
  1693. $merged = ['all' => [], 'quoted' => []];
  1694. foreach ($buckets as $b) {
  1695. if (!is_array($b)) {
  1696. continue;
  1697. }
  1698. foreach ($b['all'] ?? [] as $cn => $_) {
  1699. $merged['all'][$cn] = true;
  1700. }
  1701. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1702. $merged['quoted'][$cn] = true;
  1703. }
  1704. }
  1705. return $merged;
  1706. }
  1707. /**
  1708. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1709. */
  1710. protected function formatQuotedSupplierLines(array $bucket): string
  1711. {
  1712. $all = array_keys($bucket['all'] ?? []);
  1713. if ($all === []) {
  1714. return '';
  1715. }
  1716. sort($all, SORT_STRING);
  1717. $lines = [];
  1718. foreach ($all as $cn) {
  1719. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1720. $lines[] = $cn . '(' . $status . ')';
  1721. }
  1722. return implode("\n", $lines);
  1723. }
  1724. /**
  1725. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1726. */
  1727. protected function resolveBundleSysRq(array $bundle): string
  1728. {
  1729. foreach ($bundle['pos'] ?? [] as $po) {
  1730. if (!is_array($po)) {
  1731. continue;
  1732. }
  1733. $sr = trim((string)($po['sys_rq'] ?? ''));
  1734. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1735. return $sr;
  1736. }
  1737. }
  1738. return '';
  1739. }
  1740. /**
  1741. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1742. */
  1743. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1744. {
  1745. $raw = trim((string)$sysRq);
  1746. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1747. return true;
  1748. }
  1749. $ts = strtotime(str_replace('T', ' ', $raw));
  1750. if ($ts === false || $ts <= 0) {
  1751. return true;
  1752. }
  1753. return time() >= $ts;
  1754. }
  1755. /**
  1756. * 开标前校验:必须已过报价截止时间
  1757. *
  1758. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1759. */
  1760. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1761. {
  1762. $sysRq = $this->resolveBundleSysRq($bundle);
  1763. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1764. $this->error('未到截止时间');
  1765. }
  1766. }
  1767. /**
  1768. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1769. *
  1770. * @param array<string, mixed> $line
  1771. */
  1772. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1773. {
  1774. $amountFilled = !empty($line['amount_filled']);
  1775. $deliveryFilled = !empty($line['delivery_filled']);
  1776. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1777. $line['amount_show'] = '';
  1778. if (array_key_exists('amount_text', $line)) {
  1779. $line['amount_text'] = $line['unit_price_text'];
  1780. }
  1781. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1782. $line['delivery_show'] = $deliveryText;
  1783. if (array_key_exists('delivery_text', $line)) {
  1784. $line['delivery_text'] = $deliveryText;
  1785. }
  1786. $line['delivery_ymd'] = '';
  1787. $line['subtotal_text'] = $amountFilled ? '' : '';
  1788. $line['subtotal_num'] = null;
  1789. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1790. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1791. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1792. $line['amount_filled'] = false;
  1793. $line['delivery_filled'] = false;
  1794. $line['is_quoted'] = false;
  1795. if (array_key_exists('quote_label', $line)) {
  1796. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未开标验证' : '未报价';
  1797. }
  1798. }
  1799. protected function ensurePurchaseOrderBidOpenTable(): void
  1800. {
  1801. try {
  1802. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1803. } catch (\Throwable $e) {
  1804. Db::execute(
  1805. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1806. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1807. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1808. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1809. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1810. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1811. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1812. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1813. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1814. `createtime` datetime DEFAULT NULL,
  1815. PRIMARY KEY (`id`),
  1816. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1817. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1818. );
  1819. }
  1820. }
  1821. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1822. {
  1823. $ccydh = trim($ccydh);
  1824. if ($ccydh === '') {
  1825. return false;
  1826. }
  1827. $this->ensurePurchaseOrderBidOpenTable();
  1828. try {
  1829. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1830. return is_array($row);
  1831. } catch (\Throwable $e) {
  1832. return false;
  1833. }
  1834. }
  1835. /**
  1836. * @param array{ccydh?:string} $bundle
  1837. */
  1838. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1839. {
  1840. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1841. }
  1842. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1843. {
  1844. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1845. }
  1846. protected function loadBidOpenAdminUser(int $adminId): ?array
  1847. {
  1848. if ($adminId <= 0) {
  1849. return null;
  1850. }
  1851. try {
  1852. $row = Db::name('admin')->where('id', $adminId)->find();
  1853. } catch (\Throwable $e) {
  1854. return null;
  1855. }
  1856. if (!is_array($row)) {
  1857. return null;
  1858. }
  1859. $status = strtolower(trim((string)($row['status'] ?? '')));
  1860. if ($status !== '' && $status !== 'normal') {
  1861. return null;
  1862. }
  1863. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  1864. return null;
  1865. }
  1866. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  1867. if (!preg_match('/^1\d{10}$/', $phone)) {
  1868. return null;
  1869. }
  1870. $name = trim((string)($row['nickname'] ?? ''));
  1871. if ($name === '') {
  1872. $name = trim((string)($row['username'] ?? ''));
  1873. }
  1874. return [
  1875. 'id' => (int)$row['id'],
  1876. 'username' => trim((string)($row['username'] ?? '')),
  1877. 'nickname' => $name,
  1878. 'mobile' => $phone,
  1879. ];
  1880. }
  1881. /**
  1882. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  1883. */
  1884. protected function bidOpenVerifierAuthGroupRootId(): int
  1885. {
  1886. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  1887. return $id > 0 ? $id : 10;
  1888. }
  1889. /**
  1890. * @return int[]
  1891. */
  1892. protected function loadBidOpenVerifierAuthGroupIds(): array
  1893. {
  1894. static $memo = [];
  1895. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  1896. if (isset($memo[$rootId])) {
  1897. return $memo[$rootId];
  1898. }
  1899. try {
  1900. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  1901. } catch (\Throwable $e) {
  1902. $memo[$rootId] = [$rootId];
  1903. return $memo[$rootId];
  1904. }
  1905. if (!is_array($groups) || $groups === []) {
  1906. $memo[$rootId] = [$rootId];
  1907. return $memo[$rootId];
  1908. }
  1909. $groupList = [];
  1910. foreach ($groups as $g) {
  1911. if (is_array($g)) {
  1912. $groupList[] = $g;
  1913. }
  1914. }
  1915. if ($groupList === []) {
  1916. $memo[$rootId] = [$rootId];
  1917. return $memo[$rootId];
  1918. }
  1919. $tree = \fast\Tree::instance();
  1920. $tree->init($groupList);
  1921. $ids = $tree->getChildrenIds($rootId, true);
  1922. if (!is_array($ids) || $ids === []) {
  1923. $memo[$rootId] = [$rootId];
  1924. return $memo[$rootId];
  1925. }
  1926. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  1927. return $memo[$rootId];
  1928. }
  1929. protected function isBidOpenVerifierAdmin(int $adminId): bool
  1930. {
  1931. if ($adminId <= 0) {
  1932. return false;
  1933. }
  1934. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1935. if ($groupIds === []) {
  1936. return false;
  1937. }
  1938. try {
  1939. return (bool)Db::name('auth_group_access')
  1940. ->where('uid', $adminId)
  1941. ->where('group_id', 'in', $groupIds)
  1942. ->count();
  1943. } catch (\Throwable $e) {
  1944. return false;
  1945. }
  1946. }
  1947. /**
  1948. * @return array<int, array<string, mixed>>
  1949. */
  1950. protected function listBidOpenVerifierCandidates(): array
  1951. {
  1952. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1953. if ($groupIds === []) {
  1954. return [];
  1955. }
  1956. try {
  1957. $adminIds = Db::name('auth_group_access')
  1958. ->where('group_id', 'in', $groupIds)
  1959. ->column('uid');
  1960. } catch (\Throwable $e) {
  1961. $adminIds = [];
  1962. }
  1963. $adminIds = is_array($adminIds)
  1964. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  1965. : [];
  1966. if ($adminIds === []) {
  1967. return [];
  1968. }
  1969. try {
  1970. $rows = Db::name('admin')
  1971. ->where('status', 'normal')
  1972. ->where('id', 'in', $adminIds)
  1973. ->where('mobile', '<>', '')
  1974. ->order('id', 'asc')
  1975. ->select();
  1976. } catch (\Throwable $e) {
  1977. return [];
  1978. }
  1979. if (!is_array($rows)) {
  1980. return [];
  1981. }
  1982. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  1983. $out = [];
  1984. foreach ($rows as $row) {
  1985. if (!is_array($row)) {
  1986. continue;
  1987. }
  1988. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  1989. if ($one === null) {
  1990. continue;
  1991. }
  1992. $out[] = [
  1993. 'id' => $one['id'],
  1994. 'username' => $one['username'],
  1995. 'nickname' => $one['nickname'],
  1996. 'group_name' => $groupNameMap[$one['id']] ?? '',
  1997. 'mobile' => mask_phone($one['mobile']),
  1998. ];
  1999. }
  2000. return $out;
  2001. }
  2002. /**
  2003. * @param int[] $adminIds
  2004. * @return array<int, string>
  2005. */
  2006. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2007. {
  2008. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2009. if ($adminIds === []) {
  2010. return [];
  2011. }
  2012. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2013. try {
  2014. $rows = Db::name('auth_group_access')
  2015. ->alias('aga')
  2016. ->join('auth_group ag', 'aga.group_id = ag.id')
  2017. ->where('aga.uid', 'in', $adminIds)
  2018. ->where('aga.group_id', 'in', $groupIds)
  2019. ->field('aga.uid,ag.name')
  2020. ->order('aga.uid', 'asc')
  2021. ->order('aga.group_id', 'asc')
  2022. ->select();
  2023. } catch (\Throwable $e) {
  2024. return [];
  2025. }
  2026. if (!is_array($rows)) {
  2027. return [];
  2028. }
  2029. $out = [];
  2030. foreach ($rows as $row) {
  2031. if (!is_array($row)) {
  2032. continue;
  2033. }
  2034. $uid = (int)($row['uid'] ?? 0);
  2035. $name = trim((string)($row['name'] ?? ''));
  2036. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2037. continue;
  2038. }
  2039. $out[$uid] = $name;
  2040. }
  2041. return $out;
  2042. }
  2043. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2044. {
  2045. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2046. }
  2047. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2048. {
  2049. return 'procuremen_bidopen_wait_' . $adminId;
  2050. }
  2051. protected function renderBidOpenVerifySms(string $code): string
  2052. {
  2053. $tpl = '';
  2054. try {
  2055. $row = $this->loadNotifyTemplateRow('bid_open');
  2056. if (is_array($row)) {
  2057. $tpl = trim((string)($row['content'] ?? ''));
  2058. }
  2059. } catch (\Throwable $e) {
  2060. $tpl = '';
  2061. }
  2062. if ($tpl === '') {
  2063. $tpl = '【可集达】您的短信验证码是{code}';
  2064. }
  2065. return str_replace('{code}', $code, $tpl);
  2066. }
  2067. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2068. {
  2069. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2070. }
  2071. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2072. {
  2073. $code = trim($code);
  2074. if (!preg_match('/^\d{6}$/', $code)) {
  2075. return false;
  2076. }
  2077. $mock = Config::get('mproc.mock_sms_code');
  2078. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2079. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2080. return true;
  2081. }
  2082. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2083. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2084. return false;
  2085. }
  2086. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2087. return true;
  2088. }
  2089. /**
  2090. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2091. */
  2092. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2093. {
  2094. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2095. if ($ccydh === '') {
  2096. throw new \InvalidArgumentException('订单号无效');
  2097. }
  2098. $this->ensurePurchaseOrderBidOpenTable();
  2099. list($operatorId, $operatorName) = $this->GetUseName();
  2100. $now = date('Y-m-d H:i:s');
  2101. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2102. $payload = [
  2103. 'ccydh' => $ccydh,
  2104. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2105. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2106. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2107. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2108. 'operator_id' => (int)$operatorId,
  2109. 'operator_name' => trim((string)$operatorName),
  2110. 'createtime' => $now,
  2111. ];
  2112. if (is_array($exists)) {
  2113. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2114. } else {
  2115. Db::table('purchase_order_bid_open')->insert($payload);
  2116. }
  2117. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2118. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2119. $orderPart = '(订单' . $ccydh . ')';
  2120. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2121. $seenSid = [];
  2122. foreach ($bundle['pos'] ?? [] as $poRow) {
  2123. if (!is_array($poRow)) {
  2124. continue;
  2125. }
  2126. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2127. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2128. continue;
  2129. }
  2130. $seenSid[$sid] = true;
  2131. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2132. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2133. }
  2134. if ($seenSid === []) {
  2135. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2136. if ($this->isValidScydgyRowId($anchor)) {
  2137. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2138. }
  2139. }
  2140. }
  2141. /**
  2142. * 报价行展示字段默认值(模板安全访问)
  2143. *
  2144. * @param array<string, mixed> $line
  2145. * @return array<string, mixed>
  2146. */
  2147. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2148. {
  2149. if (!array_key_exists('amount_quote_pending', $line)) {
  2150. $line['amount_quote_pending'] = 0;
  2151. }
  2152. if (!array_key_exists('delivery_quote_pending', $line)) {
  2153. $line['delivery_quote_pending'] = 0;
  2154. }
  2155. if (!array_key_exists('quote_before_deadline', $line)) {
  2156. $line['quote_before_deadline'] = 0;
  2157. }
  2158. if (!array_key_exists('amount_filled', $line)) {
  2159. $line['amount_filled'] = 0;
  2160. }
  2161. if (!array_key_exists('delivery_filled', $line)) {
  2162. $line['delivery_filled'] = 0;
  2163. }
  2164. return $line;
  2165. }
  2166. /**
  2167. * 审核弹窗:按供应商汇总报价明细
  2168. *
  2169. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2170. * @return array<int, array<string, mixed>>
  2171. */
  2172. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2173. {
  2174. $sids = [];
  2175. foreach ($bundle['pos'] ?? [] as $po) {
  2176. if (!is_array($po)) {
  2177. continue;
  2178. }
  2179. $sid = (int)($po['scydgy_id'] ?? 0);
  2180. if ($this->isValidScydgyRowId($sid)) {
  2181. $sids[$sid] = true;
  2182. }
  2183. }
  2184. if ($sids === []) {
  2185. return [];
  2186. }
  2187. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2188. $gymcMap = [];
  2189. $qtyBySid = [];
  2190. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2191. if (!is_array($mr)) {
  2192. continue;
  2193. }
  2194. $gid = $this->extractScydgyRowId($mr);
  2195. if ($this->isValidScydgyRowId($gid)) {
  2196. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2197. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2198. if ($qty === '') {
  2199. $qty = trim((string)($mr['NGZL'] ?? ''));
  2200. }
  2201. $qtyBySid[$gid] = $qty;
  2202. }
  2203. }
  2204. foreach ($bundle['pos'] ?? [] as $po) {
  2205. if (!is_array($po)) {
  2206. continue;
  2207. }
  2208. $gid = (int)($po['scydgy_id'] ?? 0);
  2209. if ($this->isValidScydgyRowId($gid)) {
  2210. $nm = trim((string)($po['CGYMC'] ?? ''));
  2211. if ($nm !== '') {
  2212. $gymcMap[$gid] = $nm;
  2213. }
  2214. }
  2215. }
  2216. try {
  2217. $detailsQuery = Db::table('purchase_order_detail')
  2218. ->where('scydgy_id', 'in', array_keys($sids));
  2219. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2220. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2221. } catch (\Throwable $e) {
  2222. try {
  2223. $detailsQuery = Db::table('purchase_order_detail')
  2224. ->where('scydgy_id', 'in', array_keys($sids));
  2225. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2226. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2227. } catch (\Throwable $e2) {
  2228. $details = [];
  2229. }
  2230. }
  2231. if (!is_array($details)) {
  2232. $details = [];
  2233. }
  2234. $byCompany = [];
  2235. foreach ($details as $d) {
  2236. if (!is_array($d)) {
  2237. continue;
  2238. }
  2239. $cn = trim((string)($d['company_name'] ?? ''));
  2240. if ($cn === '') {
  2241. continue;
  2242. }
  2243. if (!isset($byCompany[$cn])) {
  2244. $ph = trim((string)($d['phone'] ?? ''));
  2245. $username = trim((string)($d['username'] ?? ''));
  2246. if ($username === '') {
  2247. $username = $this->resolveCustomerContactName($ph, $cn);
  2248. }
  2249. $byCompany[$cn] = [
  2250. 'name' => $cn,
  2251. 'email' => trim((string)($d['email'] ?? '')),
  2252. 'phone' => $ph,
  2253. 'username' => $username,
  2254. 'has_quote' => false,
  2255. 'lines' => [],
  2256. ];
  2257. }
  2258. $sid = (int)($d['scydgy_id'] ?? 0);
  2259. $am = trim((string)($d['amount'] ?? ''));
  2260. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2261. if ($gymc === '') {
  2262. $gymc = '工序';
  2263. }
  2264. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2265. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2266. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2267. $deliveryShow = $deliveryRaw;
  2268. }
  2269. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2270. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2271. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2272. $subtotal = null;
  2273. if ($amountNum !== null) {
  2274. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2275. }
  2276. $unitPriceText = $amountFilled
  2277. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2278. : '未填写';
  2279. $lineRow = [
  2280. 'cgymc' => $gymc,
  2281. 'amount' => $am,
  2282. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2283. 'amount_filled' => $amountFilled,
  2284. 'unit_price_text' => $unitPriceText,
  2285. 'delivery' => $deliveryRaw,
  2286. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2287. 'delivery_filled' => $deliveryFilled,
  2288. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2289. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2290. 'subtotal_num' => $subtotal,
  2291. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2292. 'is_quoted' => $amountFilled,
  2293. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2294. ];
  2295. if (!$quoteVisible) {
  2296. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2297. }
  2298. $byCompany[$cn]['lines'][] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2299. }
  2300. foreach ($byCompany as $cn => $g) {
  2301. $total = count($g['lines']);
  2302. $quoted = 0;
  2303. $groupTotal = 0.0;
  2304. $groupHasTotal = false;
  2305. if ($quoteVisible) {
  2306. foreach ($g['lines'] as $ln) {
  2307. $am = trim((string)($ln['amount'] ?? ''));
  2308. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2309. $quoted++;
  2310. }
  2311. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2312. $groupTotal += (float)$ln['subtotal_num'];
  2313. $groupHasTotal = true;
  2314. }
  2315. }
  2316. }
  2317. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2318. $byCompany[$cn]['line_count'] = $total;
  2319. $byCompany[$cn]['has_total'] = $total > 0;
  2320. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2321. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  2322. }
  2323. return array_values($byCompany);
  2324. }
  2325. /**
  2326. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2327. *
  2328. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2329. * @return array<int, array<string, mixed>>
  2330. */
  2331. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2332. {
  2333. $sids = [];
  2334. $poIdMap = [];
  2335. foreach ($bundle['pos'] ?? [] as $po) {
  2336. if (!is_array($po)) {
  2337. continue;
  2338. }
  2339. $sid = (int)($po['scydgy_id'] ?? 0);
  2340. if ($this->isValidScydgyRowId($sid)) {
  2341. $sids[$sid] = true;
  2342. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2343. }
  2344. }
  2345. if ($sids === []) {
  2346. return [];
  2347. }
  2348. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2349. $gymcMap = [];
  2350. $qtyBySid = [];
  2351. $orderedSids = [];
  2352. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2353. if (!is_array($mr)) {
  2354. continue;
  2355. }
  2356. $gid = $this->extractScydgyRowId($mr);
  2357. if ($this->isValidScydgyRowId($gid)) {
  2358. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2359. $orderedSids[] = $gid;
  2360. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2361. if ($qty === '') {
  2362. $qty = trim((string)($mr['NGZL'] ?? ''));
  2363. }
  2364. $qtyBySid[$gid] = $qty;
  2365. }
  2366. }
  2367. foreach ($bundle['pos'] ?? [] as $po) {
  2368. if (!is_array($po)) {
  2369. continue;
  2370. }
  2371. $gid = (int)($po['scydgy_id'] ?? 0);
  2372. if ($this->isValidScydgyRowId($gid)) {
  2373. $nm = trim((string)($po['CGYMC'] ?? ''));
  2374. if ($nm !== '') {
  2375. $gymcMap[$gid] = $nm;
  2376. }
  2377. }
  2378. }
  2379. try {
  2380. $details = Db::table('purchase_order_detail')
  2381. ->where('scydgy_id', 'in', array_keys($sids))
  2382. ->order('company_name', 'asc')
  2383. ->order('id', 'asc')
  2384. ->select();
  2385. } catch (\Throwable $e) {
  2386. try {
  2387. $details = Db::table('purchase_order_detail')
  2388. ->where('scydgy_id', 'in', array_keys($sids))
  2389. ->order('company_name', 'asc')
  2390. ->order('ID', 'asc')
  2391. ->select();
  2392. } catch (\Throwable $e2) {
  2393. $details = [];
  2394. }
  2395. }
  2396. if (!is_array($details)) {
  2397. $details = [];
  2398. }
  2399. $byCompany = [];
  2400. foreach ($details as $d) {
  2401. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2402. continue;
  2403. }
  2404. $cn = trim((string)($d['company_name'] ?? ''));
  2405. if ($cn === '') {
  2406. continue;
  2407. }
  2408. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2409. $sid = (int)($d['scydgy_id'] ?? 0);
  2410. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2411. continue;
  2412. }
  2413. if (!isset($byCompany[$cn])) {
  2414. $ph = trim((string)($d['phone'] ?? ''));
  2415. $username = trim((string)($d['username'] ?? ''));
  2416. if ($username === '') {
  2417. $username = $this->resolveCustomerContactName($ph, $cn);
  2418. }
  2419. $byCompany[$cn] = [
  2420. 'name' => $cn,
  2421. 'email' => trim((string)($d['email'] ?? '')),
  2422. 'phone' => $ph,
  2423. 'username' => $username,
  2424. 'pick_lines' => [],
  2425. 'detail_picks' => [],
  2426. ];
  2427. }
  2428. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2429. if ($gymc === '') {
  2430. $gymc = '工序';
  2431. }
  2432. $am = trim((string)($d['amount'] ?? ''));
  2433. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2434. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2435. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2436. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2437. $deliveryShow = $deliveryRaw;
  2438. }
  2439. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2440. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2441. $subtotal = null;
  2442. if ($amountNum !== null) {
  2443. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2444. }
  2445. $unitPriceText = $amountFilled
  2446. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2447. : '未填写';
  2448. $pickLine = [
  2449. 'cgymc' => $gymc,
  2450. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2451. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2452. 'amount_filled' => $amountFilled,
  2453. 'delivery_filled' => $deliveryFilled,
  2454. 'unit_price_text' => $unitPriceText,
  2455. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2456. 'subtotal_num' => $subtotal,
  2457. 'is_quoted' => $amountFilled,
  2458. ];
  2459. if (!$quoteVisible) {
  2460. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2461. }
  2462. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2463. $byCompany[$cn]['detail_picks'][$sid] = [
  2464. 'scydgy_id' => $sid,
  2465. 'detail_id' => $detailId,
  2466. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2467. 'cgymc' => $gymc,
  2468. ];
  2469. }
  2470. $out = [];
  2471. foreach ($byCompany as $g) {
  2472. $pickLinesMap = $g['pick_lines'] ?? [];
  2473. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2474. continue;
  2475. }
  2476. $pickLines = [];
  2477. $usedLineSids = [];
  2478. foreach ($orderedSids as $sid) {
  2479. if (!isset($pickLinesMap[$sid])) {
  2480. continue;
  2481. }
  2482. $pickLines[] = $pickLinesMap[$sid];
  2483. $usedLineSids[$sid] = true;
  2484. }
  2485. foreach ($pickLinesMap as $sid => $ln) {
  2486. if (isset($usedLineSids[$sid])) {
  2487. continue;
  2488. }
  2489. $pickLines[] = $ln;
  2490. }
  2491. $groupTotal = 0.0;
  2492. $groupHasTotal = false;
  2493. if ($quoteVisible) {
  2494. foreach ($pickLines as $ln) {
  2495. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2496. $groupTotal += (float)$ln['subtotal_num'];
  2497. $groupHasTotal = true;
  2498. }
  2499. }
  2500. }
  2501. $lineCount = count($pickLines);
  2502. $g['pick_lines'] = $pickLines;
  2503. $g['line_count'] = $lineCount;
  2504. $g['has_total'] = $lineCount > 0;
  2505. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2506. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  2507. $detailPicks = $g['detail_picks'] ?? [];
  2508. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  2509. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2510. unset($g['detail_picks']);
  2511. $out[] = $g;
  2512. }
  2513. return $out;
  2514. }
  2515. /**
  2516. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2517. * @return array<int, int[]> scydgy_id => detail_id[]
  2518. */
  2519. protected function mapDetailIdsByScydgyId(array $details): array
  2520. {
  2521. $out = [];
  2522. foreach ($details as $d) {
  2523. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2524. continue;
  2525. }
  2526. $sid = (int)($d['scydgy_id'] ?? 0);
  2527. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2528. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2529. continue;
  2530. }
  2531. if (!isset($out[$sid])) {
  2532. $out[$sid] = [];
  2533. }
  2534. $out[$sid][] = $pk;
  2535. }
  2536. foreach ($out as $sid => $ids) {
  2537. $out[$sid] = array_values(array_unique($ids));
  2538. }
  2539. return $out;
  2540. }
  2541. /**
  2542. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2543. *
  2544. * @param array<string, mixed> $dbRow
  2545. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2546. */
  2547. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2548. {
  2549. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2550. $r = [
  2551. 'ID' => $sid,
  2552. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2553. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2554. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2555. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2556. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2557. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2558. 'CDW' => $dbRow['CDW'] ?? '',
  2559. 'NGZL' => $dbRow['NGZL'] ?? '',
  2560. 'CDF' => $dbRow['CDF'] ?? '',
  2561. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2562. 'MBZ' => $dbRow['MBZ'] ?? '',
  2563. 'bwjg' => $dbRow['bwjg'] ?? '',
  2564. 'iStatus' => $dbRow['iStatus'] ?? '',
  2565. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2566. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2567. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2568. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2569. 'dStamp' => $dbRow['dStamp'] ?? '',
  2570. 'pick_time' => $dbRow['pick_time'] ?? '',
  2571. ];
  2572. if ($sid > 0 && isset($dStampMap[$sid])) {
  2573. $t = trim((string)$dStampMap[$sid]);
  2574. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2575. $r['dStamp'] = $dStampMap[$sid];
  2576. }
  2577. }
  2578. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2579. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2580. $ct = $dbRow['createtime'];
  2581. if (is_numeric($ct) && (int)$ct > 946684800) {
  2582. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2583. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2584. $r['dStamp'] = trim($ct);
  2585. }
  2586. }
  2587. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2588. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2589. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2590. $fallback = trim((string)($r['dStamp'] ?? ''));
  2591. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2592. $r['dputrecord'] = $fallback;
  2593. }
  2594. }
  2595. if (array_key_exists('id', $dbRow)) {
  2596. $r['purchase_order_id'] = (int)$dbRow['id'];
  2597. }
  2598. if ($sid < 0) {
  2599. $r['_is_manual'] = 1;
  2600. }
  2601. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2602. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2603. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2604. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2605. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2606. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2607. $r['pick_time'] = $pickFallback;
  2608. break;
  2609. }
  2610. }
  2611. }
  2612. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2613. if ($pickNm !== '') {
  2614. $r['pick_company_name'] = $pickNm;
  2615. $r['picked_supplier_name'] = $pickNm;
  2616. }
  2617. return $r;
  2618. }
  2619. /**
  2620. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2621. *
  2622. * @return array<int, array<string, mixed>>
  2623. */
  2624. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2625. {
  2626. $pool = [];
  2627. if (!is_array($dbRows) || $dbRows === []) {
  2628. return $pool;
  2629. }
  2630. $dStampMap = [];
  2631. $sidList = [];
  2632. foreach ($dbRows as $tmpRow) {
  2633. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2634. $sid = (int)$tmpRow['scydgy_id'];
  2635. if ($sid > 0) {
  2636. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2637. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2638. $sidList[$sid] = true;
  2639. }
  2640. }
  2641. }
  2642. }
  2643. if ($sidList !== []) {
  2644. try {
  2645. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2646. } catch (\Throwable $e) {
  2647. $dStampMap = [];
  2648. }
  2649. }
  2650. foreach ($dbRows as $dbRow) {
  2651. if (!is_array($dbRow)) {
  2652. continue;
  2653. }
  2654. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2655. }
  2656. return $pool;
  2657. }
  2658. /**
  2659. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2660. *
  2661. * @param int[] $scydgyIds
  2662. * @return array<int, array<string, mixed>>
  2663. */
  2664. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2665. {
  2666. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2667. if ($scydgyIds === []) {
  2668. return [];
  2669. }
  2670. try {
  2671. $list = Db::table('purchase_order_detail')
  2672. ->where('scydgy_id', 'in', $scydgyIds)
  2673. ->field('scydgy_id,company_name,amount,delivery')
  2674. ->select();
  2675. } catch (\Throwable $e) {
  2676. $list = [];
  2677. }
  2678. return is_array($list) ? $list : [];
  2679. }
  2680. /**
  2681. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2682. *
  2683. * @param int[] $scydgyIds
  2684. * @param array<int, array<string, mixed>> $allRows
  2685. * @return array{cnt:int, amt:int, deliv:int}
  2686. */
  2687. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2688. {
  2689. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2690. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2691. if ($scydgyIds === [] || $allRows === []) {
  2692. return $out;
  2693. }
  2694. $idSet = array_flip($scydgyIds);
  2695. $all = [];
  2696. $withAmt = [];
  2697. $withDeliv = [];
  2698. foreach ($allRows as $r) {
  2699. if (!is_array($r)) {
  2700. continue;
  2701. }
  2702. $sid = (int)($r['scydgy_id'] ?? 0);
  2703. if (!isset($idSet[$sid])) {
  2704. continue;
  2705. }
  2706. $cn = trim((string)($r['company_name'] ?? ''));
  2707. if ($cn === '') {
  2708. continue;
  2709. }
  2710. $all[$cn] = true;
  2711. $am = $r['amount'] ?? null;
  2712. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2713. $withAmt[$cn] = true;
  2714. }
  2715. $dv = $r['delivery'] ?? null;
  2716. if ($dv !== null && trim((string)$dv) !== '') {
  2717. $withDeliv[$cn] = true;
  2718. }
  2719. }
  2720. return [
  2721. 'cnt' => count($all),
  2722. 'amt' => count($withAmt),
  2723. 'deliv' => count($withDeliv),
  2724. ];
  2725. }
  2726. /**
  2727. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2728. *
  2729. * @param int[] $scydgyIds
  2730. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2731. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2732. */
  2733. protected function OrderDetailSummary(array $scydgyIds)
  2734. {
  2735. $out = [];
  2736. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2737. if ($scydgyIds === []) {
  2738. return $out;
  2739. }
  2740. $list = [];
  2741. try {
  2742. $list = Db::table('purchase_order_detail')
  2743. ->where('scydgy_id', 'in', $scydgyIds)
  2744. ->field('id,scydgy_id,amount,delivery')
  2745. ->select();
  2746. } catch (\Throwable $e) {
  2747. $list = [];
  2748. }
  2749. if (!is_array($list)) {
  2750. return $out;
  2751. }
  2752. foreach ($list as $r) {
  2753. if (!is_array($r)) {
  2754. continue;
  2755. }
  2756. $ids = (int)($r['scydgy_id'] ?? 0);
  2757. if (!$this->isValidScydgyRowId($ids)) {
  2758. continue;
  2759. }
  2760. if (!isset($out[$ids])) {
  2761. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2762. }
  2763. $out[$ids]['cnt']++;
  2764. $am = $r['amount'] ?? null;
  2765. if ($am !== null && $am !== '') {
  2766. if (!(is_string($am) && trim($am) === '')) {
  2767. $out[$ids]['amt']++;
  2768. }
  2769. }
  2770. $dv = $r['delivery'] ?? null;
  2771. if ($dv !== null && trim((string)$dv) !== '') {
  2772. $out[$ids]['deliv']++;
  2773. }
  2774. }
  2775. return $out;
  2776. }
  2777. /**
  2778. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2779. *
  2780. * @return array
  2781. */
  2782. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2783. {
  2784. $strContains = function ($haystack, $needle) {
  2785. if ($needle === '') {
  2786. return false;
  2787. }
  2788. $haystack = (string)$haystack;
  2789. if (function_exists('mb_stripos')) {
  2790. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2791. }
  2792. return stripos($haystack, $needle) !== false;
  2793. };
  2794. $stripAlias = function ($f) {
  2795. return preg_replace('/^[ab]\./i', '', (string)$f);
  2796. };
  2797. $searchColNames = [];
  2798. foreach (explode(',', $this->searchFields) as $colRaw) {
  2799. $c = $stripAlias(trim($colRaw));
  2800. if ($c !== '') {
  2801. $searchColNames[] = $c;
  2802. }
  2803. }
  2804. $filtered = [];
  2805. foreach ($pool as $r) {
  2806. if (!is_array($r)) {
  2807. continue;
  2808. }
  2809. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2810. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2811. if (!$isManual) {
  2812. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2813. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2814. continue;
  2815. }
  2816. if ($applyMonthRange) {
  2817. $mo = (int)$m[2];
  2818. if ($mo < 1 || $mo > 12) {
  2819. continue;
  2820. }
  2821. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2822. $rowMonthStart = $ymRow . '-01 00:00:00';
  2823. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2824. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2825. continue;
  2826. }
  2827. }
  2828. } elseif ($applyMonthRange) {
  2829. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2830. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2831. $ds = $listTime;
  2832. }
  2833. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2834. continue;
  2835. }
  2836. $mo = (int)$m[2];
  2837. if ($mo < 1 || $mo > 12) {
  2838. continue;
  2839. }
  2840. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2841. $rowMonthStart = $ymRow . '-01 00:00:00';
  2842. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2843. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2844. continue;
  2845. }
  2846. }
  2847. if ($search !== '') {
  2848. $hitSearch = false;
  2849. foreach ($searchColNames as $c) {
  2850. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2851. if ($cell !== '' && $strContains($cell, $search)) {
  2852. $hitSearch = true;
  2853. break;
  2854. }
  2855. }
  2856. if (!$hitSearch) {
  2857. continue;
  2858. }
  2859. }
  2860. foreach ($filterArr as $fk => $fv) {
  2861. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2862. continue;
  2863. }
  2864. if (is_array($fv)) {
  2865. continue;
  2866. }
  2867. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2868. continue;
  2869. }
  2870. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2871. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2872. $field = $stripAlias($fk);
  2873. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2874. $cellStr = trim((string)$cell);
  2875. switch ($sym) {
  2876. case '=':
  2877. if ((string)$cell !== (string)$fv) {
  2878. continue 3;
  2879. }
  2880. break;
  2881. case '<>':
  2882. if ((string)$cell === (string)$fv) {
  2883. continue 3;
  2884. }
  2885. break;
  2886. case 'LIKE':
  2887. case 'NOT LIKE':
  2888. $needle = trim((string)$fv);
  2889. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2890. if ($sym === 'LIKE' && !$hit) {
  2891. continue 3;
  2892. }
  2893. if ($sym === 'NOT LIKE' && $hit) {
  2894. continue 3;
  2895. }
  2896. break;
  2897. case '>':
  2898. case '>=':
  2899. case '<':
  2900. case '<=':
  2901. if (!is_numeric($cell) && $cellStr === '') {
  2902. continue 3;
  2903. }
  2904. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2905. $vv = (float)$fv;
  2906. if ($sym === '>' && !($cv > $vv)) {
  2907. continue 3;
  2908. }
  2909. if ($sym === '>=' && !($cv >= $vv)) {
  2910. continue 3;
  2911. }
  2912. if ($sym === '<' && !($cv < $vv)) {
  2913. continue 3;
  2914. }
  2915. if ($sym === '<=' && !($cv <= $vv)) {
  2916. continue 3;
  2917. }
  2918. break;
  2919. case 'RANGE':
  2920. case 'NOT RANGE':
  2921. case 'BETWEEN':
  2922. case 'NOT BETWEEN':
  2923. case 'BETWEEN TIME':
  2924. case 'NOT BETWEEN TIME':
  2925. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2926. $rawR = str_replace(' - ', ',', $rawR);
  2927. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2928. if (count($arr) < 2) {
  2929. break;
  2930. }
  2931. $lo = $arr[0];
  2932. $hi = $arr[1];
  2933. if ($lo === '' && $hi === '') {
  2934. break;
  2935. }
  2936. $isNot = (strpos($sym, 'NOT') !== false);
  2937. if ($lo === '') {
  2938. $in = ($cellStr !== '' && $cellStr <= $hi);
  2939. if ($isNot ? $in : !$in) {
  2940. continue 3;
  2941. }
  2942. break;
  2943. }
  2944. if ($hi === '') {
  2945. $in = ($cellStr !== '' && $cellStr >= $lo);
  2946. if ($isNot ? $in : !$in) {
  2947. continue 3;
  2948. }
  2949. break;
  2950. }
  2951. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2952. if ($isNot ? $in : !$in) {
  2953. continue 3;
  2954. }
  2955. break;
  2956. case 'NULL':
  2957. case 'IS NULL':
  2958. if ($cell !== null && $cell !== '') {
  2959. continue 3;
  2960. }
  2961. break;
  2962. case 'NOT NULL':
  2963. case 'IS NOT NULL':
  2964. if ($cell === null || $cell === '') {
  2965. continue 3;
  2966. }
  2967. break;
  2968. default:
  2969. break;
  2970. }
  2971. }
  2972. $filtered[] = $r;
  2973. }
  2974. return $filtered;
  2975. }
  2976. /**
  2977. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2978. */
  2979. public function snapshotToProcure()
  2980. {
  2981. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2982. $this->error(__('Invalid parameters'));
  2983. }
  2984. $row = json_decode($this->request->post('row_json', ''), true);
  2985. if (!is_array($row)) {
  2986. $this->error(__('Invalid parameters'));
  2987. }
  2988. try {
  2989. $ids = $this->extractScydgyRowId($row);
  2990. if (!$this->isValidScydgyRowId($ids)) {
  2991. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2992. }
  2993. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2994. $data = [
  2995. 'scydgy_id' => $ids,
  2996. 'CCYDH' => $row['CCYDH'] ?? null,
  2997. 'CYJMC' => $row['CYJMC'] ?? null,
  2998. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2999. 'CDXMC' => $row['CDXMC'] ?? null,
  3000. 'CGYBH' => $row['CGYBH'] ?? null,
  3001. 'CGYMC' => $row['CGYMC'] ?? null,
  3002. 'CDW' => $row['CDW'] ?? null,
  3003. 'NGZL' => $row['NGZL'] ?? null,
  3004. 'CDF' => $row['CDF'] ?? null,
  3005. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3006. 'MBZ' => $row['MBZ'] ?? null,
  3007. 'bwjg' => $row['bwjg'] ?? null,
  3008. 'iStatus' => $row['iStatus'] ?? null,
  3009. 'dStamp' => $row['dStamp'] ?? null,
  3010. 'dputrecord' => $row['dputrecord'] ?? null,
  3011. 'cywyxm' => $row['cywyxm'] ?? null,
  3012. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3013. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3014. ];
  3015. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3016. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3017. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3018. $this->success('操作成功');
  3019. return;
  3020. }
  3021. if ($exists) {
  3022. $upd = $data;
  3023. unset($upd['scydgy_id'], $upd['status']);
  3024. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3025. } else {
  3026. // 新增:不写 status(空/走库默认);仅写创建时间
  3027. $data['createtime'] = date('Y-m-d H:i:s');
  3028. Db::table('purchase_order')->insert($data);
  3029. }
  3030. } catch (\Throwable $e) {
  3031. $this->error($e->getMessage());
  3032. }
  3033. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3034. $this->success('操作成功');
  3035. }
  3036. /**
  3037. * 未发列表
  3038. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3039. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3040. */
  3041. public function completeDirectly()
  3042. {
  3043. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3044. $this->error(__('参数错误'));
  3045. }
  3046. if (!$this->procuremenCanComplete()) {
  3047. $this->error(__('You have no permission'));
  3048. }
  3049. $row = json_decode($this->request->post('row_json', ''), true);
  3050. if (!is_array($row)) {
  3051. $this->error(__('Invalid parameters'));
  3052. }
  3053. $finishRaw = $this->request->post('finish', '1');
  3054. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3055. $poIdLog = null;
  3056. try {
  3057. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3058. $ids = $this->extractScydgyRowId($row);
  3059. if (!$this->isValidScydgyRowId($ids)) {
  3060. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3061. }
  3062. if ($asComplete) {
  3063. $this->assertPickRowCanComplete($ids, $row);
  3064. }
  3065. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3066. $data = [
  3067. 'scydgy_id' => $ids,
  3068. 'CCYDH' => $row['CCYDH'] ?? null,
  3069. 'CYJMC' => $row['CYJMC'] ?? null,
  3070. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3071. 'CDXMC' => $row['CDXMC'] ?? null,
  3072. 'CGYBH' => $row['CGYBH'] ?? null,
  3073. 'CGYMC' => $row['CGYMC'] ?? null,
  3074. 'CDW' => $row['CDW'] ?? null,
  3075. 'NGZL' => $row['NGZL'] ?? null,
  3076. 'CDF' => $row['CDF'] ?? null,
  3077. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3078. 'MBZ' => $row['MBZ'] ?? null,
  3079. 'bwjg' => $row['bwjg'] ?? null,
  3080. 'iStatus' => $row['iStatus'] ?? null,
  3081. 'dStamp' => $row['dStamp'] ?? null,
  3082. 'dputrecord' => $row['dputrecord'] ?? null,
  3083. 'cywyxm' => $row['cywyxm'] ?? null,
  3084. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3085. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3086. ];
  3087. if ($asComplete) {
  3088. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3089. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3090. }
  3091. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3092. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3093. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3094. $this->success('操作成功');
  3095. return;
  3096. }
  3097. if ($exists) {
  3098. $upd = $data;
  3099. unset($upd['scydgy_id']);
  3100. if (!$asComplete) {
  3101. unset($upd['status']);
  3102. }
  3103. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3104. } else {
  3105. // 新增:不写 status;完结时 $data 已含 status=1
  3106. $data['createtime'] = date('Y-m-d H:i:s');
  3107. Db::table('purchase_order')->insert($data);
  3108. }
  3109. } catch (\Throwable $e) {
  3110. $this->error($e->getMessage());
  3111. }
  3112. try {
  3113. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3114. if (is_array($rpo)) {
  3115. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3116. $poIdLog = $tid > 0 ? $tid : null;
  3117. }
  3118. } catch (\Throwable $e) {
  3119. $poIdLog = null;
  3120. }
  3121. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3122. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3123. if ($asComplete) {
  3124. $this->addOrderLog(
  3125. $ids,
  3126. 'mark_complete',
  3127. '点击「完结」,已标记为已完结',
  3128. $poIdLog
  3129. );
  3130. try {
  3131. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3132. if ($pdfPublicPath === '') {
  3133. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3134. }
  3135. } catch (\Throwable $e) {
  3136. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3137. }
  3138. } else {
  3139. $this->addOrderLog(
  3140. $ids,
  3141. 'save_qty_price',
  3142. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3143. $poIdLog
  3144. );
  3145. }
  3146. $this->pickHiddenScydgySetCache = null;
  3147. $this->success("操作成功");
  3148. }
  3149. /**
  3150. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3151. *
  3152. * @param array<int, array> $rows 引用传递当前页行
  3153. */
  3154. protected function mergePurchaseOrder(array &$rows)
  3155. {
  3156. if ($rows === []) {
  3157. return;
  3158. }
  3159. $ids = [];
  3160. foreach ($rows as $rw) {
  3161. if (!is_array($rw)) {
  3162. continue;
  3163. }
  3164. $id = (int)($rw['ID'] ?? 0);
  3165. if ($id > 0) {
  3166. $ids[$id] = true;
  3167. }
  3168. }
  3169. $idList = array_keys($ids);
  3170. if ($idList === []) {
  3171. return;
  3172. }
  3173. try {
  3174. $list = Db::table('purchase_order')
  3175. ->where('scydgy_id', 'in', $idList)
  3176. ->field('scydgy_id,This_quantity,ceilingPrice')
  3177. ->select();
  3178. } catch (\Throwable $e) {
  3179. return;
  3180. }
  3181. if (!is_array($list)) {
  3182. return;
  3183. }
  3184. $byId = [];
  3185. foreach ($list as $dbRow) {
  3186. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3187. continue;
  3188. }
  3189. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3190. }
  3191. foreach ($rows as &$rw) {
  3192. if (!is_array($rw)) {
  3193. continue;
  3194. }
  3195. $sid = (int)($rw['ID'] ?? 0);
  3196. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3197. continue;
  3198. }
  3199. $db = $byId[$sid];
  3200. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  3201. $rw['This_quantity'] = $db['This_quantity'];
  3202. }
  3203. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  3204. $rw['ceilingPrice'] = $db['ceilingPrice'];
  3205. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  3206. $rw['ceilingPrice'] = $db['ceiling_price'];
  3207. }
  3208. }
  3209. unset($rw);
  3210. }
  3211. /**
  3212. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3213. */
  3214. public function purchaseConfirmPick()
  3215. {
  3216. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3217. $this->error(__('Invalid parameters'));
  3218. }
  3219. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3220. $this->error(__('You have no permission'));
  3221. }
  3222. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3223. if ($batchRaw !== '') {
  3224. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3225. return;
  3226. }
  3227. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3228. $sid = (int)$scydgyId;
  3229. if (!$this->isValidScydgyRowId($sid)) {
  3230. $this->error('参数无效');
  3231. }
  3232. $parseIdList = function ($raw) {
  3233. if (is_array($raw)) {
  3234. $arr = $raw;
  3235. } else {
  3236. $decoded = json_decode((string)$raw, true);
  3237. $arr = is_array($decoded) ? $decoded : [];
  3238. }
  3239. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3240. };
  3241. $selectedRaw = $this->request->post('selected_ids', null);
  3242. if ($selectedRaw === null || $selectedRaw === '') {
  3243. $legacy = (int)$this->request->post('selected_id', 0);
  3244. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3245. } else {
  3246. $selectedIds = $parseIdList($selectedRaw);
  3247. }
  3248. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3249. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3250. try {
  3251. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3252. } catch (\InvalidArgumentException $e) {
  3253. $this->error($e->getMessage());
  3254. } catch (\Throwable $e) {
  3255. $this->error($e->getMessage());
  3256. }
  3257. $this->pickHiddenScydgySetCache = null;
  3258. $this->success('操作成功', '', $result);
  3259. }
  3260. /**
  3261. * 整单采购确认(多道工序一次提交)
  3262. */
  3263. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3264. {
  3265. $decoded = json_decode($batchRaw, true);
  3266. if (!is_array($decoded) || $decoded === []) {
  3267. $this->error('提交数据无效');
  3268. }
  3269. $picks = [];
  3270. foreach ($decoded as $item) {
  3271. if (!is_array($item)) {
  3272. continue;
  3273. }
  3274. $sid = (int)($item['scydgy_id'] ?? 0);
  3275. if (!$this->isValidScydgyRowId($sid)) {
  3276. continue;
  3277. }
  3278. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3279. if (!is_array($sel)) {
  3280. $sel = [(int)$sel];
  3281. }
  3282. $unsel = $item['unselected_ids'] ?? [];
  3283. if (!is_array($unsel)) {
  3284. $unsel = json_decode((string)$unsel, true);
  3285. $unsel = is_array($unsel) ? $unsel : [];
  3286. }
  3287. $picks[] = [
  3288. 'scydgy_id' => $sid,
  3289. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3290. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3291. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3292. ];
  3293. }
  3294. if ($picks === []) {
  3295. $this->error('提交数据无效');
  3296. }
  3297. Db::startTrans();
  3298. $results = [];
  3299. try {
  3300. foreach ($picks as $pick) {
  3301. $results[] = $this->runPurchaseConfirmPick(
  3302. (int)$pick['scydgy_id'],
  3303. $pick['selected_ids'],
  3304. $pick['unselected_ids'],
  3305. (int)$pick['purchase_order_id'],
  3306. false,
  3307. false
  3308. );
  3309. }
  3310. Db::commit();
  3311. } catch (\Throwable $e) {
  3312. Db::rollback();
  3313. $msg = $e->getMessage();
  3314. $this->error($msg !== '' ? $msg : '提交失败');
  3315. }
  3316. try {
  3317. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3318. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3319. } catch (\Throwable $e) {
  3320. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3321. }
  3322. $this->pickHiddenScydgySetCache = null;
  3323. $this->success('操作成功', '', ['batch' => $results]);
  3324. }
  3325. /**
  3326. * @return array<string, mixed>
  3327. */
  3328. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3329. {
  3330. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3331. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3332. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3333. $scydgyId = (string)$sid;
  3334. if ($selectedIds === []) {
  3335. throw new \InvalidArgumentException('请至少勾选一条明细');
  3336. }
  3337. $inter = array_intersect($selectedIds, $unselectedIds);
  3338. if ($inter !== []) {
  3339. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3340. }
  3341. $allIds = $this->purchaseOrderDetail($sid);
  3342. if ($allIds === []) {
  3343. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3344. }
  3345. foreach ($selectedIds as $id) {
  3346. if (!in_array($id, $allIds, true)) {
  3347. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3348. }
  3349. }
  3350. foreach ($unselectedIds as $id) {
  3351. if (!in_array($id, $allIds, true)) {
  3352. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3353. }
  3354. }
  3355. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3356. sort($union, SORT_NUMERIC);
  3357. $expect = $allIds;
  3358. sort($expect, SORT_NUMERIC);
  3359. if ($union !== $expect) {
  3360. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3361. }
  3362. if ($manageTransaction) {
  3363. Db::startTrans();
  3364. }
  3365. try {
  3366. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3367. $aff = 0;
  3368. try {
  3369. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3370. } catch (\Throwable $e) {
  3371. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3372. }
  3373. if ($aff < 1) {
  3374. throw new \Exception('更新选中状态失败');
  3375. }
  3376. $poPayload = [
  3377. 'status' => ProcuremenStatus::PO_COMPLETED,
  3378. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3379. ];
  3380. if ($purchaseOrderId > 0) {
  3381. $poAff = (int)Db::table('purchase_order')
  3382. ->where('id', $purchaseOrderId)
  3383. ->where('scydgy_id', $sid)
  3384. ->update($poPayload);
  3385. if ($poAff < 1) {
  3386. throw new \Exception('主表订单不存在或与工序行不匹配');
  3387. }
  3388. } else {
  3389. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3390. if ($poAff < 1) {
  3391. throw new \Exception('未找到');
  3392. }
  3393. }
  3394. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3395. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3396. if ($manageTransaction) {
  3397. Db::commit();
  3398. }
  3399. } catch (\Throwable $e) {
  3400. if ($manageTransaction) {
  3401. Db::rollback();
  3402. }
  3403. throw $e;
  3404. }
  3405. $poIdFinal = $purchaseOrderId;
  3406. if ($poIdFinal <= 0) {
  3407. try {
  3408. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3409. if (is_array($rpo)) {
  3410. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3411. }
  3412. } catch (\Throwable $e) {
  3413. $poIdFinal = 0;
  3414. }
  3415. }
  3416. $pickNames = [];
  3417. foreach ($selectedIds as $pid) {
  3418. $dr = $this->purchaseOrderDetai($sid, $pid);
  3419. $nm = trim((string)($dr['company_name'] ?? ''));
  3420. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3421. }
  3422. $this->addOrderLog(
  3423. $sid,
  3424. 'purchase_confirm',
  3425. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3426. $poIdFinal > 0 ? $poIdFinal : null
  3427. );
  3428. if ($sendNotifications) {
  3429. try {
  3430. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3431. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3432. 'scydgy_id' => $sid,
  3433. 'selected_ids' => $selectedIds,
  3434. 'unselected_ids' => $unselectedIds,
  3435. 'purchase_order_id' => $purchaseOrderId,
  3436. ]]);
  3437. } catch (\Throwable $e) {
  3438. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3439. }
  3440. }
  3441. Log::write(sprintf(
  3442. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3443. $scydgyId,
  3444. $purchaseOrderId,
  3445. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3446. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3447. ), 'notice');
  3448. $pdfPublicPath = '';
  3449. try {
  3450. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3451. } catch (\Throwable $e) {
  3452. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3453. }
  3454. return [
  3455. 'scydgy_id' => $scydgyId,
  3456. 'purchase_order_id' => $purchaseOrderId,
  3457. 'selected_ids' => $selectedIds,
  3458. 'unselected_ids' => $unselectedIds,
  3459. 'purchase_confirm_pdf' => $pdfPublicPath,
  3460. ];
  3461. }
  3462. /**
  3463. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3464. *
  3465. * @param int[]|string[] $scydgyIds
  3466. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3467. */
  3468. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3469. {
  3470. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3471. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3472. if ($scydgyIds === []) {
  3473. return $empty;
  3474. }
  3475. $pos = [];
  3476. try {
  3477. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3478. } catch (\Throwable $e) {
  3479. $rows = [];
  3480. }
  3481. if (is_array($rows)) {
  3482. foreach ($rows as $po) {
  3483. if (is_array($po)) {
  3484. $pos[] = $po;
  3485. }
  3486. }
  3487. }
  3488. if ($pos === []) {
  3489. return $empty;
  3490. }
  3491. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3492. return [
  3493. 'ccydh' => $ccydh,
  3494. 'pos' => $pos,
  3495. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3496. ];
  3497. }
  3498. /**
  3499. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3500. *
  3501. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3502. * @param array<int, array<string, mixed>> $picks
  3503. */
  3504. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3505. {
  3506. if ($picks === []) {
  3507. return;
  3508. }
  3509. $fallbackDetailId = 0;
  3510. $winners = [];
  3511. $losers = [];
  3512. foreach ($picks as $pick) {
  3513. if (!is_array($pick)) {
  3514. continue;
  3515. }
  3516. $sid = (int)($pick['scydgy_id'] ?? 0);
  3517. if (!$this->isValidScydgyRowId($sid)) {
  3518. continue;
  3519. }
  3520. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3521. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3522. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3523. $fallbackDetailId = (int)$selectedIds[0];
  3524. }
  3525. foreach ($selectedIds as $pid) {
  3526. $dr = $this->purchaseOrderDetai($sid, $pid);
  3527. if (!is_array($dr)) {
  3528. continue;
  3529. }
  3530. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3531. }
  3532. foreach ($unselectedIds as $pid) {
  3533. $dr = $this->purchaseOrderDetai($sid, $pid);
  3534. if (!is_array($dr)) {
  3535. continue;
  3536. }
  3537. $key = $this->notifySupplierDedupeKey($dr);
  3538. if (!isset($winners[$key])) {
  3539. $losers[$key] = $dr;
  3540. }
  3541. }
  3542. }
  3543. if ($winners === [] && $losers === []) {
  3544. return;
  3545. }
  3546. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3547. $sendSmsSafe = function ($phone, $content) {
  3548. $phone = trim((string)$phone);
  3549. if ($phone === '') {
  3550. return;
  3551. }
  3552. try {
  3553. $this->smsbao($phone, $content);
  3554. } catch (\Throwable $e) {
  3555. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3556. }
  3557. };
  3558. foreach ($winners as $dr) {
  3559. $cname = trim((string)($dr['company_name'] ?? ''));
  3560. $ph = trim((string)($dr['phone'] ?? ''));
  3561. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3562. 'company_name' => $cname,
  3563. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3564. 'phone' => $ph,
  3565. ]));
  3566. $sendSmsSafe($ph, $sms);
  3567. }
  3568. foreach ($losers as $dr) {
  3569. $cname = trim((string)($dr['company_name'] ?? ''));
  3570. $ph = trim((string)($dr['phone'] ?? ''));
  3571. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3572. 'company_name' => $cname,
  3573. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3574. 'phone' => $ph,
  3575. ]));
  3576. $sendSmsSafe($ph, $sms);
  3577. }
  3578. }
  3579. /**
  3580. * 短信去重键:优先手机号,否则公司名
  3581. */
  3582. protected function notifySupplierDedupeKey(array $detailRow): string
  3583. {
  3584. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3585. if ($ph !== '') {
  3586. return 'p:' . $ph;
  3587. }
  3588. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3589. return 'c:' . $cn;
  3590. }
  3591. /**
  3592. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3593. *
  3594. * @param int[] $detailIds
  3595. */
  3596. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3597. {
  3598. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3599. if ($detailIds === []) {
  3600. return;
  3601. }
  3602. $payload = ['status_name' => $statusName];
  3603. try {
  3604. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3605. } catch (\Throwable $e) {
  3606. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3607. }
  3608. }
  3609. /**
  3610. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3611. */
  3612. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3613. {
  3614. try {
  3615. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3616. } catch (\Throwable $e) {
  3617. return;
  3618. }
  3619. if (!is_array($rows)) {
  3620. return;
  3621. }
  3622. foreach ($rows as $dr) {
  3623. if (!is_array($dr)) {
  3624. continue;
  3625. }
  3626. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3627. if ($id <= 0) {
  3628. continue;
  3629. }
  3630. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3631. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3632. try {
  3633. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3634. } catch (\Throwable $e) {
  3635. }
  3636. }
  3637. }
  3638. /**
  3639. * @param array<string, mixed> $detailRow
  3640. */
  3641. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3642. {
  3643. $am = $detailRow['amount'] ?? null;
  3644. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3645. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3646. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3647. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3648. }
  3649. /**
  3650. * @return int[]
  3651. */
  3652. protected function purchaseOrderDetail(int $scydgyId): array
  3653. {
  3654. if (!$this->isValidScydgyRowId($scydgyId)) {
  3655. return [];
  3656. }
  3657. try {
  3658. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3659. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3660. $list = $listQuery->select();
  3661. } catch (\Throwable $e) {
  3662. return [];
  3663. }
  3664. if (!is_array($list)) {
  3665. return [];
  3666. }
  3667. $ids = [];
  3668. foreach ($list as $r) {
  3669. if (!is_array($r)) {
  3670. continue;
  3671. }
  3672. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3673. if ($pk > 0) {
  3674. $ids[] = $pk;
  3675. }
  3676. }
  3677. return array_values(array_unique($ids));
  3678. }
  3679. /**
  3680. * 获取当前登录用户信息 [id, 展示名]
  3681. */
  3682. protected function GetUseName(): array
  3683. {
  3684. $id = 0;
  3685. $name = '';
  3686. try {
  3687. if ($this->auth && $this->auth->isLogin()) {
  3688. $u = $this->auth->getUserInfo();
  3689. if (is_array($u)) {
  3690. $id = (int)($u['id'] ?? 0);
  3691. $name = trim((string)($u['nickname'] ?? ''));
  3692. if ($name === '') {
  3693. $name = trim((string)($u['username'] ?? ''));
  3694. }
  3695. }
  3696. }
  3697. } catch (\Throwable $e) {
  3698. }
  3699. if ($name === '') {
  3700. $name = '未知用户';
  3701. }
  3702. return [$id, $name];
  3703. }
  3704. /**
  3705. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3706. */
  3707. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3708. {
  3709. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3710. }
  3711. /**
  3712. * 按主键取一条
  3713. */
  3714. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3715. {
  3716. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3717. return [];
  3718. }
  3719. try {
  3720. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3721. if (is_array($one)) {
  3722. return $one;
  3723. }
  3724. } catch (\Throwable $e) {
  3725. }
  3726. try {
  3727. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3728. if (is_array($one)) {
  3729. return $one;
  3730. }
  3731. } catch (\Throwable $e) {
  3732. }
  3733. return [];
  3734. }
  3735. /**
  3736. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3737. */
  3738. protected function formatProcuremenDetailTime($v): string
  3739. {
  3740. if ($v === null || $v === '') {
  3741. return '';
  3742. }
  3743. if (is_numeric($v) && (int)$v > 946684800) {
  3744. return date('Y-m-d H:i:s', (int)$v);
  3745. }
  3746. return ProcuremenTime::formatDisplayDateTime($v);
  3747. }
  3748. /**
  3749. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3750. */
  3751. protected function formatDeliveryYmd($v): string
  3752. {
  3753. if ($v === null || $v === '') {
  3754. return '';
  3755. }
  3756. $s = trim((string)$v);
  3757. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3758. return '';
  3759. }
  3760. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3761. return $m[1];
  3762. }
  3763. $ts = strtotime($s);
  3764. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3765. }
  3766. /**
  3767. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3768. */
  3769. protected function detailRowSupplierOperated(array $r): bool
  3770. {
  3771. $am = $r['amount'] ?? null;
  3772. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3773. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3774. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3775. return $okAmt || $okDel;
  3776. }
  3777. /**
  3778. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3779. */
  3780. protected function resolveDetailSupplierOperTime(array $r): string
  3781. {
  3782. if (!$this->detailRowSupplierOperated($r)) {
  3783. return '';
  3784. }
  3785. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3786. if ($t !== '') {
  3787. return $t;
  3788. }
  3789. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3790. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3791. continue;
  3792. }
  3793. $t = $this->formatProcuremenDetailTime($r[$col]);
  3794. if ($t !== '') {
  3795. return $t;
  3796. }
  3797. }
  3798. return '';
  3799. }
  3800. /**
  3801. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3802. */
  3803. protected function detailRowSupplierAccepted(array $r): bool
  3804. {
  3805. $am = $r['amount'] ?? null;
  3806. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3807. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3808. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3809. return $okAmt && $okDel;
  3810. }
  3811. /**
  3812. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3813. */
  3814. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3815. {
  3816. if ($detailCount > 0) {
  3817. return true;
  3818. }
  3819. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3820. return true;
  3821. }
  3822. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3823. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3824. return true;
  3825. }
  3826. return false;
  3827. }
  3828. /**
  3829. * 下发时间:优先 pick_time,其次首条下发明细时间
  3830. */
  3831. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3832. {
  3833. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3834. if ($issueTime !== '') {
  3835. return $issueTime;
  3836. }
  3837. foreach ($details as $dr) {
  3838. if (!is_array($dr)) {
  3839. continue;
  3840. }
  3841. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3842. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3843. $issueTime = $t;
  3844. }
  3845. }
  3846. if ($issueTime !== '') {
  3847. return $issueTime;
  3848. }
  3849. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3850. }
  3851. /**
  3852. * 直接点「完结」时间:优先操作记录 mark_complete
  3853. */
  3854. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3855. {
  3856. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  3857. }
  3858. /**
  3859. * 操作记录时间(取指定 action 最近一条)
  3860. *
  3861. * @param string|array<int, string> $actions
  3862. */
  3863. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3864. {
  3865. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  3866. }
  3867. /**
  3868. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3869. *
  3870. * @param array $main purchase_order 一行
  3871. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3872. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3873. */
  3874. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3875. {
  3876. $issueCnt = count($details);
  3877. $acceptCnt = 0;
  3878. $pickedName = '';
  3879. $pickedTime = '';
  3880. foreach ($details as $dr) {
  3881. if (!is_array($dr)) {
  3882. continue;
  3883. }
  3884. if ($this->detailRowSupplierAccepted($dr)) {
  3885. $acceptCnt++;
  3886. }
  3887. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3888. if ($pickedName === '') {
  3889. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3890. }
  3891. if ($pickedTime === '') {
  3892. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3893. if ($pickedTime === '') {
  3894. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3895. }
  3896. }
  3897. }
  3898. }
  3899. $hasMain = $main !== [];
  3900. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3901. if ($poTime === '') {
  3902. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3903. }
  3904. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3905. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3906. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3907. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3908. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3909. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3910. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3911. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3912. $supplierTime = '';
  3913. if ($acceptCnt > 0) {
  3914. foreach ($details as $dr) {
  3915. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3916. continue;
  3917. }
  3918. $t = $this->resolveDetailSupplierOperTime($dr);
  3919. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3920. $supplierTime = $t;
  3921. }
  3922. }
  3923. }
  3924. $directComplete = ($mainCompleted && !$issued);
  3925. $doneTime = '';
  3926. if ($mainCompleted) {
  3927. if ($directComplete) {
  3928. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3929. }
  3930. if ($doneTime === '') {
  3931. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3932. }
  3933. if ($doneTime === '') {
  3934. foreach ($details as $dr) {
  3935. if (!is_array($dr)) {
  3936. continue;
  3937. }
  3938. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3939. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3940. $doneTime = $t;
  3941. }
  3942. }
  3943. }
  3944. if ($doneTime === '') {
  3945. $doneTime = $poTime;
  3946. }
  3947. if ($confirmApproveTime !== '') {
  3948. $doneTime = $confirmApproveTime;
  3949. }
  3950. }
  3951. if ($directComplete) {
  3952. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3953. $step1Done = $hasMain;
  3954. $step2Done = false;
  3955. $step3Done = false;
  3956. $step4Done = false;
  3957. $step5Done = false;
  3958. $step6Done = true;
  3959. } else {
  3960. $step1Done = $issued;
  3961. $step2Done = $issued;
  3962. $step3Done = $acceptCnt > 0;
  3963. $step4Done = $wflowPendingApproval;
  3964. if (!$step4Done) {
  3965. foreach ($details as $dr) {
  3966. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3967. $step4Done = true;
  3968. break;
  3969. }
  3970. }
  3971. }
  3972. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3973. $step6Done = $mainCompleted;
  3974. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3975. if ($mainCompleted && $issued) {
  3976. $step3Done = true;
  3977. $step4Done = true;
  3978. $step5Done = true;
  3979. if ($supplierTime === '') {
  3980. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3981. if ($fillT !== '') {
  3982. $supplierTime = $fillT;
  3983. }
  3984. }
  3985. if ($pickedTime === '') {
  3986. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3987. if ($fillT !== '') {
  3988. $pickedTime = $fillT;
  3989. }
  3990. }
  3991. if ($auditSelectTime === '') {
  3992. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3993. if ($fillT !== '') {
  3994. $auditSelectTime = $fillT;
  3995. }
  3996. }
  3997. if ($confirmApproveTime === '') {
  3998. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3999. if ($fillT !== '') {
  4000. $confirmApproveTime = $fillT;
  4001. }
  4002. }
  4003. }
  4004. }
  4005. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4006. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4007. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4008. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4009. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4010. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4011. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4012. $steps = [
  4013. [
  4014. 'title' => '未发',
  4015. 'subtitle' => '',
  4016. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4017. 'done' => $step1Done,
  4018. ],
  4019. [
  4020. 'title' => '下发',
  4021. 'subtitle' => '',
  4022. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4023. 'done' => $step2Done,
  4024. ],
  4025. [
  4026. 'title' => '供应商接单',
  4027. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4028. 'time' => '',
  4029. 'done' => $step3Done,
  4030. ],
  4031. [
  4032. 'title' => '待确认',
  4033. 'subtitle' => $step4Done
  4034. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4035. : ($issued ? '待选供应商' : ''),
  4036. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4037. 'done' => $step4Done,
  4038. ],
  4039. [
  4040. 'title' => '待审批',
  4041. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4042. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4043. 'done' => $step5Done,
  4044. ],
  4045. [
  4046. 'title' => '已完结',
  4047. 'subtitle' => '',
  4048. 'time' => $step6Done ? $doneTime : '',
  4049. 'done' => $step6Done,
  4050. ],
  4051. ];
  4052. $currentIdx = count($steps) - 1;
  4053. if (!$directComplete) {
  4054. foreach ($steps as $i => $s) {
  4055. if (!$s['done']) {
  4056. $currentIdx = $i;
  4057. break;
  4058. }
  4059. }
  4060. }
  4061. $nSteps = count($steps);
  4062. foreach ($steps as $idx => &$s) {
  4063. $s['current'] = ($idx === $currentIdx);
  4064. if ($idx === 0) {
  4065. $s['pdf_left_bg'] = '';
  4066. } else {
  4067. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4068. }
  4069. if ($idx >= $nSteps - 1) {
  4070. $s['pdf_right_bg'] = '';
  4071. } else {
  4072. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4073. }
  4074. }
  4075. unset($s);
  4076. $labelMap = [
  4077. 'CCYDH' => '订单号',
  4078. 'CYJMC' => '印件名称',
  4079. 'CCLBMMC' => '承揽部门',
  4080. 'CGYMC' => '工序名称',
  4081. 'CDW' => '单位',
  4082. 'NGZL' => '工作量',
  4083. 'CDF' => '单价',
  4084. 'cGzzxMc' => '工作中心',
  4085. 'MBZ' => '备注',
  4086. 'This_quantity' => '本次数量',
  4087. 'ceilingPrice' => '最高限价',
  4088. ];
  4089. $orderSummary = [];
  4090. foreach ($labelMap as $key => $lab) {
  4091. if (!array_key_exists($key, $main)) {
  4092. continue;
  4093. }
  4094. $val = $main[$key];
  4095. if ($val === null) {
  4096. $val = '';
  4097. } elseif (!is_scalar($val)) {
  4098. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4099. } else {
  4100. $val = (string)$val;
  4101. }
  4102. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4103. }
  4104. $orderSummaryGrid = [];
  4105. $n = count($orderSummary);
  4106. for ($i = 0; $i < $n; $i += 2) {
  4107. $left = $orderSummary[$i];
  4108. $hasRight = ($i + 1) < $n;
  4109. $orderSummaryGrid[] = [
  4110. 'l1' => $left['label'],
  4111. 'v1' => $left['value'],
  4112. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4113. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4114. ];
  4115. }
  4116. return [
  4117. 'steps' => $steps,
  4118. 'orderSummary' => $orderSummary,
  4119. 'orderSummaryGrid' => $orderSummaryGrid,
  4120. 'detailRows' => $details,
  4121. ];
  4122. }
  4123. /**
  4124. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4125. *
  4126. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4127. */
  4128. protected function prepareProcuremenDetailsView(string $ids): array
  4129. {
  4130. $main = [];
  4131. try {
  4132. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4133. $main = is_array($one) ? $one : [];
  4134. } catch (\Throwable $e) {
  4135. $main = [];
  4136. }
  4137. $details = [];
  4138. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4139. if ($mergeRows === []) {
  4140. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4141. if ($mergeRows === [] && $main !== []) {
  4142. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4143. }
  4144. }
  4145. $detailSidList = [];
  4146. $anchorSid = (int)$ids;
  4147. if ($anchorSid !== 0) {
  4148. $detailSidList[$anchorSid] = true;
  4149. }
  4150. foreach ($mergeRows as $mr) {
  4151. if (!is_array($mr)) {
  4152. continue;
  4153. }
  4154. $sid = $this->extractScydgyRowId($mr);
  4155. if ($sid !== 0) {
  4156. $detailSidList[$sid] = true;
  4157. }
  4158. }
  4159. try {
  4160. if ($detailSidList !== []) {
  4161. $details = Db::table('purchase_order_detail')
  4162. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4163. ->order('id', 'asc')
  4164. ->select();
  4165. }
  4166. } catch (\Throwable $e) {
  4167. $details = [];
  4168. }
  4169. if (!is_array($details)) {
  4170. $details = [];
  4171. }
  4172. foreach ($details as &$r) {
  4173. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4174. $r['id'] = $r['ID'];
  4175. }
  4176. if (isset($r['createtime'])) {
  4177. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4178. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4179. } else {
  4180. $r['createtime_text'] = (string)$r['createtime'];
  4181. }
  4182. } else {
  4183. $r['createtime_text'] = '';
  4184. }
  4185. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4186. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4187. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4188. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4189. if (is_array($r)) {
  4190. $r = $this->maskSupplierContactFields($r);
  4191. }
  4192. }
  4193. unset($r);
  4194. $activeDetails = [];
  4195. foreach ($details as $r) {
  4196. if (is_array($r) && empty($r['is_void'])) {
  4197. $activeDetails[] = $r;
  4198. }
  4199. }
  4200. $operLogs = [];
  4201. try {
  4202. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4203. } catch (\Throwable $e) {
  4204. $operLogs = [];
  4205. }
  4206. if (!is_array($operLogs)) {
  4207. $operLogs = [];
  4208. }
  4209. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4210. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4211. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4212. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4213. if ($ccydh === '') {
  4214. foreach ($details as $r) {
  4215. if (!is_array($r)) {
  4216. continue;
  4217. }
  4218. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4219. if ($ccydh !== '') {
  4220. break;
  4221. }
  4222. }
  4223. }
  4224. $this->view->assign('ccydh', $ccydh);
  4225. $this->view->assign('steps', $bundle['steps']);
  4226. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4227. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4228. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4229. $this->view->assign('processCount', count($mergeRows));
  4230. $this->view->assign('detailRows', $details);
  4231. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4232. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4233. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4234. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4235. $this->view->assign('operLogs', $operLogs);
  4236. return [
  4237. 'ok' => $main !== [] || $details !== [],
  4238. 'ccydh' => $ccydh,
  4239. ];
  4240. }
  4241. /**
  4242. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4243. */
  4244. public function details()
  4245. {
  4246. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4247. if (is_array($ids)) {
  4248. $ids = isset($ids[0]) ? $ids[0] : '';
  4249. }
  4250. $ids = trim((string)$ids);
  4251. if ($ids === '') {
  4252. $this->error(__('Invalid parameters'));
  4253. }
  4254. $this->assertManualOrderDetailsViewable((int)$ids);
  4255. $this->prepareProcuremenDetailsView($ids);
  4256. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4257. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4258. $this->view->engine->layout(false);
  4259. try {
  4260. return $this->view->fetch('procuremen/details_dialog_shell');
  4261. } finally {
  4262. if ($restoreLayout) {
  4263. $this->view->engine->layout($restoreLayout);
  4264. }
  4265. }
  4266. }
  4267. /**
  4268. * 解析合并审核工序行(订单号须一致,且均未协助)
  4269. *
  4270. * @return array<int, array<string, mixed>>
  4271. */
  4272. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4273. {
  4274. $primary = json_decode($rowJson, true);
  4275. if (!is_array($primary)) {
  4276. $this->error(__('Invalid parameters'));
  4277. }
  4278. $merge = json_decode($mergeRowsJson, true);
  4279. if (!is_array($merge) || $merge === []) {
  4280. $merge = [$primary];
  4281. }
  4282. $seen = [];
  4283. $out = [];
  4284. foreach ($merge as $r) {
  4285. if (!is_array($r)) {
  4286. continue;
  4287. }
  4288. $id = $this->extractScydgyRowId($r);
  4289. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4290. continue;
  4291. }
  4292. $seen[$id] = true;
  4293. $out[] = $r;
  4294. }
  4295. if ($out === []) {
  4296. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4297. }
  4298. $ccydh = null;
  4299. foreach ($out as $r) {
  4300. $dh = trim((string)($r['CCYDH'] ?? ''));
  4301. if ($ccydh === null) {
  4302. $ccydh = $dh;
  4303. } elseif ($dh !== $ccydh) {
  4304. $this->error('合并审核要求所选行的订单号一致');
  4305. }
  4306. }
  4307. $ids = [];
  4308. foreach ($out as $r) {
  4309. $id = $this->extractScydgyRowId($r);
  4310. if ($this->isValidScydgyRowId($id)) {
  4311. $ids[$id] = true;
  4312. }
  4313. }
  4314. $poBySid = [];
  4315. $detCntBySid = [];
  4316. if ($ids !== []) {
  4317. $idList = array_keys($ids);
  4318. try {
  4319. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4320. if (is_array($poList)) {
  4321. foreach ($poList as $po) {
  4322. if (!is_array($po)) {
  4323. continue;
  4324. }
  4325. $sid = (int)($po['scydgy_id'] ?? 0);
  4326. if ($this->isValidScydgyRowId($sid)) {
  4327. $poBySid[$sid] = $po;
  4328. }
  4329. }
  4330. }
  4331. } catch (\Throwable $e) {
  4332. }
  4333. try {
  4334. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4335. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4336. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4337. if (is_array($detRows)) {
  4338. foreach ($detRows as $dr) {
  4339. if (!is_array($dr)) {
  4340. continue;
  4341. }
  4342. $sid = (int)($dr['scydgy_id'] ?? 0);
  4343. if ($this->isValidScydgyRowId($sid)) {
  4344. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4345. }
  4346. }
  4347. }
  4348. } catch (\Throwable $e) {
  4349. }
  4350. }
  4351. foreach ($out as $r) {
  4352. $id = $this->extractScydgyRowId($r);
  4353. if (!$this->isValidScydgyRowId($id)) {
  4354. continue;
  4355. }
  4356. $po = $poBySid[$id] ?? null;
  4357. if (!is_array($po)) {
  4358. continue;
  4359. }
  4360. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4361. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4362. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4363. }
  4364. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4365. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4366. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4367. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4368. }
  4369. }
  4370. return $out;
  4371. }
  4372. /**
  4373. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4374. */
  4375. protected function maskSupplierContactFields(array $item): array
  4376. {
  4377. if (array_key_exists('email', $item)) {
  4378. $item['email'] = mask_email((string)$item['email']);
  4379. }
  4380. if (array_key_exists('phone', $item)) {
  4381. $item['phone'] = mask_phone((string)$item['phone']);
  4382. }
  4383. return $item;
  4384. }
  4385. /**
  4386. * @param array<int, array<string, mixed>> $list
  4387. * @return array<int, array<string, mixed>>
  4388. */
  4389. protected function maskSupplierContactList(array $list): array
  4390. {
  4391. $out = [];
  4392. foreach ($list as $item) {
  4393. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4394. }
  4395. return $out;
  4396. }
  4397. /**
  4398. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4399. *
  4400. * @return array<string, string>|null
  4401. */
  4402. protected function buildCustomerContactPayloadFromRow($row): ?array
  4403. {
  4404. if (!is_array($row)) {
  4405. return null;
  4406. }
  4407. $norm = [];
  4408. foreach ($row as $k => $v) {
  4409. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4410. }
  4411. $row = $norm;
  4412. $st = $row['status'] ?? '';
  4413. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4414. return null;
  4415. }
  4416. $companyName = '';
  4417. foreach (['company_name', 'name'] as $nk) {
  4418. if (!empty($row[$nk])) {
  4419. $companyName = trim((string)$row[$nk]);
  4420. break;
  4421. }
  4422. }
  4423. if ($companyName === '') {
  4424. return null;
  4425. }
  4426. $username = '';
  4427. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4428. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4429. $username = trim((string)$row[$uk]);
  4430. break;
  4431. }
  4432. }
  4433. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4434. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4435. if ($phone === '' && isset($row['account'])) {
  4436. $phone = trim((string)$row['account']);
  4437. }
  4438. if ($phone === '' && isset($row['mobile'])) {
  4439. $phone = trim((string)$row['mobile']);
  4440. }
  4441. if ($email === '' && $phone === '') {
  4442. return null;
  4443. }
  4444. $category = '';
  4445. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4446. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4447. $category = trim((string)$row[$ck]);
  4448. break;
  4449. }
  4450. }
  4451. return [
  4452. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4453. 'name' => $companyName,
  4454. 'company_name' => $companyName,
  4455. 'username' => $username,
  4456. 'email' => $email,
  4457. 'phone' => $phone,
  4458. 'category' => $category,
  4459. 'company_type' => $category,
  4460. ];
  4461. }
  4462. /**
  4463. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4464. */
  4465. protected function resolveCustomerContactById(string $id): ?array
  4466. {
  4467. $id = trim($id);
  4468. if ($id === '' || !ctype_digit($id)) {
  4469. return null;
  4470. }
  4471. try {
  4472. $row = Db::table('customer')->where('id', (int)$id)->find();
  4473. } catch (\Throwable $e) {
  4474. return null;
  4475. }
  4476. return $this->buildCustomerContactPayloadFromRow($row);
  4477. }
  4478. /**
  4479. * 按供应商名称解析联系信息(兼容旧提交数据)
  4480. */
  4481. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4482. {
  4483. $name = trim($name);
  4484. if ($name === '') {
  4485. return null;
  4486. }
  4487. try {
  4488. $row = Db::table('customer')
  4489. ->where(function ($q) use ($name) {
  4490. $q->where('company_name', $name)->whereOr('name', $name);
  4491. })
  4492. ->order('id', 'desc')
  4493. ->find();
  4494. } catch (\Throwable $e) {
  4495. return null;
  4496. }
  4497. return $this->buildCustomerContactPayloadFromRow($row);
  4498. }
  4499. /**
  4500. * 规范化下发/确认时勾选的供应商
  4501. *
  4502. * @param array<int, mixed> $companies
  4503. * @return array<int, array<string, string>>
  4504. */
  4505. protected function normalizePickCompanies(array $companies): array
  4506. {
  4507. $out = [];
  4508. foreach ($companies as $c) {
  4509. if (!is_array($c)) {
  4510. continue;
  4511. }
  4512. $resolved = null;
  4513. $cid = trim((string)($c['id'] ?? ''));
  4514. if ($cid !== '') {
  4515. $resolved = $this->resolveCustomerContactById($cid);
  4516. }
  4517. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4518. if ($resolved === null && $name !== '') {
  4519. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4520. }
  4521. if ($resolved === null) {
  4522. continue;
  4523. }
  4524. $out[] = $resolved;
  4525. }
  4526. return $out;
  4527. }
  4528. /**
  4529. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4530. *
  4531. * @param array<int, array<string, mixed>> $pool
  4532. * @return array<int, array<string, mixed>>
  4533. */
  4534. protected function collapseProcuremenPoolByOrder(array $pool): array
  4535. {
  4536. if ($pool === []) {
  4537. return [];
  4538. }
  4539. $groups = [];
  4540. foreach ($pool as $row) {
  4541. if (!is_array($row)) {
  4542. continue;
  4543. }
  4544. $dh = trim((string)($row['CCYDH'] ?? ''));
  4545. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4546. if (!isset($groups[$key])) {
  4547. $groups[$key] = [];
  4548. }
  4549. $groups[$key][] = $row;
  4550. }
  4551. $out = [];
  4552. foreach ($groups as $ccydh => $rows) {
  4553. if ($rows === []) {
  4554. continue;
  4555. }
  4556. usort($rows, function ($a, $b) {
  4557. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4558. });
  4559. $head = $rows[0];
  4560. $gymcList = [];
  4561. foreach ($rows as $r) {
  4562. $g = trim((string)($r['CGYMC'] ?? ''));
  4563. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4564. $gymcList[] = $g;
  4565. }
  4566. }
  4567. $merged = $head;
  4568. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4569. $merged['process_count'] = count($rows);
  4570. $merged['_order_merge_rows'] = $rows;
  4571. if (count($rows) > 1) {
  4572. $merged['CGYMC'] = implode('、', $gymcList);
  4573. }
  4574. $mergedPickTime = '';
  4575. foreach ($rows as $r) {
  4576. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4577. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4578. $mergedPickTime = $t;
  4579. }
  4580. }
  4581. if ($mergedPickTime !== '') {
  4582. $merged['pick_time'] = $mergedPickTime;
  4583. }
  4584. $out[] = $merged;
  4585. }
  4586. usort($out, function ($a, $b) {
  4587. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4588. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4589. if ($ta === $tb) {
  4590. $ida = (int)($a['purchase_order_id'] ?? 0);
  4591. $idb = (int)($b['purchase_order_id'] ?? 0);
  4592. if ($ida !== $idb) {
  4593. return $idb <=> $ida;
  4594. }
  4595. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4596. }
  4597. if ($ta === '') {
  4598. return 1;
  4599. }
  4600. if ($tb === '') {
  4601. return -1;
  4602. }
  4603. return strcmp($tb, $ta);
  4604. });
  4605. return $out;
  4606. }
  4607. /**
  4608. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4609. *
  4610. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4611. */
  4612. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4613. {
  4614. $scydgyId = trim($scydgyId);
  4615. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4616. if ($scydgyId === '') {
  4617. return $empty;
  4618. }
  4619. try {
  4620. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4621. } catch (\Throwable $e) {
  4622. $anchor = null;
  4623. }
  4624. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4625. return $empty;
  4626. }
  4627. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4628. if ($ccydh === '') {
  4629. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4630. }
  4631. try {
  4632. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4633. } catch (\Throwable $e) {
  4634. $pos = [$anchor];
  4635. }
  4636. if (!is_array($pos) || $pos === []) {
  4637. $pos = [$anchor];
  4638. }
  4639. return [
  4640. 'ccydh' => $ccydh,
  4641. 'pos' => $pos,
  4642. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4643. ];
  4644. }
  4645. /**
  4646. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4647. */
  4648. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4649. {
  4650. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4651. return false;
  4652. }
  4653. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4654. return false;
  4655. }
  4656. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4657. return true;
  4658. }
  4659. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4660. $sid = (int)($po['scydgy_id'] ?? 0);
  4661. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4662. }
  4663. return false;
  4664. }
  4665. /**
  4666. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4667. *
  4668. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4669. */
  4670. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4671. {
  4672. $scydgyId = trim($scydgyId);
  4673. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4674. if ($scydgyId === '') {
  4675. return $empty;
  4676. }
  4677. try {
  4678. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4679. } catch (\Throwable $e) {
  4680. $anchor = null;
  4681. }
  4682. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4683. return $empty;
  4684. }
  4685. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4686. if ($ccydh === '') {
  4687. return [
  4688. 'ccydh' => '',
  4689. 'pos' => [$anchor],
  4690. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4691. ];
  4692. }
  4693. try {
  4694. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4695. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4696. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4697. } catch (\Throwable $e) {
  4698. $pos = [$anchor];
  4699. }
  4700. if (!is_array($pos) || $pos === []) {
  4701. $pos = [$anchor];
  4702. }
  4703. $pos = array_values(array_filter($pos, function ($po) {
  4704. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4705. }));
  4706. if ($pos === []) {
  4707. $pos = [$anchor];
  4708. }
  4709. return [
  4710. 'ccydh' => $ccydh,
  4711. 'pos' => $pos,
  4712. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4713. ];
  4714. }
  4715. /**
  4716. * @param array<int, array<string, mixed>> $purchaseOrders
  4717. * @return array<int, array<string, mixed>>
  4718. */
  4719. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4720. {
  4721. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4722. $byId = [];
  4723. foreach ($pool as $r) {
  4724. if (!is_array($r)) {
  4725. continue;
  4726. }
  4727. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4728. if ($this->isValidScydgyRowId($sid)) {
  4729. $byId[$sid] = $r;
  4730. }
  4731. }
  4732. $out = [];
  4733. foreach ($purchaseOrders as $po) {
  4734. if (!is_array($po)) {
  4735. continue;
  4736. }
  4737. $sid = (int)($po['scydgy_id'] ?? 0);
  4738. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4739. $out[] = $byId[$sid];
  4740. }
  4741. }
  4742. return $out;
  4743. }
  4744. /**
  4745. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4746. *
  4747. * @return array<int, array<string, mixed>>
  4748. */
  4749. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4750. {
  4751. $scydgyId = trim($scydgyId);
  4752. if ($scydgyId === '') {
  4753. return [];
  4754. }
  4755. try {
  4756. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4757. } catch (\Throwable $e) {
  4758. $anchor = null;
  4759. }
  4760. if (!is_array($anchor)) {
  4761. return [];
  4762. }
  4763. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4764. return [];
  4765. }
  4766. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4767. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4768. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4769. try {
  4770. $q = Db::table('purchase_order');
  4771. if ($ccydh !== '') {
  4772. $q->where('CCYDH', $ccydh);
  4773. } else {
  4774. $q->where('scydgy_id', $scydgyId);
  4775. }
  4776. if ($isValidPick) {
  4777. $q->where('pick_time', $pickTime);
  4778. }
  4779. $pos = $q->order('scydgy_id', 'asc')->select();
  4780. } catch (\Throwable $e) {
  4781. $pos = [$anchor];
  4782. }
  4783. if (!is_array($pos) || $pos === []) {
  4784. $pos = [$anchor];
  4785. }
  4786. $pos = array_values(array_filter($pos, function ($po) {
  4787. if (!is_array($po)) {
  4788. return false;
  4789. }
  4790. $mr = $po['mod_rq'] ?? null;
  4791. if ($mr === null || $mr === '') {
  4792. return true;
  4793. }
  4794. $mrs = trim((string)$mr);
  4795. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4796. }));
  4797. if ($pos === []) {
  4798. $pos = [$anchor];
  4799. }
  4800. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4801. if ($rows === []) {
  4802. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4803. }
  4804. return $rows;
  4805. }
  4806. /**
  4807. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4808. *
  4809. * @param array<int, array<string, mixed>> $mergeRows
  4810. * @return array<int, array<string, mixed>>
  4811. */
  4812. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4813. {
  4814. $list = array_values($mergeRows);
  4815. $n = count($list);
  4816. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4817. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4818. $mergeSame = $n > 1 && $orderKey0 !== '';
  4819. if ($mergeSame) {
  4820. foreach ($list as $rr) {
  4821. if (!is_array($rr)) {
  4822. $mergeSame = false;
  4823. break;
  4824. }
  4825. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4826. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4827. $mergeSame = false;
  4828. break;
  4829. }
  4830. }
  4831. }
  4832. $out = [];
  4833. foreach ($list as $idx => $r) {
  4834. if (!is_array($r)) {
  4835. continue;
  4836. }
  4837. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4838. if (is_scalar($qty)) {
  4839. $qty = trim((string)$qty);
  4840. } else {
  4841. $qty = '';
  4842. }
  4843. if ($qty === '') {
  4844. $gzl = $r['NGZL'] ?? '';
  4845. if (is_scalar($gzl)) {
  4846. $qty = trim((string)$gzl);
  4847. }
  4848. }
  4849. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4850. $sid = $this->extractScydgyRowId($r);
  4851. $out[] = [
  4852. 'seq' => $idx + 1,
  4853. 'scydgy_id' => $sid,
  4854. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4855. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4856. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4857. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4858. 'NGZL' => $r['NGZL'] ?? '',
  4859. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4860. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4861. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4862. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4863. 'show_order_cells' => !$mergeSame || $idx === 0,
  4864. 'order_rowspan' => $mergeSame ? $n : 1,
  4865. ];
  4866. }
  4867. return $out;
  4868. }
  4869. /**
  4870. * 解析金额/数量(去千分位等非数字字符)
  4871. */
  4872. protected function parseProcuremenMoneyNumber($value): ?float
  4873. {
  4874. if ($value === null || $value === '') {
  4875. return null;
  4876. }
  4877. if (is_numeric($value)) {
  4878. return (float)$value;
  4879. }
  4880. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4881. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4882. }
  4883. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4884. {
  4885. if ($amount === null) {
  4886. return '';
  4887. }
  4888. return (string)(int)round($amount);
  4889. }
  4890. /**
  4891. * 列表/详情展示:工作量为 0 时显示空
  4892. */
  4893. protected function formatProcuremenWorkloadDisplay($value): string
  4894. {
  4895. if ($value === null || $value === '') {
  4896. return '';
  4897. }
  4898. $s = trim((string)$value);
  4899. if ($s === '') {
  4900. return '';
  4901. }
  4902. if (is_numeric($s) && (float)$s == 0) {
  4903. return '';
  4904. }
  4905. return $s;
  4906. }
  4907. /**
  4908. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4909. */
  4910. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4911. {
  4912. foreach ($details as $d) {
  4913. if (!is_array($d)) {
  4914. continue;
  4915. }
  4916. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4917. $cn = trim((string)($d['company_name'] ?? ''));
  4918. if ($cn !== '') {
  4919. return $cn;
  4920. }
  4921. }
  4922. }
  4923. return trim((string)($main['pick_company_name'] ?? ''));
  4924. }
  4925. /**
  4926. * 详情报价小计:单价 × 本工序本次数量
  4927. */
  4928. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4929. {
  4930. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4931. if ($unit === null) {
  4932. return null;
  4933. }
  4934. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4935. if ($qty === null || $qty <= 0) {
  4936. return null;
  4937. }
  4938. return $unit * $qty;
  4939. }
  4940. /**
  4941. * 详情页:工序小计 + 供应商分组报价与总计
  4942. *
  4943. * @param array<int, array<string, mixed>> $mergeRows
  4944. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4945. * @return array{
  4946. * process_rows: array,
  4947. * supplier_groups: array,
  4948. * order_total_text: string,
  4949. * order_total_has: bool,
  4950. * selected_company: string
  4951. * }
  4952. */
  4953. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4954. {
  4955. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4956. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  4957. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  4958. $qtyBySid = [];
  4959. $gymcBySid = [];
  4960. $orderedSids = [];
  4961. foreach ($mergeRows as $mr) {
  4962. if (!is_array($mr)) {
  4963. continue;
  4964. }
  4965. $sid = $this->extractScydgyRowId($mr);
  4966. if ($sid > 0) {
  4967. $orderedSids[] = $sid;
  4968. }
  4969. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4970. if ($qty === '') {
  4971. $qty = trim((string)($mr['NGZL'] ?? ''));
  4972. }
  4973. $qtyBySid[$sid] = $qty;
  4974. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4975. }
  4976. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4977. $detailByCompanySid = [];
  4978. foreach ($details as $d) {
  4979. if (!is_array($d)) {
  4980. continue;
  4981. }
  4982. $cn = trim((string)($d['company_name'] ?? ''));
  4983. $sid = (int)($d['scydgy_id'] ?? 0);
  4984. if ($cn === '' || $sid === 0) {
  4985. continue;
  4986. }
  4987. if (!isset($detailByCompanySid[$cn])) {
  4988. $detailByCompanySid[$cn] = [];
  4989. }
  4990. $detailByCompanySid[$cn][$sid] = $d;
  4991. }
  4992. $supplierGroups = [];
  4993. foreach ($detailByCompanySid as $cn => $bySid) {
  4994. $lines = [];
  4995. $groupTotal = 0.0;
  4996. $groupHas = false;
  4997. $groupVoid = true;
  4998. $usedSids = [];
  4999. $appendLine = function (int $sid, array $d) use (
  5000. &$lines,
  5001. &$groupTotal,
  5002. &$groupHas,
  5003. &$groupVoid,
  5004. $qtyBySid,
  5005. $gymcBySid,
  5006. $quoteVisible
  5007. ) {
  5008. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5009. if (!$isVoid) {
  5010. $groupVoid = false;
  5011. }
  5012. $qtyStr = $qtyBySid[$sid] ?? '';
  5013. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5014. $am = trim((string)($d['amount'] ?? ''));
  5015. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5016. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5017. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5018. $sub = null;
  5019. if (!$isVoid && $amountNum !== null) {
  5020. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5021. }
  5022. $ct = $this->resolveDetailSupplierOperTime($d);
  5023. $line = [
  5024. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5025. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  5026. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5027. 'delivery_ymd' => $deliveryYmd,
  5028. 'amount_filled' => $amountFilled,
  5029. 'delivery_filled' => $deliveryFilled,
  5030. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5031. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5032. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5033. 'is_void' => $isVoid,
  5034. 'oper_time_text' => $ct,
  5035. ];
  5036. if (!$quoteVisible && !$isVoid) {
  5037. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5038. } elseif ($sub !== null) {
  5039. $groupTotal += $sub;
  5040. $groupHas = true;
  5041. }
  5042. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5043. };
  5044. foreach ($orderedSids as $sid) {
  5045. if (!isset($bySid[$sid])) {
  5046. continue;
  5047. }
  5048. $usedSids[$sid] = true;
  5049. $appendLine($sid, $bySid[$sid]);
  5050. }
  5051. foreach ($bySid as $sid => $d) {
  5052. if (isset($usedSids[$sid])) {
  5053. continue;
  5054. }
  5055. $appendLine((int)$sid, $d);
  5056. }
  5057. $firstDetail = null;
  5058. foreach ($bySid as $d) {
  5059. if (is_array($d)) {
  5060. $firstDetail = $d;
  5061. break;
  5062. }
  5063. }
  5064. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5065. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5066. if ($username === '' && $ph !== '') {
  5067. $username = $this->resolveCustomerContactName($ph, $cn);
  5068. }
  5069. $lineCount = count($lines);
  5070. $supplierGroups[] = [
  5071. 'company_name' => $cn,
  5072. 'username' => $username,
  5073. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5074. 'phone' => $ph,
  5075. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5076. 'is_void' => $groupVoid,
  5077. 'lines' => $lines,
  5078. 'line_count' => $lineCount,
  5079. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  5080. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5081. 'has_total' => $lineCount > 0,
  5082. ];
  5083. }
  5084. usort($supplierGroups, function ($a, $b) {
  5085. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5086. return ($a['is_void'] ?? false) ? 1 : -1;
  5087. }
  5088. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5089. return ($a['is_selected'] ?? false) ? -1 : 1;
  5090. }
  5091. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5092. });
  5093. return [
  5094. 'process_rows' => $processRows,
  5095. 'supplier_groups' => $supplierGroups,
  5096. 'order_total_text' => '',
  5097. 'order_total_has' => false,
  5098. 'selected_company' => $selectedCompany,
  5099. ];
  5100. }
  5101. /**
  5102. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5103. */
  5104. protected function buildProcessLinesPlain(array $mergeRows): string
  5105. {
  5106. $lines = [];
  5107. $i = 1;
  5108. foreach ($mergeRows as $r) {
  5109. if (!is_array($r)) {
  5110. continue;
  5111. }
  5112. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5113. $dw = trim((string)($r['CDW'] ?? ''));
  5114. $gzl = trim((string)($r['NGZL'] ?? ''));
  5115. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5116. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5117. if ($dw !== '') {
  5118. $parts[] = '单位:' . $dw;
  5119. }
  5120. if ($gzl !== '') {
  5121. $parts[] = '工作量:' . $gzl;
  5122. }
  5123. if ($qty !== '') {
  5124. $parts[] = '本次数量:' . $qty;
  5125. }
  5126. $lines[] = implode(' ', $parts);
  5127. $i++;
  5128. }
  5129. return implode("\n", $lines);
  5130. }
  5131. /**
  5132. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5133. *
  5134. * @return array<string, string>
  5135. */
  5136. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5137. {
  5138. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5139. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5140. }
  5141. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5142. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5143. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5144. $cyjmc = '';
  5145. foreach ($mergeRows as $mr) {
  5146. if (!is_array($mr)) {
  5147. continue;
  5148. }
  5149. if ($ccydh === '') {
  5150. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5151. }
  5152. if ($cyjmc === '') {
  5153. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5154. }
  5155. }
  5156. if ($pos !== []) {
  5157. $firstPo = $pos[0];
  5158. if (is_array($firstPo)) {
  5159. if ($ccydh === '') {
  5160. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5161. }
  5162. if ($cyjmc === '') {
  5163. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5164. }
  5165. }
  5166. }
  5167. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5168. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5169. if (is_array($any)) {
  5170. if ($ccydh === '') {
  5171. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5172. }
  5173. if ($cyjmc === '') {
  5174. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5175. }
  5176. }
  5177. }
  5178. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5179. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5180. $cgymc = '';
  5181. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5182. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5183. }
  5184. return [
  5185. 'ccydh' => $ccydh,
  5186. 'cyjmc' => $cyjmc,
  5187. 'cgymc' => $cgymc,
  5188. 'process_lines' => $processLines,
  5189. 'process_lines_html' => '',
  5190. ];
  5191. }
  5192. /**
  5193. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5194. */
  5195. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5196. {
  5197. $lines = [];
  5198. if ($ccydh !== '') {
  5199. $lines[] = '订单号:' . $ccydh;
  5200. }
  5201. if ($cyjmc !== '') {
  5202. $lines[] = '印件名称:' . $cyjmc;
  5203. }
  5204. if ($processPlain !== '') {
  5205. $lines[] = $processPlain;
  5206. }
  5207. return implode("\n", $lines);
  5208. }
  5209. /**
  5210. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5211. *
  5212. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5213. */
  5214. protected function buildPlatformLinksPlain(array $detailLinks): string
  5215. {
  5216. $lines = [];
  5217. $i = 1;
  5218. foreach ($detailLinks as $lk) {
  5219. if (!is_array($lk)) {
  5220. continue;
  5221. }
  5222. $url = trim((string)($lk['url'] ?? ''));
  5223. if ($url === '') {
  5224. continue;
  5225. }
  5226. $label = trim((string)($lk['cgymc'] ?? ''));
  5227. if ($label === '') {
  5228. $label = '工序' . $i;
  5229. }
  5230. $lines[] = $label . ':' . $url;
  5231. $i++;
  5232. }
  5233. return implode("\n", $lines);
  5234. }
  5235. /**
  5236. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5237. *
  5238. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5239. */
  5240. protected function buildPlatformLinksHtml(array $detailLinks): string
  5241. {
  5242. $parts = [];
  5243. $i = 1;
  5244. foreach ($detailLinks as $lk) {
  5245. if (!is_array($lk)) {
  5246. continue;
  5247. }
  5248. $url = trim((string)($lk['url'] ?? ''));
  5249. if ($url === '') {
  5250. continue;
  5251. }
  5252. $label = trim((string)($lk['cgymc'] ?? ''));
  5253. if ($label === '') {
  5254. $label = '工序' . $i;
  5255. }
  5256. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5257. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5258. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5259. $i++;
  5260. }
  5261. return implode("<br>\n", $parts);
  5262. }
  5263. /**
  5264. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5265. *
  5266. * @return array<string, mixed>
  5267. */
  5268. protected function loadMailerConfig(): array
  5269. {
  5270. try {
  5271. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5272. } catch (\Throwable $e) {
  5273. $cfg = [];
  5274. }
  5275. return is_array($cfg) ? $cfg : [];
  5276. }
  5277. protected function loadNotifyTemplateRow(string $scene): ?array
  5278. {
  5279. try {
  5280. $row = Db::table('purchase_sms_template')
  5281. ->where('scene', $scene)
  5282. ->where(function ($q) {
  5283. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5284. })
  5285. ->order('id', 'asc')
  5286. ->find();
  5287. } catch (\Throwable $e) {
  5288. return null;
  5289. }
  5290. if (!is_array($row) || $row === []) {
  5291. return null;
  5292. }
  5293. return [
  5294. 'title' => trim((string)($row['title'] ?? '')),
  5295. 'content' => trim((string)($row['content'] ?? '')),
  5296. ];
  5297. }
  5298. /**
  5299. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5300. */
  5301. protected function buildProcessLinesHtml(array $mergeRows): string
  5302. {
  5303. if (count($mergeRows) <= 1) {
  5304. $r = $mergeRows[0] ?? [];
  5305. if (!is_array($r)) {
  5306. return '';
  5307. }
  5308. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5309. $dw = trim((string)($r['CDW'] ?? ''));
  5310. $gzl = trim((string)($r['NGZL'] ?? ''));
  5311. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5312. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5313. if ($dw !== '') {
  5314. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5315. }
  5316. if ($gzl !== '') {
  5317. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5318. }
  5319. if ($qty !== '') {
  5320. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5321. }
  5322. return $html;
  5323. }
  5324. $rows = '';
  5325. $i = 1;
  5326. foreach ($mergeRows as $r) {
  5327. if (!is_array($r)) {
  5328. continue;
  5329. }
  5330. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5331. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5332. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5333. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5334. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5335. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5336. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5337. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5338. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5339. $i++;
  5340. }
  5341. if ($rows === '') {
  5342. return '';
  5343. }
  5344. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5345. . '<thead><tr style="background:#f5f5f5;">'
  5346. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5347. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5348. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5349. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5350. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5351. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5352. }
  5353. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5354. {
  5355. $sysRq = trim($sysRq);
  5356. if ($sysRq === '') {
  5357. if ($required) {
  5358. $this->error('请选择截止时间');
  5359. }
  5360. return '';
  5361. }
  5362. $ts = strtotime($sysRq);
  5363. if ($ts === false || $ts <= 0) {
  5364. $this->error('截止时间格式无效');
  5365. }
  5366. return date('Y-m-d H:i:s', $ts);
  5367. }
  5368. protected function formatProcuremenSysRqForInput($sysRq): string
  5369. {
  5370. $sr = trim((string)$sysRq);
  5371. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5372. return '';
  5373. }
  5374. $ts = strtotime($sr);
  5375. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5376. }
  5377. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5378. {
  5379. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5380. if ($sr === '') {
  5381. return '—';
  5382. }
  5383. $ts = strtotime($sr);
  5384. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5385. }
  5386. /**
  5387. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5388. *
  5389. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5390. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5391. */
  5392. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5393. {
  5394. return $bundle;
  5395. }
  5396. /**
  5397. * 写入/更新 purchase_order(单道工序行)
  5398. */
  5399. protected function upsertPurchaseOrderFromRow(
  5400. array $row,
  5401. string $sysRqDb,
  5402. $wflowStatus = null,
  5403. ?string $pickTime = null,
  5404. ?array $exists = null
  5405. ): void {
  5406. $ids = $this->extractScydgyRowId($row);
  5407. if (!$this->isValidScydgyRowId($ids)) {
  5408. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5409. }
  5410. if ($exists === null) {
  5411. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5412. }
  5413. $data = [
  5414. 'scydgy_id' => $ids,
  5415. 'CCYDH' => $row['CCYDH'] ?? null,
  5416. 'CYJMC' => $row['CYJMC'] ?? null,
  5417. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5418. 'CDXMC' => $row['CDXMC'] ?? null,
  5419. 'CGYBH' => $row['CGYBH'] ?? null,
  5420. 'CGYMC' => $row['CGYMC'] ?? null,
  5421. 'CDW' => $row['CDW'] ?? null,
  5422. 'NGZL' => $row['NGZL'] ?? null,
  5423. 'CDF' => $row['CDF'] ?? null,
  5424. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5425. 'MBZ' => $row['MBZ'] ?? null,
  5426. 'bwjg' => $row['bwjg'] ?? null,
  5427. 'iStatus' => $row['iStatus'] ?? null,
  5428. 'dStamp' => $row['dStamp'] ?? null,
  5429. 'dputrecord' => $row['dputrecord'] ?? null,
  5430. 'cywyxm' => $row['cywyxm'] ?? null,
  5431. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5432. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5433. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5434. 'sys_rq' => $sysRqDb,
  5435. ];
  5436. if ($wflowStatus !== null && $wflowStatus !== '') {
  5437. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5438. }
  5439. if ($pickTime !== null && $pickTime !== '') {
  5440. $data['pick_time'] = $pickTime;
  5441. $data['pick_company_name'] = '';
  5442. }
  5443. if ($exists) {
  5444. $upd = $data;
  5445. unset($upd['scydgy_id']);
  5446. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5447. } else {
  5448. $data['createtime'] = date('Y-m-d H:i:s');
  5449. Db::table('purchase_order')->insert($data);
  5450. }
  5451. }
  5452. /**
  5453. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5454. *
  5455. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5456. */
  5457. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5458. {
  5459. $toDb = function ($value) {
  5460. if ($value === null) {
  5461. return null;
  5462. }
  5463. if (is_scalar($value)) {
  5464. return $value;
  5465. }
  5466. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5467. };
  5468. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5469. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5470. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5471. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5472. if ($username === '') {
  5473. $username = $this->resolveCustomerContactName($phone, $companyName);
  5474. }
  5475. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5476. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5477. }
  5478. if ($phone === '') {
  5479. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5480. }
  5481. $detailLinks = [];
  5482. foreach ($mergeRows as $row) {
  5483. if (!is_array($row)) {
  5484. continue;
  5485. }
  5486. $sid = $this->extractScydgyRowId($row);
  5487. $detailId = 0;
  5488. if ($skipExisting) {
  5489. try {
  5490. $existsQuery = Db::table('purchase_order_detail')
  5491. ->where('scydgy_id', $sid)
  5492. ->where('company_name', $companyName);
  5493. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5494. $exists = $existsQuery->find();
  5495. } catch (\Throwable $e) {
  5496. $exists = null;
  5497. }
  5498. if (is_array($exists)) {
  5499. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5500. }
  5501. }
  5502. if ($detailId <= 0) {
  5503. $one = [
  5504. 'scydgy_id' => $toDb($sid),
  5505. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5506. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5507. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5508. 'username' => $username !== '' ? $username : null,
  5509. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5510. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5511. 'createtime' => date('Y-m-d H:i:s'),
  5512. 'status' => ProcuremenStatus::POD_UNPICKED,
  5513. 'status_name' => '未提交',
  5514. ];
  5515. Db::table('purchase_order_detail')->insert($one);
  5516. $detailId = (int)Db::getLastInsID();
  5517. }
  5518. $mprocUrl = '';
  5519. if ($buildMobileLinks && $detailId > 0) {
  5520. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5521. }
  5522. $detailLinks[] = [
  5523. 'detail_id' => $detailId,
  5524. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5525. 'url' => $mprocUrl,
  5526. ];
  5527. }
  5528. return $detailLinks;
  5529. }
  5530. /**
  5531. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5532. * @return array<string, mixed>
  5533. */
  5534. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5535. {
  5536. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5537. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5538. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5539. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5540. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5541. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5542. $isMerge = !empty($ctx['is_merge']);
  5543. $contactName = trim((string)($c['username'] ?? ''));
  5544. if ($contactName === '') {
  5545. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5546. }
  5547. $notifyVars = [
  5548. 'company_name' => $companyName,
  5549. 'contact_name' => $contactName,
  5550. 'phone' => $phone,
  5551. 'email' => $toEmail,
  5552. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5553. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5554. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5555. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5556. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5557. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5558. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5559. 'platform_url' => $platformUrl,
  5560. 'platform_links' => $platformLinksPlain,
  5561. 'platform_links_html' => $platformLinksHtml,
  5562. ];
  5563. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5564. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5565. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5566. return [
  5567. 'company_name' => $companyName,
  5568. 'phone' => $phone,
  5569. 'email' => $toEmail,
  5570. 'sms_content' => $smsContent,
  5571. 'mail_plain' => $mailPlain,
  5572. 'mail_body' => $mailBody,
  5573. 'notify_vars' => $notifyVars,
  5574. 'detail_links' => $detailLinks,
  5575. ];
  5576. }
  5577. /**
  5578. * @param array<string, mixed> $chosen
  5579. * @param array<int, array<string, mixed>> $mergeRows
  5580. * @param array{ccydh:string, pos:array} $bundle
  5581. */
  5582. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5583. {
  5584. if (!$sendSms && !$sendEmail) {
  5585. return;
  5586. }
  5587. $companyName = trim((string)($chosen['name'] ?? ''));
  5588. $phone = trim((string)($chosen['phone'] ?? ''));
  5589. $toEmail = trim((string)($chosen['email'] ?? ''));
  5590. if ($companyName === '') {
  5591. throw new \Exception('供应商名称无效');
  5592. }
  5593. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5594. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5595. }
  5596. if ($sendSms && $phone === '') {
  5597. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5598. }
  5599. $sids = [];
  5600. foreach ($mergeRows as $mr) {
  5601. if (!is_array($mr)) {
  5602. continue;
  5603. }
  5604. $sid = $this->extractScydgyRowId($mr);
  5605. if ($this->isValidScydgyRowId($sid)) {
  5606. $sids[$sid] = true;
  5607. }
  5608. }
  5609. if ($sids === []) {
  5610. throw new \Exception('未找到工序行,无法发送通知');
  5611. }
  5612. $sysRqNotify = '';
  5613. $pos = $bundle['pos'] ?? [];
  5614. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5615. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5616. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5617. $ts = strtotime($sr);
  5618. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5619. }
  5620. }
  5621. try {
  5622. $detailsQuery = Db::table('purchase_order_detail')
  5623. ->where('scydgy_id', 'in', array_keys($sids))
  5624. ->where('company_name', $companyName);
  5625. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5626. $details = $detailsQuery->order('id', 'asc')->select();
  5627. } catch (\Throwable $e) {
  5628. $details = [];
  5629. }
  5630. if (!is_array($details) || $details === []) {
  5631. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5632. try {
  5633. $detailsQuery = Db::table('purchase_order_detail')
  5634. ->where('scydgy_id', 'in', array_keys($sids))
  5635. ->where('company_name', $companyName);
  5636. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5637. $details = $detailsQuery->order('id', 'asc')->select();
  5638. } catch (\Throwable $e) {
  5639. $details = [];
  5640. }
  5641. }
  5642. if (!is_array($details) || $details === []) {
  5643. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5644. }
  5645. $detailLinks = [];
  5646. foreach ($details as $d) {
  5647. if (!is_array($d)) {
  5648. continue;
  5649. }
  5650. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5651. if ($detailId <= 0) {
  5652. continue;
  5653. }
  5654. $sid = (int)($d['scydgy_id'] ?? 0);
  5655. $gymc = '';
  5656. foreach ($mergeRows as $mr) {
  5657. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5658. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5659. break;
  5660. }
  5661. }
  5662. $detailLinks[] = [
  5663. 'detail_id' => $detailId,
  5664. 'cgymc' => $gymc,
  5665. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5666. ];
  5667. }
  5668. if ($detailLinks === []) {
  5669. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5670. }
  5671. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5672. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5673. $notifyBundle['email_log_scene'] = $emailLogScene;
  5674. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  5675. $poIdLog = 0;
  5676. $pos = $bundle['pos'] ?? [];
  5677. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5678. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5679. }
  5680. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  5681. if ($sendEmail) {
  5682. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5683. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5684. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5685. }
  5686. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5687. $mailConfig = $this->loadMailerConfig();
  5688. if (!$this->isProcuremenNotifyDryRun()) {
  5689. if (empty($mailConfig['host'])) {
  5690. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5691. }
  5692. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5693. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5694. }
  5695. }
  5696. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5697. }
  5698. if ($sendSms) {
  5699. $this->issueSendSupplierSms($notifyBundle);
  5700. }
  5701. }
  5702. /**
  5703. * @param array<int, array<string, mixed>> $quoteGroups
  5704. * @return array<int, array<string, mixed>>
  5705. */
  5706. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5707. {
  5708. $names = [];
  5709. if (is_string($companiesJson) && $companiesJson !== '') {
  5710. $decoded = json_decode($companiesJson, true);
  5711. if (is_array($decoded)) {
  5712. foreach ($decoded as $nm) {
  5713. $nm = trim((string)$nm);
  5714. if ($nm !== '') {
  5715. $names[] = $nm;
  5716. }
  5717. }
  5718. }
  5719. }
  5720. $names = array_values(array_unique($names));
  5721. if ($names === [] && $selectedCompany !== '') {
  5722. $names = [$selectedCompany];
  5723. }
  5724. if ($names === []) {
  5725. return $quoteGroups;
  5726. }
  5727. $targets = [];
  5728. foreach ($quoteGroups as $g) {
  5729. if (!is_array($g)) {
  5730. continue;
  5731. }
  5732. $cn = trim((string)($g['name'] ?? ''));
  5733. if ($cn !== '' && in_array($cn, $names, true)) {
  5734. $targets[] = $g;
  5735. }
  5736. }
  5737. return $targets;
  5738. }
  5739. /**
  5740. * @return array{pos:array, merge_rows:array, bundle:array}
  5741. */
  5742. protected function loadAuditResendBundle(string $scydgyId): array
  5743. {
  5744. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5745. $pos = $bundle['pos'];
  5746. $mergeRows = $bundle['merge_rows'];
  5747. if ($pos === [] || $mergeRows === []) {
  5748. $this->error('该订单不在待确认供应商状态');
  5749. }
  5750. $sysRqDb = '';
  5751. if (isset($pos[0]) && is_array($pos[0])) {
  5752. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5753. }
  5754. foreach ($pos as $i => $poRow) {
  5755. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5756. $pos[$i]['sys_rq'] = $sysRqDb;
  5757. }
  5758. }
  5759. $bundle['pos'] = $pos;
  5760. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5761. }
  5762. /**
  5763. * @param array<int, array<string, mixed>> $targets
  5764. */
  5765. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5766. {
  5767. if ($targets === []) {
  5768. $this->error('未找到可通知的供应商');
  5769. }
  5770. $notifyErrors = [];
  5771. try {
  5772. $this->notifyDryRunPreview = [];
  5773. foreach ($targets as $g) {
  5774. if (!is_array($g)) {
  5775. continue;
  5776. }
  5777. $cname = trim((string)($g['name'] ?? ''));
  5778. if ($cname === '') {
  5779. continue;
  5780. }
  5781. $chosen = [
  5782. 'name' => $cname,
  5783. 'company_name' => $cname,
  5784. 'email' => trim((string)($g['email'] ?? '')),
  5785. 'phone' => trim((string)($g['phone'] ?? '')),
  5786. 'username' => trim((string)($g['username'] ?? '')),
  5787. ];
  5788. try {
  5789. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  5790. } catch (\Throwable $e) {
  5791. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5792. }
  5793. }
  5794. } catch (\Throwable $e) {
  5795. $this->error('通知发送失败:' . $e->getMessage());
  5796. }
  5797. if ($notifyErrors !== []) {
  5798. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5799. }
  5800. if ($this->isProcuremenNotifyDryRun()) {
  5801. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5802. 'notify_dry_run' => true,
  5803. 'notify_preview' => $this->notifyDryRunPreview,
  5804. ]);
  5805. }
  5806. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5807. }
  5808. /**
  5809. * 协助下发 — 发送短信(一家供应商)
  5810. *
  5811. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5812. */
  5813. protected function issueSendSupplierSms(array $bundle): void
  5814. {
  5815. $companyName = (string)($bundle['company_name'] ?? '');
  5816. $phone = (string)($bundle['phone'] ?? '');
  5817. $smsContent = (string)($bundle['sms_content'] ?? '');
  5818. $this->logIssueNotifyDebug('短信', [
  5819. 'company' => $companyName,
  5820. 'phone' => $phone,
  5821. 'sms_content' => $smsContent,
  5822. ]);
  5823. if ($this->isProcuremenNotifyDryRun()) {
  5824. $this->recordNotifyDryRunPreview([
  5825. 'scene' => 'issue_sms',
  5826. 'company_name' => $companyName,
  5827. 'phone' => $phone,
  5828. 'sms_content' => $smsContent,
  5829. ]);
  5830. return;
  5831. }
  5832. $this->smsbao($phone, $smsContent);
  5833. }
  5834. /**
  5835. * 协助下发 — 发送邮件(一家供应商)
  5836. *
  5837. * @param array<string, mixed> $bundle
  5838. * @param array<string, mixed> $mailConfig
  5839. */
  5840. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5841. {
  5842. $companyName = (string)($bundle['company_name'] ?? '');
  5843. $toEmail = (string)($bundle['email'] ?? '');
  5844. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5845. $mailBody = (string)($bundle['mail_body'] ?? '');
  5846. $this->logIssueNotifyDebug('邮件', [
  5847. 'company' => $companyName,
  5848. 'email' => $toEmail,
  5849. 'mail_subject' => $mailSubject,
  5850. 'mail_body' => $mailPlain,
  5851. ]);
  5852. if ($this->isProcuremenNotifyDryRun()) {
  5853. $this->recordNotifyDryRunPreview([
  5854. 'scene' => 'issue_email',
  5855. 'company_name' => $companyName,
  5856. 'email' => $toEmail,
  5857. 'mail_subject' => $mailSubject,
  5858. 'mail_body' => $mailPlain,
  5859. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5860. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5861. 'detail_links' => $bundle['detail_links'] ?? [],
  5862. ]);
  5863. return;
  5864. }
  5865. $mail = new PHPMailer(true);
  5866. $mail->isSMTP();
  5867. $mail->Host = $mailConfig['host'];
  5868. $mail->SMTPAuth = true;
  5869. $mail->Username = $mailConfig['addr'];
  5870. $mail->Password = $mailConfig['pass'];
  5871. $mail->SMTPSecure = $mailConfig['security'];
  5872. $mail->Port = $mailConfig['port'];
  5873. $mail->CharSet = $mailConfig['charset'];
  5874. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5875. $mail->addAddress($toEmail, $companyName);
  5876. $mail->isHTML(true);
  5877. $mail->Subject = $mailSubject;
  5878. $mail->Body = $mailBody;
  5879. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  5880. $sendOk = true;
  5881. $failReason = '';
  5882. try {
  5883. $mail->send();
  5884. } catch (\Throwable $e) {
  5885. $sendOk = false;
  5886. $failReason = $e->getMessage();
  5887. $this->persistEmailSendLog([
  5888. 'from_email' => $fromEmail,
  5889. 'to_email' => $toEmail,
  5890. 'send_time' => date('Y-m-d H:i:s'),
  5891. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  5892. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  5893. 'company_name' => $companyName,
  5894. 'mail_subject' => $mailSubject,
  5895. 'status' => 0,
  5896. 'fail_reason' => $failReason,
  5897. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  5898. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  5899. ]);
  5900. throw $e;
  5901. }
  5902. $this->persistEmailSendLog([
  5903. 'from_email' => $fromEmail,
  5904. 'to_email' => $toEmail,
  5905. 'send_time' => date('Y-m-d H:i:s'),
  5906. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  5907. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  5908. 'company_name' => $companyName,
  5909. 'mail_subject' => $mailSubject,
  5910. 'status' => 1,
  5911. 'fail_reason' => '',
  5912. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  5913. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  5914. ]);
  5915. }
  5916. /**
  5917. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5918. *
  5919. * @param array<int, array<string, mixed>> $mergeRows
  5920. * @return array<string, mixed>
  5921. */
  5922. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5923. {
  5924. $head = $mergeRows[0] ?? [];
  5925. $isMerge = count($mergeRows) > 1;
  5926. return [
  5927. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5928. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5929. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5930. 'is_merge' => $isMerge,
  5931. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5932. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5933. 'deadline' => $sysRqNotify,
  5934. ];
  5935. }
  5936. /**
  5937. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5938. *
  5939. * @param array<string, mixed> $data
  5940. */
  5941. protected function logIssueNotifyDebug(string $type, array $data): void
  5942. {
  5943. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5944. return;
  5945. }
  5946. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5947. }
  5948. protected function ensurePurchaseEmailSendLogTableOnce(): void
  5949. {
  5950. try {
  5951. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  5952. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  5953. return;
  5954. } catch (\Throwable $e) {
  5955. }
  5956. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  5957. if (is_file($sqlFile)) {
  5958. $sql = file_get_contents($sqlFile);
  5959. if (is_string($sql) && $sql !== '') {
  5960. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  5961. $stmt = trim($stmt);
  5962. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  5963. continue;
  5964. }
  5965. try {
  5966. Db::execute($stmt);
  5967. } catch (\Throwable $ignore) {
  5968. }
  5969. }
  5970. }
  5971. }
  5972. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  5973. }
  5974. /**
  5975. * @param array<string, mixed> $row
  5976. */
  5977. protected function persistEmailSendLog(array $row): void
  5978. {
  5979. try {
  5980. $this->ensurePurchaseEmailSendLogTableOnce();
  5981. } catch (\Throwable $e) {
  5982. return;
  5983. }
  5984. list($adminId, $adminName) = $this->GetUseName();
  5985. $cut = function ($s, $max) {
  5986. $s = (string)$s;
  5987. if (function_exists('mb_substr')) {
  5988. return mb_substr($s, 0, $max, 'UTF-8');
  5989. }
  5990. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5991. };
  5992. $data = [
  5993. 'from_email' => $cut($row['from_email'] ?? '', 128),
  5994. 'to_email' => $cut($row['to_email'] ?? '', 128),
  5995. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  5996. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  5997. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  5998. 'company_name' => $cut($row['company_name'] ?? '', 128),
  5999. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6000. 'status' => !empty($row['status']) ? 1 : 0,
  6001. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6002. 'admin_id' => (int)$adminId,
  6003. 'admin_name' => $cut($adminName, 64),
  6004. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6005. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6006. 'createtime' => date('Y-m-d H:i:s'),
  6007. ];
  6008. try {
  6009. Db::table('purchase_email_send_log')->insert($data);
  6010. } catch (\Throwable $e) {
  6011. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6012. }
  6013. }
  6014. protected function formatEmailLogSceneText(string $scene): string
  6015. {
  6016. $map = [
  6017. 'pick_issue' => '初选下发',
  6018. 'audit_resend' => '确认页重发',
  6019. ];
  6020. return $map[$scene] ?? $scene;
  6021. }
  6022. /**
  6023. * 邮件发送日志列表
  6024. */
  6025. public function emailLog()
  6026. {
  6027. $this->relationSearch = false;
  6028. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6029. $this->request->filter(['strip_tags', 'trim']);
  6030. $bakModel = $this->model;
  6031. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6032. if ($this->request->isAjax()) {
  6033. $this->ensurePurchaseEmailSendLogTableOnce();
  6034. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6035. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6036. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6037. $list = $this->model
  6038. ->where($where)
  6039. ->order($sortField, $orderDir)
  6040. ->paginate($limit);
  6041. $rows = [];
  6042. foreach ($list->items() as $item) {
  6043. $row = is_array($item) ? $item : $item->toArray();
  6044. $scene = trim((string)($row['scene'] ?? ''));
  6045. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6046. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6047. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6048. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6049. $rows[] = $row;
  6050. }
  6051. $this->model = $bakModel;
  6052. return json(['total' => $list->total(), 'rows' => $rows]);
  6053. }
  6054. $this->model = $bakModel;
  6055. return $this->view->fetch('procuremen/emaillog');
  6056. }
  6057. /**
  6058. * 协助下发弹窗(选多家供应商并通知)
  6059. */
  6060. public function pickReview()
  6061. {
  6062. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6063. $this->error(__('You have no permission'));
  6064. }
  6065. if ($this->request->isPost()) {
  6066. $this->error('请使用弹窗内「确认下发」提交');
  6067. }
  6068. $this->view->assign('pickMode', 1);
  6069. return $this->view->fetch('procuremen/review');
  6070. }
  6071. /**
  6072. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6073. */
  6074. public function add()
  6075. {
  6076. if ($this->request->isPost()) {
  6077. $params = $this->request->post('row/a');
  6078. if (!is_array($params)) {
  6079. $this->error(__('Parameter %s can not be empty', ''));
  6080. }
  6081. [, $adminName] = $this->GetUseName();
  6082. $params['cywyxm'] = $adminName;
  6083. try {
  6084. $sid = $this->saveManualPickOrder($params);
  6085. } catch (\InvalidArgumentException $e) {
  6086. $this->error($e->getMessage());
  6087. } catch (\Throwable $e) {
  6088. $this->error($e->getMessage());
  6089. }
  6090. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6091. }
  6092. [, $adminName] = $this->GetUseName();
  6093. $this->view->assign('adminNickname', $adminName);
  6094. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6095. return $this->view->fetch();
  6096. }
  6097. /**
  6098. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6099. */
  6100. public function rfqlist()
  6101. {
  6102. $this->relationSearch = false;
  6103. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6104. $this->request->filter(['strip_tags', 'trim']);
  6105. if ($this->request->isAjax()) {
  6106. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6107. $limit = max(10, min(500, (int)$limit));
  6108. $applyFilters = function ($query) use ($where) {
  6109. $query->where('scydgy_id', '<', 0);
  6110. $query->whereRaw(
  6111. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6112. );
  6113. if (!$this->auth->isSuperAdmin()) {
  6114. [, $adminName] = $this->GetUseName();
  6115. $query->where('cywyxm', $adminName);
  6116. }
  6117. if (!empty($where)) {
  6118. $query->where($where);
  6119. }
  6120. };
  6121. $countQuery = Db::table('purchase_order');
  6122. $applyFilters($countQuery);
  6123. $total = (int)$countQuery->count();
  6124. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6125. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6126. $listQuery = Db::table('purchase_order');
  6127. $applyFilters($listQuery);
  6128. $rows = $listQuery
  6129. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6130. ->order($sortField, $orderDir)
  6131. ->limit($offset, $limit)
  6132. ->select();
  6133. if (!is_array($rows)) {
  6134. $rows = [];
  6135. }
  6136. $out = [];
  6137. foreach ($rows as $r) {
  6138. if (!is_array($r)) {
  6139. continue;
  6140. }
  6141. $sid = (int)($r['scydgy_id'] ?? 0);
  6142. if ($sid >= 0) {
  6143. continue;
  6144. }
  6145. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6146. if ($createdText === '') {
  6147. $createdText = trim((string)($r['dStamp'] ?? ''));
  6148. }
  6149. $out[] = [
  6150. 'id' => (int)($r['id'] ?? 0),
  6151. 'scydgy_id' => $sid,
  6152. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6153. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6154. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6155. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6156. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6157. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6158. 'createtime' => $r['createtime'] ?? null,
  6159. 'createtime_text' => $createdText,
  6160. ];
  6161. }
  6162. return json(['total' => $total, 'rows' => $out]);
  6163. }
  6164. [, $adminName] = $this->GetUseName();
  6165. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6166. $this->view->assign('adminNickname', $adminName);
  6167. return $this->view->fetch('procuremen/rfqlist');
  6168. }
  6169. /**
  6170. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6171. */
  6172. public function rfqlistDetails()
  6173. {
  6174. return $this->details();
  6175. }
  6176. /**
  6177. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6178. */
  6179. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6180. {
  6181. if ($scydgyId >= 0) {
  6182. return;
  6183. }
  6184. try {
  6185. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6186. } catch (\Throwable $e) {
  6187. $po = null;
  6188. }
  6189. if (!is_array($po)) {
  6190. $this->error('订单不存在');
  6191. }
  6192. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6193. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6194. $this->error('订单不存在');
  6195. }
  6196. if ($this->auth->isSuperAdmin()) {
  6197. return;
  6198. }
  6199. [, $adminName] = $this->GetUseName();
  6200. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6201. if ($cywy !== '' && $cywy === $adminName) {
  6202. return;
  6203. }
  6204. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6205. try {
  6206. if ($this->auth->check($rule)) {
  6207. return;
  6208. }
  6209. } catch (\Throwable $e) {
  6210. }
  6211. }
  6212. $this->error('无权查看该订单');
  6213. }
  6214. /**
  6215. * 手工新增协助工序进度文案
  6216. */
  6217. protected function formatProcuremenRfqProgressText(array $row): string
  6218. {
  6219. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6220. return ProcuremenStatus::PO_COMPLETED;
  6221. }
  6222. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6223. return '待采购确认';
  6224. }
  6225. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6226. return '待确认供应商';
  6227. }
  6228. $sid = (int)($row['scydgy_id'] ?? 0);
  6229. if ($sid < 0) {
  6230. try {
  6231. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6232. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6233. $detCnt = (int)$detCntQuery->count();
  6234. if ($detCnt > 0) {
  6235. return '已下发待确认';
  6236. }
  6237. } catch (\Throwable $e) {
  6238. }
  6239. }
  6240. return '待协助下发';
  6241. }
  6242. /**
  6243. * 协助初选列表 — 批量软删除
  6244. */
  6245. public function pickDelete()
  6246. {
  6247. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6248. $this->error(__('Invalid parameters'));
  6249. }
  6250. if (!$this->procuremenCanPickDelete()) {
  6251. $this->error(__('You have no permission'));
  6252. }
  6253. $rowsRaw = $this->request->post('rows_json', '[]');
  6254. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6255. if (!is_array($rows) || $rows === []) {
  6256. $this->error('请至少勾选一条工序');
  6257. }
  6258. $done = 0;
  6259. Db::startTrans();
  6260. try {
  6261. foreach ($rows as $row) {
  6262. if (!is_array($row)) {
  6263. continue;
  6264. }
  6265. $this->softDeleteProcuremenPickRow($row);
  6266. $done++;
  6267. }
  6268. if ($done < 1) {
  6269. throw new \Exception('没有可删除的工序');
  6270. }
  6271. Db::commit();
  6272. } catch (\InvalidArgumentException $e) {
  6273. Db::rollback();
  6274. $this->error($e->getMessage());
  6275. } catch (\Throwable $e) {
  6276. Db::rollback();
  6277. $this->error($e->getMessage());
  6278. }
  6279. $this->pickHiddenScydgySetCache = null;
  6280. $this->success('已删除 ' . $done . ' 条工序');
  6281. }
  6282. /**
  6283. * 下发 — 手工新增工序(弹窗)
  6284. */
  6285. public function pickAdd()
  6286. {
  6287. if ($this->request->isPost()) {
  6288. $params = $this->request->post('row/a');
  6289. if (!is_array($params)) {
  6290. $this->error(__('Parameter %s can not be empty', ''));
  6291. }
  6292. try {
  6293. $sid = $this->saveManualPickOrder($params);
  6294. } catch (\InvalidArgumentException $e) {
  6295. $this->error($e->getMessage());
  6296. } catch (\Throwable $e) {
  6297. $this->error($e->getMessage());
  6298. }
  6299. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6300. }
  6301. return $this->view->fetch('procuremen/pick_add');
  6302. }
  6303. /**
  6304. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6305. */
  6306. public function pickSubmit()
  6307. {
  6308. if (!$this->request->isPost()) {
  6309. $this->error(__('Invalid parameters'));
  6310. }
  6311. // ---------- 接口订单数据 ----------
  6312. $rowJson = $this->request->post('row_json', '');
  6313. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6314. $companiesJson = $this->request->post('companies_json', '[]');
  6315. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6316. $companies = json_decode($companiesJson, true);
  6317. if (!is_array($companies)) {
  6318. $this->error('供应商数据无效');
  6319. }
  6320. $issueCompanies = $this->normalizePickCompanies($companies);
  6321. if ($issueCompanies === []) {
  6322. $this->error('请至少选择一家合作供应商');
  6323. }
  6324. $issueNameLabels = [];
  6325. foreach ($issueCompanies as $pc) {
  6326. $issueNameLabels[] = $pc['name'];
  6327. }
  6328. $issueNamesSummary = implode('、', $issueNameLabels);
  6329. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6330. if ($sysRq === '') {
  6331. $this->error('请选择截止时间');
  6332. }
  6333. $sysRqTs = strtotime($sysRq);
  6334. if ($sysRqTs === false || $sysRqTs <= 0) {
  6335. $this->error('截止时间格式无效');
  6336. }
  6337. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  6338. $isMerge = count($mergeRows) > 1;
  6339. $ccydhLog = '';
  6340. foreach ($mergeRows as $row) {
  6341. if (!is_array($row)) {
  6342. continue;
  6343. }
  6344. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6345. if ($ccydhLog !== '') {
  6346. break;
  6347. }
  6348. }
  6349. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6350. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6351. $logMsg = '下发' . $orderPart . $procPart
  6352. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6353. $issueTime = date('Y-m-d H:i:s');
  6354. $logSidList = [];
  6355. foreach ($mergeRows as $row) {
  6356. if (!is_array($row)) {
  6357. continue;
  6358. }
  6359. $sid = $this->extractScydgyRowId($row);
  6360. if ($this->isValidScydgyRowId($sid)) {
  6361. $logSidList[$sid] = true;
  6362. }
  6363. }
  6364. $existingBySid = [];
  6365. if ($logSidList !== []) {
  6366. try {
  6367. $existingRows = Db::table('purchase_order')
  6368. ->where('scydgy_id', 'in', array_keys($logSidList))
  6369. ->select();
  6370. if (is_array($existingRows)) {
  6371. foreach ($existingRows as $poRow) {
  6372. if (!is_array($poRow)) {
  6373. continue;
  6374. }
  6375. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6376. if ($this->isValidScydgyRowId($sid)) {
  6377. $existingBySid[$sid] = $poRow;
  6378. }
  6379. }
  6380. }
  6381. } catch (\Throwable $e) {
  6382. $existingBySid = [];
  6383. }
  6384. }
  6385. Db::startTrans();
  6386. try {
  6387. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6388. foreach ($mergeRows as $row) {
  6389. if (!is_array($row)) {
  6390. continue;
  6391. }
  6392. $sid = $this->extractScydgyRowId($row);
  6393. $this->upsertPurchaseOrderFromRow(
  6394. $row,
  6395. $sysRqDb,
  6396. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6397. $issueTime,
  6398. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  6399. );
  6400. }
  6401. foreach ($issueCompanies as $c) {
  6402. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6403. }
  6404. Db::commit();
  6405. } catch (\Throwable $e) {
  6406. Db::rollback();
  6407. $this->error($e->getMessage());
  6408. }
  6409. $poIdBySid = [];
  6410. if ($logSidList !== []) {
  6411. try {
  6412. $poIdBySid = Db::table('purchase_order')
  6413. ->where('scydgy_id', 'in', array_keys($logSidList))
  6414. ->column('id', 'scydgy_id');
  6415. } catch (\Throwable $e) {
  6416. $poIdBySid = [];
  6417. }
  6418. }
  6419. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6420. if ($logSidList !== []) {
  6421. list($adminId, $adminName) = $this->GetUseName();
  6422. $cut = function ($s, $max) {
  6423. if (function_exists('mb_substr')) {
  6424. return mb_substr($s, 0, $max, 'UTF-8');
  6425. }
  6426. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6427. };
  6428. $logRows = [];
  6429. $seenLogSid = [];
  6430. foreach ($mergeRows as $row) {
  6431. if (!is_array($row)) {
  6432. continue;
  6433. }
  6434. $ids = $this->extractScydgyRowId($row);
  6435. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6436. continue;
  6437. }
  6438. $seenLogSid[$ids] = true;
  6439. $poIdLog = null;
  6440. if (isset($poIdBySid[$ids])) {
  6441. $tid = (int)$poIdBySid[$ids];
  6442. $poIdLog = $tid > 0 ? $tid : null;
  6443. }
  6444. $logRows[] = [
  6445. 'scydgy_id' => $ids,
  6446. 'purchase_order_id' => $poIdLog,
  6447. 'admin_id' => $adminId,
  6448. 'admin_name' => $cut($adminName, 64),
  6449. 'action' => $cut('issue_submit', 64),
  6450. 'content' => $cut($logMsg, 1000),
  6451. 'createtime' => ProcuremenTime::nowDateTime(),
  6452. ];
  6453. }
  6454. if ($logRows !== []) {
  6455. try {
  6456. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6457. } catch (\Throwable $e) {
  6458. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6459. }
  6460. }
  6461. }
  6462. $notifyErrors = [];
  6463. $posNotify = [];
  6464. if ($logSidList !== []) {
  6465. try {
  6466. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6467. } catch (\Throwable $e) {
  6468. $posNotify = [];
  6469. }
  6470. }
  6471. if (!is_array($posNotify)) {
  6472. $posNotify = [];
  6473. }
  6474. foreach ($posNotify as $i => $prow) {
  6475. if (is_array($posNotify[$i])) {
  6476. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6477. }
  6478. }
  6479. $ccydhPick = '';
  6480. foreach ($mergeRows as $row) {
  6481. if (!is_array($row)) {
  6482. continue;
  6483. }
  6484. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6485. if ($ccydhPick !== '') {
  6486. break;
  6487. }
  6488. }
  6489. $notifyBundleBase = [
  6490. 'ccydh' => $ccydhPick,
  6491. 'pos' => $posNotify,
  6492. 'merge_rows' => $mergeRows,
  6493. ];
  6494. try {
  6495. $this->notifyDryRunPreview = [];
  6496. foreach ($issueCompanies as $c) {
  6497. if (!is_array($c)) {
  6498. continue;
  6499. }
  6500. $cname = trim((string)($c['name'] ?? ''));
  6501. if ($cname === '') {
  6502. continue;
  6503. }
  6504. try {
  6505. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6506. } catch (\Throwable $e) {
  6507. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6508. }
  6509. }
  6510. } catch (\Throwable $e) {
  6511. $this->error('通知发送失败:' . $e->getMessage());
  6512. }
  6513. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6514. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6515. }
  6516. if ($this->isProcuremenNotifyDryRun()) {
  6517. $this->success('【演练模式】已保存并生成通知预览', '', [
  6518. 'notify_dry_run' => true,
  6519. 'notify_preview' => $this->notifyDryRunPreview,
  6520. ]);
  6521. }
  6522. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6523. }
  6524. /**
  6525. * 确认供应商弹窗
  6526. */
  6527. public function auditIssue()
  6528. {
  6529. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6530. if (is_array($ids)) {
  6531. $ids = isset($ids[0]) ? $ids[0] : '';
  6532. }
  6533. $ids = trim((string)$ids);
  6534. if ($ids === '') {
  6535. $this->error(__('Invalid parameters'));
  6536. }
  6537. if ($this->request->isPost()) {
  6538. $this->error('请使用弹窗内「确认」提交');
  6539. }
  6540. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6541. $pos = $bundle['pos'];
  6542. if ($pos === []) {
  6543. $this->error('该订单不在待确认供应商状态');
  6544. }
  6545. $po = $pos[0];
  6546. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6547. if ($quoteGroups === []) {
  6548. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6549. }
  6550. $pickedName = '';
  6551. foreach ($pos as $poRow) {
  6552. if (!is_array($poRow)) {
  6553. continue;
  6554. }
  6555. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6556. if ($pn !== '') {
  6557. $pickedName = $pn;
  6558. break;
  6559. }
  6560. }
  6561. $this->view->assign('po', $po);
  6562. $this->view->assign('scydgyId', $ids);
  6563. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6564. $mergeRows = $bundle['merge_rows'];
  6565. $this->view->assign('processRows', $mergeRows);
  6566. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6567. $this->view->assign('processCount', count($mergeRows));
  6568. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6569. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6570. $this->view->assign('pickedCompanyName', $pickedName);
  6571. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  6572. if ($sysRqForView === '') {
  6573. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6574. }
  6575. $this->view->assign('sysRq', $sysRqForView);
  6576. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6577. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  6578. return $this->view->fetch('procuremen/audit_issue');
  6579. }
  6580. /**
  6581. * 开标双重验证 — 可选验证人列表
  6582. */
  6583. public function bidOpenUsers()
  6584. {
  6585. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6586. $this->error('无权限');
  6587. }
  6588. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  6589. if ($scydgyId !== '') {
  6590. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6591. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6592. $this->success('已完成开标验证', null, [
  6593. 'verified' => 1,
  6594. 'users' => [],
  6595. ]);
  6596. }
  6597. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6598. }
  6599. $this->success('', null, [
  6600. 'verified' => 0,
  6601. 'users' => $this->listBidOpenVerifierCandidates(),
  6602. ]);
  6603. }
  6604. /**
  6605. * 开标双重验证 — 向指定管理员发送短信验证码
  6606. */
  6607. public function bidOpenSendCode()
  6608. {
  6609. if (!$this->request->isPost()) {
  6610. $this->error(__('Invalid parameters'));
  6611. }
  6612. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6613. $this->error('无权限');
  6614. }
  6615. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6616. $adminId = (int)$this->request->post('admin_id', 0);
  6617. if ($scydgyId === '' || $adminId <= 0) {
  6618. $this->error('参数无效');
  6619. }
  6620. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6621. if ($bundle['pos'] === []) {
  6622. $this->error('该订单不在待确认供应商状态');
  6623. }
  6624. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6625. $this->success('已完成开标验证,无需重复发送');
  6626. }
  6627. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6628. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6629. if ($ccydh === '') {
  6630. $this->error('订单号无效');
  6631. }
  6632. $admin = $this->loadBidOpenAdminUser($adminId);
  6633. if ($admin === null) {
  6634. $this->error('验证人无效或未绑定手机号');
  6635. }
  6636. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  6637. $cd = max(30, min(120, $cd));
  6638. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  6639. $this->error('发送过于频繁,请稍后再试');
  6640. }
  6641. $code = (string)random_int(100000, 999999);
  6642. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  6643. $ttl = max(60, min(600, $ttl));
  6644. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  6645. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  6646. try {
  6647. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  6648. } catch (\Throwable $e) {
  6649. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  6650. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  6651. $this->error($e->getMessage());
  6652. }
  6653. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  6654. }
  6655. /**
  6656. * 开标双重验证 — 两人验证码校验并记录
  6657. */
  6658. public function bidOpenVerify()
  6659. {
  6660. if (!$this->request->isPost()) {
  6661. $this->error(__('Invalid parameters'));
  6662. }
  6663. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6664. $this->error('无权限');
  6665. }
  6666. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6667. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  6668. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  6669. $code1 = trim((string)$this->request->post('code1', ''));
  6670. $code2 = trim((string)$this->request->post('code2', ''));
  6671. if ($scydgyId === '') {
  6672. $this->error('参数无效');
  6673. }
  6674. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  6675. $this->error('请选择两位验证人');
  6676. }
  6677. if ($verifier1Id === $verifier2Id) {
  6678. $this->error('两位验证人不能相同');
  6679. }
  6680. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  6681. $this->error('请输入6位短信验证码');
  6682. }
  6683. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6684. if ($bundle['pos'] === []) {
  6685. $this->error('该订单不在待确认供应商状态');
  6686. }
  6687. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6688. if ($ccydh === '') {
  6689. $this->error('订单号无效');
  6690. }
  6691. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6692. $this->success('已完成开标验证');
  6693. }
  6694. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6695. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  6696. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  6697. if ($verifier1 === null || $verifier2 === null) {
  6698. $this->error('验证人无效或未绑定手机号');
  6699. }
  6700. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  6701. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  6702. }
  6703. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  6704. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  6705. }
  6706. try {
  6707. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  6708. } catch (\Throwable $e) {
  6709. $this->error($e->getMessage());
  6710. }
  6711. $this->success('开标验证成功,可查看供应商报价与交货日期');
  6712. }
  6713. /**
  6714. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  6715. */
  6716. public function auditSubmit()
  6717. {
  6718. if (!$this->request->isPost()) {
  6719. $this->error(__('Invalid parameters'));
  6720. }
  6721. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6722. if ($scydgyId === '') {
  6723. $this->error('参数无效');
  6724. }
  6725. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6726. $pos = $bundle['pos'];
  6727. $mergeRows = $bundle['merge_rows'];
  6728. if ($pos === [] || $mergeRows === []) {
  6729. $this->error('该订单不在待确认供应商状态');
  6730. }
  6731. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6732. if ($quoteGroups === []) {
  6733. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  6734. }
  6735. $companyName = trim((string)$this->request->post('selected_company', ''));
  6736. if ($companyName === '') {
  6737. $this->error('请选择一家供应商');
  6738. }
  6739. $matched = null;
  6740. foreach ($quoteGroups as $g) {
  6741. if (!is_array($g)) {
  6742. continue;
  6743. }
  6744. if (trim((string)($g['name'] ?? '')) === $companyName) {
  6745. $matched = $g;
  6746. break;
  6747. }
  6748. }
  6749. if ($matched === null) {
  6750. $this->error('所选供应商不在本单报价列表中');
  6751. }
  6752. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6753. if ($sysRqDb === '') {
  6754. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  6755. } else {
  6756. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  6757. }
  6758. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6759. $this->error('请先完成开标双重验证后再确认供应商');
  6760. }
  6761. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6762. $procCnt = count($mergeRows);
  6763. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6764. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  6765. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  6766. Db::startTrans();
  6767. try {
  6768. foreach ($pos as $poRow) {
  6769. if (!is_array($poRow)) {
  6770. continue;
  6771. }
  6772. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6773. if (!$this->isValidScydgyRowId($sid)) {
  6774. continue;
  6775. }
  6776. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6777. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6778. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6779. 'pick_company_name' => $companyName,
  6780. 'sys_rq' => $sysRqDb,
  6781. ]);
  6782. }
  6783. Db::commit();
  6784. } catch (\Throwable $e) {
  6785. Db::rollback();
  6786. $this->error($e->getMessage());
  6787. }
  6788. foreach ($pos as $poRow) {
  6789. if (!is_array($poRow)) {
  6790. continue;
  6791. }
  6792. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6793. if (!$this->isValidScydgyRowId($sid)) {
  6794. continue;
  6795. }
  6796. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6797. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6798. }
  6799. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6800. }
  6801. /**
  6802. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6803. */
  6804. public function auditResendSms()
  6805. {
  6806. if (!$this->request->isPost()) {
  6807. $this->error(__('Invalid parameters'));
  6808. }
  6809. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6810. if ($scydgyId === '') {
  6811. $this->error('参数无效');
  6812. }
  6813. $loaded = $this->loadAuditResendBundle($scydgyId);
  6814. $mergeRows = $loaded['merge_rows'];
  6815. $bundle = $loaded['bundle'];
  6816. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6817. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6818. if ($quoteGroups === []) {
  6819. $this->error('暂无可通知的供应商');
  6820. }
  6821. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6822. $companiesJson = (string)$this->request->post('companies_json', '');
  6823. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6824. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  6825. }
  6826. /**
  6827. * 确认供应商 — 二次发送邮件(可选单家/批量)
  6828. */
  6829. public function auditResendEmail()
  6830. {
  6831. if (!$this->request->isPost()) {
  6832. $this->error(__('Invalid parameters'));
  6833. }
  6834. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6835. if ($scydgyId === '') {
  6836. $this->error('参数无效');
  6837. }
  6838. $loaded = $this->loadAuditResendBundle($scydgyId);
  6839. $mergeRows = $loaded['merge_rows'];
  6840. $bundle = $loaded['bundle'];
  6841. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6842. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6843. if ($quoteGroups === []) {
  6844. $this->error('暂无可通知的供应商');
  6845. }
  6846. $companiesJson = (string)$this->request->post('companies_json', '');
  6847. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6848. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6849. if ($companiesJson === '' && $selectedCompany === '') {
  6850. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  6851. }
  6852. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  6853. }
  6854. /**
  6855. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  6856. *
  6857. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  6858. * @return array<int, true> 已处理的 scydgy_id 集合
  6859. */
  6860. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  6861. {
  6862. $pos = $bundle['pos'] ?? [];
  6863. if (!is_array($pos) || $pos === []) {
  6864. return [];
  6865. }
  6866. $sids = [];
  6867. foreach ($pos as $poRow) {
  6868. if (!is_array($poRow)) {
  6869. continue;
  6870. }
  6871. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6872. if ($this->isValidScydgyRowId($sid)) {
  6873. $sids[$sid] = true;
  6874. }
  6875. }
  6876. if ($sids === []) {
  6877. return [];
  6878. }
  6879. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6880. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  6881. $suffix = trim((string)$logSuffix, ',, ');
  6882. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  6883. $logMsg .= ':从历史存证退回协助初选';
  6884. } else {
  6885. $logMsg .= ':退回协助初选';
  6886. }
  6887. Db::table('purchase_order')
  6888. ->where('scydgy_id', 'in', array_keys($sids))
  6889. ->update([
  6890. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  6891. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6892. 'pick_company_name' => '',
  6893. 'pick_time' => null,
  6894. 'sys_rq' => null,
  6895. 'mod_rq' => null,
  6896. ]);
  6897. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  6898. foreach (array_keys($sids) as $sid) {
  6899. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  6900. }
  6901. return $sids;
  6902. }
  6903. /**
  6904. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  6905. *
  6906. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6907. */
  6908. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  6909. {
  6910. $scydgyId = trim($scydgyId);
  6911. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6912. if ($scydgyId === '') {
  6913. return $empty;
  6914. }
  6915. try {
  6916. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6917. } catch (\Throwable $e) {
  6918. $anchor = null;
  6919. }
  6920. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  6921. return $empty;
  6922. }
  6923. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6924. if ($ccydh === '') {
  6925. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6926. }
  6927. try {
  6928. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6929. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6930. $pos = $query->order('scydgy_id', 'asc')->select();
  6931. } catch (\Throwable $e) {
  6932. $pos = [$anchor];
  6933. }
  6934. if (!is_array($pos) || $pos === []) {
  6935. $pos = [$anchor];
  6936. }
  6937. return [
  6938. 'ccydh' => $ccydh,
  6939. 'pos' => $pos,
  6940. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6941. ];
  6942. }
  6943. protected function purchaseOrderRowIsCompleted(array $po): bool
  6944. {
  6945. $st = $po['status'] ?? null;
  6946. if ($st === 1 || $st === '1') {
  6947. return true;
  6948. }
  6949. if (is_string($st) && trim($st) === '1') {
  6950. return true;
  6951. }
  6952. return is_numeric($st) && (int)$st === 1;
  6953. }
  6954. /**
  6955. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  6956. */
  6957. public function auditAbandon()
  6958. {
  6959. if (!$this->request->isPost()) {
  6960. $this->error(__('Invalid parameters'));
  6961. }
  6962. $anchorIds = [];
  6963. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6964. if ($batchRaw !== '') {
  6965. $decoded = json_decode($batchRaw, true);
  6966. if (is_array($decoded)) {
  6967. foreach ($decoded as $id) {
  6968. $s = trim((string)$id);
  6969. if ($s !== '') {
  6970. $anchorIds[] = $s;
  6971. }
  6972. }
  6973. }
  6974. }
  6975. if ($anchorIds === []) {
  6976. $single = trim((string)$this->request->post('scydgy_id', ''));
  6977. if ($single !== '') {
  6978. $anchorIds[] = $single;
  6979. }
  6980. }
  6981. if ($anchorIds === []) {
  6982. $this->error('请至少选择一条订单');
  6983. }
  6984. $processedCcydh = [];
  6985. $doneOrders = 0;
  6986. $allSids = [];
  6987. Db::startTrans();
  6988. try {
  6989. foreach ($anchorIds as $anchorId) {
  6990. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  6991. if (($bundle['pos'] ?? []) === []) {
  6992. continue;
  6993. }
  6994. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6995. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6996. if (isset($processedCcydh[$dedupeKey])) {
  6997. continue;
  6998. }
  6999. $processedCcydh[$dedupeKey] = true;
  7000. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7001. if ($sids === []) {
  7002. continue;
  7003. }
  7004. $doneOrders++;
  7005. foreach (array_keys($sids) as $sid) {
  7006. $allSids[(int)$sid] = true;
  7007. }
  7008. }
  7009. if ($doneOrders < 1) {
  7010. throw new \Exception('所选订单均不在待确认供应商状态');
  7011. }
  7012. Db::commit();
  7013. } catch (\Throwable $e) {
  7014. Db::rollback();
  7015. $this->error($e->getMessage());
  7016. }
  7017. $this->pickHiddenScydgySetCache = null;
  7018. $msg = $doneOrders > 1
  7019. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7020. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7021. $this->success($msg);
  7022. }
  7023. /**
  7024. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7025. */
  7026. public function archiveAbandon()
  7027. {
  7028. if (!$this->request->isPost()) {
  7029. $this->error(__('Invalid parameters'));
  7030. }
  7031. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7032. $this->error(__('You have no permission'));
  7033. }
  7034. $anchorIds = [];
  7035. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7036. if ($batchRaw !== '') {
  7037. $decoded = json_decode($batchRaw, true);
  7038. if (is_array($decoded)) {
  7039. foreach ($decoded as $id) {
  7040. $s = trim((string)$id);
  7041. if ($s !== '') {
  7042. $anchorIds[] = $s;
  7043. }
  7044. }
  7045. }
  7046. }
  7047. if ($anchorIds === []) {
  7048. $single = trim((string)$this->request->post('scydgy_id', ''));
  7049. if ($single !== '') {
  7050. $anchorIds[] = $single;
  7051. }
  7052. }
  7053. if ($anchorIds === []) {
  7054. $this->error('请至少选择一条订单');
  7055. }
  7056. $processedCcydh = [];
  7057. $doneOrders = 0;
  7058. Db::startTrans();
  7059. try {
  7060. foreach ($anchorIds as $anchorId) {
  7061. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7062. if (($bundle['pos'] ?? []) === []) {
  7063. continue;
  7064. }
  7065. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7066. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7067. if (isset($processedCcydh[$dedupeKey])) {
  7068. continue;
  7069. }
  7070. $processedCcydh[$dedupeKey] = true;
  7071. $sids = $this->abandonOrderBundleToPick(
  7072. $bundle,
  7073. 'archive_abandon',
  7074. ',从历史存证退回协助初选'
  7075. );
  7076. if ($sids === []) {
  7077. continue;
  7078. }
  7079. $doneOrders++;
  7080. }
  7081. if ($doneOrders < 1) {
  7082. throw new \Exception('所选订单均不是已完结状态');
  7083. }
  7084. Db::commit();
  7085. } catch (\Throwable $e) {
  7086. Db::rollback();
  7087. $this->error($e->getMessage());
  7088. }
  7089. $this->pickHiddenScydgySetCache = null;
  7090. $msg = $doneOrders > 1
  7091. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7092. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7093. $this->success($msg);
  7094. }
  7095. /**
  7096. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7097. */
  7098. public function purchaseApprovalReject()
  7099. {
  7100. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7101. $this->error(__('Invalid parameters'));
  7102. }
  7103. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7104. $this->error(__('You have no permission'));
  7105. }
  7106. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7107. $decoded = json_decode($batchRaw, true);
  7108. if (!is_array($decoded) || $decoded === []) {
  7109. $this->error('提交数据无效');
  7110. }
  7111. $done = 0;
  7112. Db::startTrans();
  7113. try {
  7114. foreach ($decoded as $item) {
  7115. if (!is_array($item)) {
  7116. continue;
  7117. }
  7118. $sid = (int)($item['scydgy_id'] ?? 0);
  7119. if (!$this->isValidScydgyRowId($sid)) {
  7120. continue;
  7121. }
  7122. $this->runPurchaseApprovalRejectForSid($sid);
  7123. $done++;
  7124. }
  7125. if ($done < 1) {
  7126. throw new \Exception('所选订单均不在待审批状态');
  7127. }
  7128. Db::commit();
  7129. } catch (\Throwable $e) {
  7130. Db::rollback();
  7131. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7132. }
  7133. $this->pickHiddenScydgySetCache = null;
  7134. $this->success('已驳回并退回「协助审批下发」');
  7135. }
  7136. /**
  7137. * @throws \Exception
  7138. */
  7139. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7140. {
  7141. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7142. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7143. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7144. $allIds = $this->purchaseOrderDetail($sid);
  7145. if ($allIds === []) {
  7146. throw new \Exception('未找到下发明细');
  7147. }
  7148. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7149. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7150. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7151. 'pick_company_name' => '',
  7152. ]);
  7153. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7154. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7155. $poId = 0;
  7156. try {
  7157. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7158. if (is_array($po)) {
  7159. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7160. }
  7161. } catch (\Throwable $e) {
  7162. }
  7163. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7164. }
  7165. /**
  7166. * 审核弹窗(旧入口,POST 已关闭)
  7167. */
  7168. public function review()
  7169. {
  7170. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7171. $this->error(__('You have no permission'));
  7172. }
  7173. if ($this->request->isPost()) {
  7174. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7175. }
  7176. $this->view->assign('pickMode', 0);
  7177. return $this->view->fetch('procuremen/review');
  7178. }
  7179. /**
  7180. * 审核弹窗获取公司列表
  7181. */
  7182. public function reviewCompanies()
  7183. {
  7184. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  7185. $this->error(__('You have no permission'));
  7186. }
  7187. if (!$this->request->isAjax()) {
  7188. $this->error(__('Invalid parameters'));
  7189. }
  7190. $list = [];
  7191. try {
  7192. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7193. $rows = Db::table('customer')
  7194. ->where(function ($q) {
  7195. $q->where('status', 1)
  7196. ->whereOr('status', '1')
  7197. ->whereOr('status', '')
  7198. ->whereNull('status');
  7199. })
  7200. ->order('id', 'desc')
  7201. ->select();
  7202. } catch (\Throwable $e) {
  7203. $this->success('', '', []);
  7204. return;
  7205. }
  7206. if (!is_array($rows)) {
  7207. $this->success('', '', []);
  7208. return;
  7209. }
  7210. $detailColCandidates = [
  7211. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7212. 'company_detail', 'company_desc', 'address',
  7213. ];
  7214. foreach ($rows as $row) {
  7215. if (!is_array($row)) {
  7216. continue;
  7217. }
  7218. $norm = [];
  7219. foreach ($row as $k => $v) {
  7220. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7221. }
  7222. $row = $norm;
  7223. $st = $row['status'] ?? '';
  7224. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7225. continue;
  7226. }
  7227. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7228. if ($payload === null) {
  7229. continue;
  7230. }
  7231. $detail = '';
  7232. foreach ($detailColCandidates as $dk) {
  7233. if (!isset($row[$dk])) {
  7234. continue;
  7235. }
  7236. $dv = trim((string)$row[$dk]);
  7237. if ($dv !== '') {
  7238. $detail = $dv;
  7239. break;
  7240. }
  7241. }
  7242. $payload['detail'] = $detail;
  7243. $list[] = $this->maskSupplierContactFields($payload);
  7244. }
  7245. $this->success('', '', $list);
  7246. }
  7247. /**
  7248. * 采购确认-下发明细弹窗:
  7249. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7250. */
  7251. public function outward_detail()
  7252. {
  7253. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7254. if (is_array($ids)) {
  7255. $ids = isset($ids[0]) ? $ids[0] : '';
  7256. }
  7257. $ids = trim((string)$ids);
  7258. if ($ids === '') {
  7259. $this->error(__('Invalid parameters'));
  7260. }
  7261. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7262. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7263. $wffTab = 'all';
  7264. }
  7265. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7266. $purchaseOrderId = 0;
  7267. $po = null;
  7268. try {
  7269. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7270. if (is_array($po)) {
  7271. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7272. }
  7273. } catch (\Throwable $e) {
  7274. $purchaseOrderId = 0;
  7275. $po = null;
  7276. }
  7277. if (!$isPurchaseConfirm && is_array($po)) {
  7278. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7279. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7280. $isPurchaseConfirm = true;
  7281. }
  7282. }
  7283. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7284. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7285. $confirmProcessCount = 1;
  7286. $confirmPickGroups = [];
  7287. $processDisplayRows = [];
  7288. $allDetailsBySid = [];
  7289. $requiredSidList = [];
  7290. $sidList = [$ids];
  7291. if ($isPurchaseConfirm) {
  7292. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7293. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7294. if ($mergeRows !== []) {
  7295. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7296. }
  7297. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7298. if ($confirmBundle['pos'] !== []) {
  7299. $sidList = [];
  7300. foreach ($confirmBundle['pos'] as $poRow) {
  7301. if (!is_array($poRow)) {
  7302. continue;
  7303. }
  7304. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7305. if (!$this->isValidScydgyRowId($sid)) {
  7306. continue;
  7307. }
  7308. $sidList[] = (string)$sid;
  7309. $requiredSidList[] = $sid;
  7310. }
  7311. }
  7312. if ($sidList === []) {
  7313. $sidList = [$ids];
  7314. $requiredSidList = [(int)$ids];
  7315. }
  7316. $confirmProcessCount = max(1, count($requiredSidList));
  7317. if (is_array($po) && $purchaseOrderId <= 0) {
  7318. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7319. }
  7320. }
  7321. $rows = [];
  7322. try {
  7323. if (count($sidList) === 1) {
  7324. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7325. } else {
  7326. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7327. }
  7328. } catch (\Throwable $e) {
  7329. $rows = [];
  7330. }
  7331. if ($isPurchaseConfirm) {
  7332. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7333. }
  7334. foreach ($rows as &$r) {
  7335. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7336. $r['id'] = $r['ID'];
  7337. }
  7338. if (isset($r['createtime'])) {
  7339. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7340. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7341. } else {
  7342. $r['createtime_text'] = (string)$r['createtime'];
  7343. }
  7344. } else {
  7345. $r['createtime_text'] = '';
  7346. }
  7347. if (is_array($r)) {
  7348. $r = $this->maskSupplierContactFields($r);
  7349. }
  7350. }
  7351. unset($r);
  7352. $pickedCompanyName = '';
  7353. if ($isPurchaseConfirm) {
  7354. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7355. if (!is_array($poRow)) {
  7356. continue;
  7357. }
  7358. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7359. if ($pn !== '') {
  7360. $pickedCompanyName = $pn;
  7361. break;
  7362. }
  7363. }
  7364. }
  7365. $this->view->assign('rows', $rows ?: []);
  7366. $this->view->assign('rowCount', count($rows ?: []));
  7367. $this->view->assign('scydgyId', $ids);
  7368. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7369. $this->view->assign('headTitle', $headTitle);
  7370. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7371. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7372. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7373. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7374. $this->view->assign('processDisplayRows', $processDisplayRows);
  7375. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  7376. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  7377. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  7378. $sysRqDisplay = '—';
  7379. if ($isPurchaseConfirm) {
  7380. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  7381. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  7382. );
  7383. }
  7384. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  7385. $this->view->assign('sysRq', $isPurchaseConfirm
  7386. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  7387. : '');
  7388. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  7389. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  7390. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  7391. if ($isPurchaseConfirm) {
  7392. return $this->view->fetch();
  7393. }
  7394. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7395. $this->view->engine->layout(false);
  7396. try {
  7397. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  7398. $this->view->assign('dialogBody', $bodyHtml);
  7399. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  7400. } finally {
  7401. if ($restoreLayout) {
  7402. $this->view->engine->layout($restoreLayout);
  7403. }
  7404. }
  7405. }
  7406. /**
  7407. * 月度导出记录表(不存在时自动创建)
  7408. */
  7409. protected function ensurePurchaseMonthExportLogTable(): void
  7410. {
  7411. try {
  7412. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  7413. } catch (\Throwable $e) {
  7414. Db::execute(
  7415. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  7416. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  7417. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  7418. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  7419. `admin_name` varchar(64) NOT NULL DEFAULT '',
  7420. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  7421. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  7422. `createtime` int(10) unsigned DEFAULT NULL,
  7423. PRIMARY KEY (`id`),
  7424. KEY `idx_ym` (`ym`),
  7425. KEY `idx_ct` (`createtime`)
  7426. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  7427. );
  7428. }
  7429. }
  7430. /**
  7431. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  7432. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  7433. */
  7434. public function export_month_outward()
  7435. {
  7436. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  7437. $this->error(__('You have no permission'));
  7438. }
  7439. $this->request->filter(['strip_tags', 'trim']);
  7440. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  7441. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  7442. $ym = date('Y-m');
  7443. }
  7444. $dbRows = [];
  7445. try {
  7446. $query = Db::table('purchase_order');
  7447. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7448. $dbRows = $query->select();
  7449. } catch (\Throwable $e) {
  7450. $dbRows = [];
  7451. }
  7452. if (!is_array($dbRows)) {
  7453. $dbRows = [];
  7454. }
  7455. $completeTsMap = [];
  7456. $sidList = [];
  7457. foreach ($dbRows as $dbRow) {
  7458. if (!is_array($dbRow)) {
  7459. continue;
  7460. }
  7461. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  7462. if ($sid > 0) {
  7463. $sidList[$sid] = true;
  7464. }
  7465. }
  7466. if ($sidList !== []) {
  7467. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  7468. }
  7469. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  7470. if (!is_array($dbRow)) {
  7471. return false;
  7472. }
  7473. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  7474. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  7475. }));
  7476. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  7477. $filtered = $pool;
  7478. $mainBySid = [];
  7479. foreach ($filtered as $rw) {
  7480. if (!is_array($rw)) {
  7481. continue;
  7482. }
  7483. $rid = (int)($rw['ID'] ?? 0);
  7484. if ($rid > 0) {
  7485. $mainBySid[$rid] = $rw;
  7486. }
  7487. }
  7488. if ($mainBySid === []) {
  7489. $detailRows = [];
  7490. } else {
  7491. try {
  7492. $detailRows = Db::table('purchase_order_detail')
  7493. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7494. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7495. ->order('status', 'desc')
  7496. ->order('CCYDH', 'asc')
  7497. ->order('company_name', 'asc')
  7498. ->order('id', 'asc')
  7499. ->select();
  7500. } catch (\Throwable $e) {
  7501. try {
  7502. $detailRows = Db::table('purchase_order_detail')
  7503. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7504. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7505. ->order('status', 'desc')
  7506. ->order('CCYDH', 'asc')
  7507. ->order('company_name', 'asc')
  7508. ->order('ID', 'asc')
  7509. ->select();
  7510. } catch (\Throwable $e2) {
  7511. $detailRows = [];
  7512. }
  7513. }
  7514. }
  7515. if (!is_array($detailRows)) {
  7516. $detailRows = [];
  7517. }
  7518. $exportLines = [];
  7519. $detailSidSeen = [];
  7520. foreach ($detailRows as $dr) {
  7521. if (!is_array($dr)) {
  7522. continue;
  7523. }
  7524. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7525. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7526. continue;
  7527. }
  7528. if (isset($detailSidSeen[$sid])) {
  7529. continue;
  7530. }
  7531. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  7532. continue;
  7533. }
  7534. $detailSidSeen[$sid] = true;
  7535. $m = $mainBySid[$sid];
  7536. $exportLines[] = [
  7537. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7538. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7539. 'company_name' => (string)($dr['company_name'] ?? ''),
  7540. 'CDF' => (string)($m['CDF'] ?? ''),
  7541. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7542. 'gx' => $this->procuremenExportGxText($m),
  7543. 'detail' => $dr,
  7544. ];
  7545. }
  7546. foreach ($detailRows as $dr) {
  7547. if (!is_array($dr)) {
  7548. continue;
  7549. }
  7550. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7551. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  7552. continue;
  7553. }
  7554. $detailSidSeen[$sid] = true;
  7555. $m = $mainBySid[$sid];
  7556. $exportLines[] = [
  7557. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7558. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7559. 'company_name' => (string)($dr['company_name'] ?? ''),
  7560. 'CDF' => (string)($m['CDF'] ?? ''),
  7561. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7562. 'gx' => $this->procuremenExportGxText($m),
  7563. 'detail' => $dr,
  7564. ];
  7565. }
  7566. foreach ($mainBySid as $sid => $m) {
  7567. if (isset($detailSidSeen[$sid])) {
  7568. continue;
  7569. }
  7570. $company = trim((string)($m['pick_company_name'] ?? ''));
  7571. $exportLines[] = [
  7572. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  7573. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  7574. 'company_name' => $company,
  7575. 'CDF' => (string)($m['CDF'] ?? ''),
  7576. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7577. 'gx' => $this->procuremenExportGxText($m),
  7578. 'detail' => [],
  7579. ];
  7580. }
  7581. $groups = [];
  7582. foreach ($exportLines as $line) {
  7583. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  7584. if (!isset($groups[$k])) {
  7585. $groups[$k] = [];
  7586. }
  7587. $groups[$k][] = $line;
  7588. }
  7589. ksort($groups, SORT_STRING);
  7590. $spreadsheet = new Spreadsheet();
  7591. $sheet = $spreadsheet->getActiveSheet();
  7592. $sheet->setTitle('外协加工明细');
  7593. $mon = (int)substr($ym, 5, 2);
  7594. $sheet->mergeCells('A1:H1');
  7595. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  7596. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  7597. $sheet->getStyle('A1')->getAlignment()
  7598. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7599. ->setVertical(Alignment::VERTICAL_CENTER);
  7600. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  7601. $col = 'A';
  7602. foreach ($headers as $h) {
  7603. $sheet->setCellValue($col . '2', $h);
  7604. $col++;
  7605. }
  7606. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  7607. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7608. $rowNum = 3;
  7609. $sumSubtotalCounts = 0;
  7610. $grandAmount = 0.0;
  7611. $globalSeq = 0;
  7612. if ($groups === []) {
  7613. $sheet->mergeCells('A3:H3');
  7614. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  7615. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7616. $rowNum = 4;
  7617. } else {
  7618. foreach ($groups as $items) {
  7619. if ($items === []) {
  7620. continue;
  7621. }
  7622. $groupLineCount = count($items);
  7623. $subAmount = 0.0;
  7624. foreach ($items as $line) {
  7625. $globalSeq++;
  7626. $dr = $line['detail'];
  7627. $amt = $this->procuremenExportAmount($dr);
  7628. $subAmount += $amt;
  7629. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  7630. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  7631. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  7632. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  7633. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  7634. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  7635. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  7636. $sheet->setCellValue('H' . $rowNum, $amt);
  7637. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  7638. $rowNum++;
  7639. }
  7640. $sumSubtotalCounts += $groupLineCount;
  7641. $grandAmount += $subAmount;
  7642. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7643. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  7644. $sheet->getStyle('G' . $rowNum)->getAlignment()
  7645. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7646. ->setVertical(Alignment::VERTICAL_CENTER);
  7647. $rowNum++;
  7648. }
  7649. }
  7650. $sheet->setCellValue('A' . $rowNum, '总计');
  7651. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  7652. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7653. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  7654. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7655. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  7656. $lastRow = $rowNum;
  7657. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  7658. 'borders' => [
  7659. 'allBorders' => [
  7660. 'borderStyle' => Border::BORDER_THIN,
  7661. 'color' => ['rgb' => '000000'],
  7662. ],
  7663. ],
  7664. ]);
  7665. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7666. if ($lastRow >= 3) {
  7667. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7668. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7669. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7670. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7671. }
  7672. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  7673. $sheet->getColumnDimension('A')->setWidth(7);
  7674. $sheet->getColumnDimension('B')->setWidth(16);
  7675. $sheet->getColumnDimension('C')->setWidth(52);
  7676. $sheet->getColumnDimension('D')->setWidth(32);
  7677. $sheet->getColumnDimension('E')->setWidth(12);
  7678. $sheet->getColumnDimension('F')->setWidth(44);
  7679. $sheet->getColumnDimension('G')->setWidth(26);
  7680. $sheet->getColumnDimension('H')->setWidth(13);
  7681. $sheet->getRowDimension(1)->setRowHeight(28);
  7682. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  7683. $quoteStartRow = $lastRow + 3;
  7684. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  7685. if ($quoteLastRow >= $quoteStartRow) {
  7686. $sheet->getColumnDimension('E')->setWidth(28);
  7687. }
  7688. $ymCompact = str_replace('-', '', $ym);
  7689. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  7690. $filename = $fileBase . '.xlsx';
  7691. try {
  7692. $this->ensurePurchaseMonthExportLogTable();
  7693. list($adminId, $adminName) = $this->GetUseName();
  7694. Db::table('purchase_month_export_log')->insert([
  7695. 'ym' => $ym,
  7696. 'admin_id' => (int)$adminId,
  7697. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  7698. 'row_count' => count($exportLines),
  7699. 'total_amount' => round($grandAmount, 2),
  7700. 'createtime' => time(),
  7701. ]);
  7702. } catch (\Throwable $e) {
  7703. Log::write('month export log: ' . $e->getMessage(), 'error');
  7704. }
  7705. if (ob_get_length()) {
  7706. ob_end_clean();
  7707. }
  7708. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  7709. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  7710. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  7711. header('Cache-Control: max-age=0');
  7712. $writer = new Xlsx($spreadsheet);
  7713. $writer->save('php://output');
  7714. $spreadsheet->disconnectWorksheets();
  7715. unset($spreadsheet);
  7716. exit;
  7717. }
  7718. /**
  7719. * 导出用:工序列文案
  7720. */
  7721. protected function procuremenExportGxText(array $r)
  7722. {
  7723. $a = trim((string)($r['CDXMC'] ?? ''));
  7724. $b = trim((string)($r['CGYMC'] ?? ''));
  7725. if ($a !== '' && $b !== '') {
  7726. return $a . ':' . $b;
  7727. }
  7728. return $a !== '' ? $a : $b;
  7729. }
  7730. /**
  7731. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  7732. */
  7733. protected function procuremenExportAmount(array $r)
  7734. {
  7735. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  7736. if (!array_key_exists($k, $r)) {
  7737. continue;
  7738. }
  7739. $v = $r[$k];
  7740. if ($v === null || $v === '') {
  7741. continue;
  7742. }
  7743. if (is_numeric($v)) {
  7744. return (float)$v;
  7745. }
  7746. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  7747. if ($v !== '' && is_numeric($v)) {
  7748. return (float)$v;
  7749. }
  7750. }
  7751. return 0.0;
  7752. }
  7753. /**
  7754. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  7755. *
  7756. * @param array<int, array<string, mixed>> $detailRows
  7757. * @param array<int, array<string, mixed>> $mainBySid
  7758. * @return array<int, array<string, mixed>>
  7759. */
  7760. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  7761. {
  7762. $lines = [];
  7763. foreach ($detailRows as $dr) {
  7764. if (!is_array($dr)) {
  7765. continue;
  7766. }
  7767. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7768. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7769. continue;
  7770. }
  7771. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  7772. continue;
  7773. }
  7774. $cn = trim((string)($dr['company_name'] ?? ''));
  7775. if ($cn === '') {
  7776. continue;
  7777. }
  7778. $m = $mainBySid[$sid];
  7779. $am = trim((string)($dr['amount'] ?? ''));
  7780. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7781. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  7782. $amountText = $amountFilled
  7783. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7784. : '未填写';
  7785. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  7786. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  7787. if ($deliveryShow === '' && $deliveryRaw !== '') {
  7788. $deliveryShow = $deliveryRaw;
  7789. }
  7790. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  7791. ? $deliveryShow
  7792. : '未填写';
  7793. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  7794. $lines[] = [
  7795. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7796. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7797. 'gx' => $this->procuremenExportGxText($m),
  7798. 'company_name' => $cn,
  7799. 'amount_text' => $amountText,
  7800. 'amount_num' => $amountFilled ? $amountNum : null,
  7801. 'delivery_text' => $deliveryText,
  7802. 'picked_text' => $picked ? '中标' : '未中标',
  7803. 'picked' => $picked,
  7804. ];
  7805. }
  7806. $winnerSupplierByOrder = [];
  7807. foreach ($lines as $line) {
  7808. $dh = trim((string)($line['CCYDH'] ?? ''));
  7809. $cn = trim((string)($line['company_name'] ?? ''));
  7810. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  7811. $winnerSupplierByOrder[$dh][$cn] = true;
  7812. }
  7813. }
  7814. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  7815. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  7816. if ($c !== 0) {
  7817. return $c;
  7818. }
  7819. $dh = trim((string)($a['CCYDH'] ?? ''));
  7820. $aCn = trim((string)($a['company_name'] ?? ''));
  7821. $bCn = trim((string)($b['company_name'] ?? ''));
  7822. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  7823. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  7824. if ($aSupplierWin !== $bSupplierWin) {
  7825. return $aSupplierWin ? -1 : 1;
  7826. }
  7827. $c = strcmp($aCn, $bCn);
  7828. if ($c !== 0) {
  7829. return $c;
  7830. }
  7831. if (!empty($a['picked']) !== !empty($b['picked'])) {
  7832. return !empty($a['picked']) ? -1 : 1;
  7833. }
  7834. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  7835. if ($c !== 0) {
  7836. return $c;
  7837. }
  7838. return 0;
  7839. });
  7840. return $lines;
  7841. }
  7842. /**
  7843. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  7844. *
  7845. * @param array<int, array<string, mixed>> $quoteLines
  7846. */
  7847. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  7848. {
  7849. $mon = (int)substr($ym, 5, 2);
  7850. $titleRow = $startRow;
  7851. $headerRow = $startRow + 1;
  7852. $dataStartRow = $startRow + 2;
  7853. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  7854. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  7855. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  7856. $sheet->getStyle('A' . $titleRow)->getAlignment()
  7857. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7858. ->setVertical(Alignment::VERTICAL_CENTER);
  7859. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  7860. $col = 'A';
  7861. foreach ($headers as $h) {
  7862. $sheet->setCellValue($col . $headerRow, $h);
  7863. $col++;
  7864. }
  7865. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  7866. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7867. $rowNum = $dataStartRow;
  7868. if ($quoteLines === []) {
  7869. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  7870. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  7871. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7872. $rowNum = $dataStartRow + 1;
  7873. } else {
  7874. $i = 0;
  7875. foreach ($quoteLines as $line) {
  7876. $i++;
  7877. $sheet->setCellValue('A' . $rowNum, $i);
  7878. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  7879. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  7880. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  7881. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  7882. if ($line['amount_num'] !== null) {
  7883. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  7884. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  7885. } else {
  7886. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  7887. }
  7888. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  7889. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  7890. if (!empty($line['picked'])) {
  7891. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7892. }
  7893. $rowNum++;
  7894. }
  7895. }
  7896. $lastRow = $rowNum - 1;
  7897. if ($lastRow >= $headerRow) {
  7898. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  7899. 'borders' => [
  7900. 'allBorders' => [
  7901. 'borderStyle' => Border::BORDER_THIN,
  7902. 'color' => ['rgb' => '000000'],
  7903. ],
  7904. ],
  7905. ]);
  7906. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7907. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7908. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7909. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7910. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  7911. if ($lastRow >= $dataStartRow) {
  7912. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  7913. }
  7914. }
  7915. return $lastRow;
  7916. }
  7917. /**
  7918. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  7919. */
  7920. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  7921. {
  7922. if ($lastRow < $dataStartRow || $headerRow < 1) {
  7923. return;
  7924. }
  7925. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  7926. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7927. ->setVertical(Alignment::VERTICAL_CENTER);
  7928. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  7929. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7930. ->setVertical(Alignment::VERTICAL_CENTER);
  7931. if ($lastCol > 'B') {
  7932. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  7933. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7934. ->setVertical(Alignment::VERTICAL_CENTER);
  7935. }
  7936. }
  7937. /**
  7938. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  7939. */
  7940. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  7941. {
  7942. $s = trim($ccydh);
  7943. if ($s === '') {
  7944. return 'ORDER';
  7945. }
  7946. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  7947. $s = trim($s, '._-');
  7948. if ($s === '') {
  7949. return 'ORDER';
  7950. }
  7951. if (function_exists('mb_substr')) {
  7952. return mb_substr($s, 0, 80, 'UTF-8');
  7953. }
  7954. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  7955. }
  7956. /**
  7957. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  7958. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  7959. *
  7960. * @return array{objectKey: string, webPath: string}
  7961. */
  7962. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  7963. {
  7964. $sid = (int)$scydgyId;
  7965. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  7966. $y = date('Y');
  7967. $m = date('m');
  7968. $d = date('d');
  7969. $basename = $safeOrder . '_' . $sid . '.pdf';
  7970. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  7971. return [
  7972. 'objectKey' => $objectKey,
  7973. 'webPath' => '/' . $objectKey,
  7974. ];
  7975. }
  7976. /**
  7977. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  7978. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  7979. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  7980. *
  7981. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  7982. */
  7983. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  7984. {
  7985. if (!$this->isValidScydgyRowId($scydgyId)) {
  7986. return '';
  7987. }
  7988. $ids = trim((string)$scydgyId);
  7989. $prep = $this->prepareProcuremenDetailsView($ids);
  7990. if (!$prep['ok']) {
  7991. return '';
  7992. }
  7993. $ccydh = $prep['ccydh'];
  7994. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  7995. $objectKey = $paths['objectKey'];
  7996. $webPath = $paths['webPath'];
  7997. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  7998. $this->view->assign([
  7999. 'pdf_export' => 1,
  8000. 'pdfMetaLine' => $meta,
  8001. ]);
  8002. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8003. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8004. $this->view->engine->layout(false);
  8005. try {
  8006. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8007. } catch (\Throwable $e) {
  8008. if ($restoreLayout) {
  8009. $this->view->engine->layout($restoreLayout);
  8010. }
  8011. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8012. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8013. return '';
  8014. }
  8015. if ($restoreLayout) {
  8016. $this->view->engine->layout($restoreLayout);
  8017. }
  8018. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8019. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8020. if (!is_dir($tempDir)) {
  8021. @mkdir($tempDir, 0755, true);
  8022. }
  8023. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8024. try {
  8025. $mpdf = new \Mpdf\Mpdf([
  8026. 'mode' => 'utf-8',
  8027. 'format' => 'A4',
  8028. 'margin_left' => 12,
  8029. 'margin_right' => 12,
  8030. 'margin_top' => 14,
  8031. 'margin_bottom' => 14,
  8032. 'tempDir' => $tempDir,
  8033. 'autoScriptToLang' => true,
  8034. 'autoLangToFont' => true,
  8035. ]);
  8036. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8037. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8038. $mpdf->SetBasePath('http://127.0.0.1/');
  8039. $mpdf->WriteHTML($html);
  8040. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8041. } catch (\Throwable $e) {
  8042. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8043. if (is_file($tempPdf)) {
  8044. @unlink($tempPdf);
  8045. }
  8046. return '';
  8047. }
  8048. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8049. if ($ossUrl !== '') {
  8050. @unlink($tempPdf);
  8051. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8052. return $ossUrl;
  8053. }
  8054. $pi = pathinfo($objectKey);
  8055. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8056. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8057. if ($baseFile === '') {
  8058. @unlink($tempPdf);
  8059. return '';
  8060. }
  8061. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8062. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8063. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8064. @unlink($tempPdf);
  8065. return '';
  8066. }
  8067. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8068. if (!@copy($tempPdf, $fullPath)) {
  8069. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8070. @unlink($tempPdf);
  8071. return '';
  8072. }
  8073. @unlink($tempPdf);
  8074. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8075. return $webPath;
  8076. }
  8077. /**
  8078. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8079. */
  8080. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8081. {
  8082. if ($scydgyId <= 0 || $webPath === '') {
  8083. return;
  8084. }
  8085. try {
  8086. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8087. } catch (\Throwable $e) {
  8088. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8089. }
  8090. }
  8091. /**
  8092. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8093. *
  8094. * @param array<string, string> $vars
  8095. * @return array<string, string>
  8096. */
  8097. protected function normalizeSmsTemplateVars(array $vars): array
  8098. {
  8099. $out = [];
  8100. foreach ($vars as $k => $v) {
  8101. $out[(string)$k] = trim((string)$v);
  8102. }
  8103. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8104. $out['contact_name'] = $out['company_name'];
  8105. }
  8106. return $out;
  8107. }
  8108. /**
  8109. * 按手机号或公司名称查 customer 表联系人姓名
  8110. */
  8111. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8112. {
  8113. $phone = trim($phone);
  8114. $companyName = trim($companyName);
  8115. try {
  8116. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8117. $row = Db::table('customer')
  8118. ->where(function ($q) use ($phone) {
  8119. $q->where('phone', $phone)->whereOr('account', $phone);
  8120. })
  8121. ->order('id', 'asc')
  8122. ->find();
  8123. if (is_array($row)) {
  8124. $nm = trim((string)($row['username'] ?? ''));
  8125. if ($nm !== '') {
  8126. return $nm;
  8127. }
  8128. }
  8129. }
  8130. if ($companyName !== '') {
  8131. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8132. if (is_array($row)) {
  8133. return trim((string)($row['username'] ?? ''));
  8134. }
  8135. }
  8136. } catch (\Throwable $e) {
  8137. }
  8138. return '';
  8139. }
  8140. /**
  8141. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8142. */
  8143. protected function plainTextToHtmlEmailBody(string $text): string
  8144. {
  8145. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8146. $parts = explode("\n", $text);
  8147. $out = [];
  8148. foreach ($parts as $line) {
  8149. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8150. $out[] = $line;
  8151. } else {
  8152. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8153. }
  8154. }
  8155. return implode("<br>\n", $out);
  8156. }
  8157. /**
  8158. * 短信场景:去掉链接类变量,避免误填 URL
  8159. *
  8160. * @param array<string, string> $vars
  8161. * @return array<string, string>
  8162. */
  8163. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8164. {
  8165. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8166. return $vars;
  8167. }
  8168. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8169. $vars[$k] = '';
  8170. }
  8171. return $vars;
  8172. }
  8173. /**
  8174. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8175. *
  8176. * @param array<string, string> $vars
  8177. */
  8178. protected function renderNotifyTemplate(string $scene, array $vars): string
  8179. {
  8180. $vars = $this->normalizeSmsTemplateVars($vars);
  8181. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8182. $row = $this->loadNotifyTemplateRow($scene);
  8183. if ($row === null) {
  8184. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8185. }
  8186. $tpl = trim((string)($row['content'] ?? ''));
  8187. if ($tpl === '') {
  8188. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8189. }
  8190. foreach ($vars as $k => $v) {
  8191. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8192. }
  8193. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8194. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8195. return $tpl;
  8196. }
  8197. protected function resolveProcuremenEmailSubject(string $scene): string
  8198. {
  8199. $map = [
  8200. 'review_email' => '您有新的协助加工订单',
  8201. ];
  8202. $subject = trim((string)($map[$scene] ?? ''));
  8203. if ($subject === '') {
  8204. $this->error('未配置邮件主题:' . $scene);
  8205. }
  8206. return $subject;
  8207. }
  8208. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8209. {
  8210. $map = [
  8211. 'review_email' => '协助下发-邮箱',
  8212. 'review_sms' => '协助下发-短信',
  8213. 'confirm_ok' => '采购确认-通过',
  8214. 'confirm_fail' => '采购确认-未通过',
  8215. 'bid_open' => '开标双重验证',
  8216. ];
  8217. $label = $map[$scene] ?? $scene;
  8218. if ($titleRequired) {
  8219. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8220. }
  8221. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8222. }
  8223. /**
  8224. * 是否开启协助通知演练(不发真实短信/邮件)
  8225. */
  8226. protected function isProcuremenNotifyDryRun(): bool
  8227. {
  8228. return (bool)Config::get('procuremen_notify_dry_run');
  8229. }
  8230. /**
  8231. * @param array<string, mixed> $payload
  8232. */
  8233. protected function recordNotifyDryRunPreview(array $payload): void
  8234. {
  8235. $this->notifyDryRunPreview[] = $payload;
  8236. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8237. }
  8238. /**
  8239. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8240. * @throws \Exception
  8241. */
  8242. protected function smsbao($phone, $content)
  8243. {
  8244. if ($this->isProcuremenNotifyDryRun()) {
  8245. $this->recordNotifyDryRunPreview([
  8246. 'scene' => 'sms_only',
  8247. 'phone' => $phone,
  8248. 'sms_content' => $content,
  8249. ]);
  8250. return;
  8251. }
  8252. $statusStr = [
  8253. '0' => '短信发送成功',
  8254. '-1' => '参数不全',
  8255. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8256. '30' => '密码错误',
  8257. '40' => '账号不存在',
  8258. '41' => '余额不足',
  8259. '42' => '帐户已过期',
  8260. '43' => 'IP地址限制',
  8261. '50' => '内容含有敏感词',
  8262. ];
  8263. $smsapi = 'http://api.smsbao.com/';
  8264. $user = 'zhuwei123';
  8265. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8266. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8267. $result = @file_get_contents($sendurl);
  8268. if ($result === false) {
  8269. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  8270. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  8271. }
  8272. $result = trim((string)$result);
  8273. if ($result !== '0') {
  8274. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  8275. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  8276. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  8277. }
  8278. }
  8279. }