Procuremen.php 486 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924
  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\ProcuremenSupplierScore;
  9. use app\common\library\ProcuremenTime;
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use think\Config;
  12. use think\Cache;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use think\Db;
  19. use think\Log;
  20. class Procuremen extends Backend
  21. {
  22. /**
  23. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  24. */
  25. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  26. /**
  27. * Procuremen模型对象
  28. * @var \app\admin\model\Procuremen
  29. */
  30. protected $model = null;
  31. /**
  32. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  33. */
  34. protected $notifyDryRunPreview = [];
  35. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  36. protected $procuremenRedisCache = null;
  37. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  38. protected $pickHiddenScydgySetCache = null;
  39. /** 邮件发送日志表结构已就绪缓存键 */
  40. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  41. /**
  42. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  43. * @var array
  44. */
  45. protected $noNeedRight = [
  46. 'pickreview', 'review', 'reviewcompanies',
  47. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  48. 'auditmanualpick',
  49. // 与 rfqlist 同权,方法内校验
  50. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  51. 'rfqappendsuppliers', 'rfqsupplieroptions',
  52. ];
  53. public function _initialize()
  54. {
  55. parent::_initialize();
  56. $this->model = new \app\admin\model\Procuremen;
  57. $this->maybeMigrateLegacyWflowStatusText();
  58. $this->assignProcuremenAuthConfig();
  59. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  60. $this->ensurePurchaseEmailSendLogTableOnce();
  61. }
  62. }
  63. /**
  64. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  65. */
  66. protected function maybeMigrateLegacyWflowStatusText(): void
  67. {
  68. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  69. if (is_file($flagFile)) {
  70. return;
  71. }
  72. $map = [
  73. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  74. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  75. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  76. '3' => ProcuremenStatus::WFLOW_APPROVED,
  77. ];
  78. try {
  79. foreach ($map as $num => $text) {
  80. Db::table('purchase_order')
  81. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  82. ->update(['wflow_status' => $text]);
  83. }
  84. @file_put_contents($flagFile, date('c'));
  85. } catch (\Throwable $e) {
  86. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  87. }
  88. }
  89. /**
  90. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  91. *
  92. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  93. */
  94. protected function hasProcuremenPerm(array $actions): bool
  95. {
  96. foreach ($actions as $action) {
  97. $action = strtolower(trim((string)$action));
  98. if ($action === '') {
  99. continue;
  100. }
  101. if (strpos($action, 'procuremen/') !== 0) {
  102. $action = 'procuremen/' . $action;
  103. }
  104. if ($this->auth->check($action)) {
  105. return true;
  106. }
  107. }
  108. $suffixes = [];
  109. foreach ($actions as $action) {
  110. $action = strtolower(trim((string)$action));
  111. $action = preg_replace('#^procuremen/#', '', $action);
  112. if ($action !== '') {
  113. $suffixes[$action] = true;
  114. }
  115. }
  116. if ($suffixes === []) {
  117. return false;
  118. }
  119. try {
  120. foreach ($this->auth->getRuleList() as $rule) {
  121. $rule = strtolower((string)$rule);
  122. if (strpos($rule, 'procuremen/') !== 0) {
  123. continue;
  124. }
  125. foreach (array_keys($suffixes) as $suffix) {
  126. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  127. return true;
  128. }
  129. }
  130. }
  131. } catch (\Throwable $e) {
  132. }
  133. return false;
  134. }
  135. /**
  136. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  137. *
  138. * @param string[] $actions
  139. */
  140. protected function hasProcuremenPermStrict(array $actions): bool
  141. {
  142. foreach ($actions as $action) {
  143. $action = strtolower(trim((string)$action));
  144. if ($action === '') {
  145. continue;
  146. }
  147. if (strpos($action, 'procuremen/') !== 0) {
  148. $action = 'procuremen/' . $action;
  149. }
  150. if ($this->auth->check($action)) {
  151. return true;
  152. }
  153. }
  154. return false;
  155. }
  156. /**
  157. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  158. *
  159. * @param string[] $titles
  160. */
  161. protected function authHasAssignedRuleTitle(array $titles): bool
  162. {
  163. $titles = array_values(array_filter(array_map('trim', $titles)));
  164. if ($titles === []) {
  165. return false;
  166. }
  167. try {
  168. $ids = $this->auth->getRuleIds();
  169. if (in_array('*', $ids, true)) {
  170. return true;
  171. }
  172. if ($ids === []) {
  173. return false;
  174. }
  175. $rows = Db::name('auth_rule')
  176. ->where('status', 'normal')
  177. ->whereIn('id', $ids)
  178. ->column('title');
  179. foreach ($rows as $title) {
  180. $t = trim((string)$title);
  181. if ($t !== '' && in_array($t, $titles, true)) {
  182. return true;
  183. }
  184. }
  185. } catch (\Throwable $e) {
  186. }
  187. return false;
  188. }
  189. protected function procuremenCanPickDelete(): bool
  190. {
  191. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  192. return true;
  193. }
  194. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  195. }
  196. protected function procuremenCanComplete(): bool
  197. {
  198. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  199. return true;
  200. }
  201. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  202. }
  203. protected function procuremenCanDispatch(): bool
  204. {
  205. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  206. }
  207. /**
  208. * 前端按钮显隐(Config.procuremenAuth)
  209. */
  210. protected function assignProcuremenAuthConfig(): void
  211. {
  212. $authMap = [
  213. 'pickreview' => $this->procuremenCanDispatch(),
  214. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  215. 'pickdelete' => $this->procuremenCanPickDelete(),
  216. 'completedirectly' => $this->procuremenCanComplete(),
  217. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  218. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  219. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  220. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  221. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  222. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  223. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  224. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  225. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  226. 'details' => $this->hasProcuremenPerm(['details']),
  227. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  228. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  229. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  230. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  231. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  232. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  233. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  234. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  235. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  236. 'add' => $this->hasProcuremenPerm(['add']),
  237. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  238. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen']),
  239. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman']),
  240. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers']),
  241. 'rfqissue' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue']),
  242. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail']),
  243. 'rfqquotes' => $this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue']),
  244. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers']),
  245. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  246. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  247. ];
  248. $this->assignconfig('procuremenAuth', $authMap);
  249. }
  250. /**
  251. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  252. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  253. *
  254. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  255. */
  256. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  257. {
  258. static $mprocCfgLoaded = false;
  259. if (!$mprocCfgLoaded) {
  260. $mprocCfgLoaded = true;
  261. if (is_file(APP_PATH . 'extra/mproc.php')) {
  262. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  263. }
  264. }
  265. $eid = (int)$purchaseOrderDetailId;
  266. $base = $this->resolveMprocMobilePublicBaseUrl();
  267. if ($base === '') {
  268. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  269. }
  270. $path = trim((string)Config::get('mproc.mobile_index_path'));
  271. if ($path === '') {
  272. $path = '/index.php/index/index/index';
  273. } else {
  274. $path = '/' . ltrim($path, '/');
  275. }
  276. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  277. if ($eid > 0) {
  278. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  279. }
  280. return $base . $path . '?main_tab=orders';
  281. }
  282. /**
  283. * 邮件/短信外链:须为带点的公网域名
  284. */
  285. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  286. {
  287. $u = trim((string)$baseUrl);
  288. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  289. return false;
  290. }
  291. $host = parse_url($u, PHP_URL_HOST);
  292. if (!is_string($host) || $host === '') {
  293. return false;
  294. }
  295. if (strcasecmp($host, 'localhost') === 0) {
  296. return false;
  297. }
  298. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  299. return false;
  300. }
  301. if (strpos($host, '.') === false) {
  302. return false;
  303. }
  304. return true;
  305. }
  306. /**
  307. * 解析用于协助邮件/短信的手机端站点根
  308. */
  309. protected function resolveMprocMobilePublicBaseUrl()
  310. {
  311. $candidates = [];
  312. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  313. $candidates[] = trim((string)Config::get('site.indexurl'));
  314. $cdn = trim((string)Config::get('site.cdnurl'));
  315. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  316. $candidates[] = rtrim($cdn, '/');
  317. }
  318. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  319. $candidates[] = $reqBase;
  320. foreach ($candidates as $c) {
  321. if ($c === '') {
  322. continue;
  323. }
  324. $c = rtrim($c, '/');
  325. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  326. return $c;
  327. }
  328. }
  329. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  330. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  331. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  332. return $reqBase;
  333. }
  334. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  335. return '';
  336. }
  337. /**
  338. * 获取 Redis 中 procuremen_redis
  339. */
  340. protected function ProcuremenRedis(): array
  341. {
  342. if ($this->procuremenRedisCache !== null) {
  343. return $this->procuremenRedisCache;
  344. }
  345. try {
  346. $redis = redis();
  347. $raw = $redis->get('procuremen_redis');
  348. if ($raw === false || $raw === '') {
  349. $this->procuremenRedisCache = [];
  350. return $this->procuremenRedisCache;
  351. }
  352. $decoded = json_decode($raw, true);
  353. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  354. $this->procuremenRedisCache = [];
  355. return $this->procuremenRedisCache;
  356. }
  357. $this->procuremenRedisCache = $decoded['data'];
  358. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  359. if ($this->loadProcuremenSidebarYmList() === []) {
  360. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  361. }
  362. return $this->procuremenRedisCache;
  363. } catch (\Throwable $e) {
  364. $this->procuremenRedisCache = [];
  365. return $this->procuremenRedisCache;
  366. }
  367. }
  368. /**
  369. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  370. *
  371. * @return array<int, array<string, mixed>>
  372. */
  373. protected function procuremenFetchErpPoolFromDb(): array
  374. {
  375. try {
  376. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  377. $endTime = date('Y-m-d 23:59:59');
  378. $list = Db::table('scydgy')
  379. ->alias('a')
  380. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  381. ->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, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  382. ->where([
  383. 'a.bwjg' => 1,
  384. 'a.iEndBz' => 0,
  385. 'a.iType' => 0,
  386. 'a.iStatus' => 10,
  387. ])
  388. ->where('a.dStamp', '>=', $startTime)
  389. ->where('a.dStamp', '<=', $endTime)
  390. ->order('a.dStamp', 'desc')
  391. ->select();
  392. if (!is_array($list)) {
  393. return [];
  394. }
  395. try {
  396. $redis = redis();
  397. $payload = [
  398. 'code' => 200,
  399. 'msg' => 'success',
  400. 'data' => $list,
  401. ];
  402. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  403. $this->procuremenRedisCache = $list;
  404. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  405. $this->clearPickMonthPoolCaches();
  406. $this->warmPickMonthPoolCachesFromPool($list);
  407. } catch (\Throwable $e) {
  408. }
  409. return $list;
  410. } catch (\Throwable $e) {
  411. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  412. return [];
  413. }
  414. }
  415. /**
  416. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  417. *
  418. * @return array<int, array<string, mixed>>
  419. */
  420. protected function procuremenEnsureRedisPool(): array
  421. {
  422. $pool = $this->ProcuremenRedis();
  423. if (is_array($pool) && $pool !== []) {
  424. return $pool;
  425. }
  426. static $warmed = false;
  427. if ($warmed) {
  428. return is_array($pool) ? $pool : [];
  429. }
  430. $warmed = true;
  431. return $this->procuremenFetchErpPoolFromDb();
  432. }
  433. /**
  434. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  435. *
  436. * @param array<string, mixed> $row
  437. */
  438. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  439. {
  440. $t = $this->procuremenRowListSortTime($row, $primary);
  441. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  442. return null;
  443. }
  444. $mo = (int)$m[2];
  445. if ($mo < 1 || $mo > 12) {
  446. return null;
  447. }
  448. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  449. }
  450. /**
  451. * @param array<int, array{year:string, months:array}> $sidebar
  452. * @return array<int, array{year:string, months:array}>
  453. */
  454. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  455. {
  456. $ym = trim($ym);
  457. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  458. return $sidebar;
  459. }
  460. foreach ($sidebar as $block) {
  461. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  462. continue;
  463. }
  464. foreach ($block['months'] as $item) {
  465. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  466. return $sidebar;
  467. }
  468. }
  469. }
  470. $y = substr($ym, 0, 4);
  471. $mo = (int)substr($ym, 5, 2);
  472. $sidebar[] = [
  473. 'year' => $y,
  474. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  475. ];
  476. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  477. }
  478. /**
  479. * @param array<int, array{year:string, months:array}> $sidebar
  480. * @return string[]
  481. */
  482. protected function flattenProcuremenSidebarYms(array $sidebar): array
  483. {
  484. $yms = [];
  485. foreach ($sidebar as $block) {
  486. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  487. continue;
  488. }
  489. foreach ($block['months'] as $item) {
  490. if (!is_array($item)) {
  491. continue;
  492. }
  493. $ym = trim((string)($item['ym'] ?? ''));
  494. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  495. $yms[$ym] = true;
  496. }
  497. }
  498. }
  499. return array_keys($yms);
  500. }
  501. /**
  502. * 左侧菜单(协助初选)
  503. * 禁止扫整包/重 SQL。有月份小键则用;否则只展示当月,等列表第一次暖缓存后再补全。
  504. */
  505. protected function GetIndexYearMonths()
  506. {
  507. $ymList = $this->loadProcuremenSidebarYmList();
  508. if ($ymList === []) {
  509. $def = $this->resolveProcuremenDefaultYm('pick');
  510. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  511. }
  512. $def = $this->resolveProcuremenDefaultYm('pick');
  513. if (preg_match('/^\d{4}-\d{2}$/', $def) && !in_array($def, $ymList, true)) {
  514. $ymList[] = $def;
  515. }
  516. return $this->buildYearMonthSidebar($ymList);
  517. }
  518. /**
  519. * @return string[] 形如 2026-07
  520. */
  521. protected function loadProcuremenSidebarYmList(): array
  522. {
  523. try {
  524. $raw = redis()->get('procuremen_redis_yms');
  525. if ($raw === false || $raw === null || $raw === '') {
  526. return [];
  527. }
  528. $decoded = json_decode((string)$raw, true);
  529. if (!is_array($decoded)) {
  530. return [];
  531. }
  532. $out = [];
  533. foreach ($decoded as $ym) {
  534. $ym = trim((string)$ym);
  535. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  536. $out[$ym] = true;
  537. }
  538. }
  539. return array_keys($out);
  540. } catch (\Throwable $e) {
  541. return [];
  542. }
  543. }
  544. /**
  545. * @param string[] $ymList
  546. */
  547. protected function saveProcuremenSidebarYmList(array $ymList): void
  548. {
  549. $out = [];
  550. foreach ($ymList as $ym) {
  551. $ym = trim((string)$ym);
  552. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  553. $out[$ym] = true;
  554. }
  555. }
  556. if ($out === []) {
  557. return;
  558. }
  559. try {
  560. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  561. } catch (\Throwable $e) {
  562. }
  563. }
  564. /**
  565. * @param array<int, array<string, mixed>> $pool
  566. * @return string[]
  567. */
  568. protected function extractYearMonthsFromPoolRows(array $pool): array
  569. {
  570. $ymSet = [];
  571. foreach ($pool as $r) {
  572. if (!is_array($r)) {
  573. continue;
  574. }
  575. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  576. continue;
  577. }
  578. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  579. if ($ym !== null) {
  580. $ymSet[$ym] = true;
  581. }
  582. }
  583. return array_keys($ymSet);
  584. }
  585. /**
  586. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  587. *
  588. * @return string[]
  589. */
  590. protected function queryProcuremenPickSidebarYmListLight(): array
  591. {
  592. try {
  593. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  594. $endTime = date('Y-m-d 23:59:59');
  595. $sql = 'SELECT DISTINCT DATE_FORMAT('
  596. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  597. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  598. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  599. . ' FROM scydgy a'
  600. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  601. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  602. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  603. $rows = Db::query($sql, [$startTime, $endTime]);
  604. if (!is_array($rows)) {
  605. return [];
  606. }
  607. $out = [];
  608. foreach ($rows as $r) {
  609. $ym = trim((string)($r['ym'] ?? ''));
  610. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  611. $out[$ym] = true;
  612. }
  613. }
  614. return array_keys($out);
  615. } catch (\Throwable $e) {
  616. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  617. return [];
  618. }
  619. }
  620. /**
  621. * @return string[] 含当月在内的近 N 个自然月
  622. */
  623. protected function buildRecentCalendarYmList(int $months = 12): array
  624. {
  625. $months = max(1, min(24, $months));
  626. $out = [];
  627. $base = strtotime(date('Y-m-01'));
  628. for ($i = 0; $i < $months; $i++) {
  629. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  630. }
  631. return $out;
  632. }
  633. /**
  634. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  635. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  636. *
  637. * @return array<int, array<string, mixed>>
  638. */
  639. protected function loadPickPoolForYm(string $ym): array
  640. {
  641. $ym = trim($ym);
  642. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  643. return [];
  644. }
  645. $hit = $this->readPickMonthPoolCache($ym);
  646. if ($hit !== null) {
  647. return $hit;
  648. }
  649. return $this->queryPickPoolForYmFromDb($ym);
  650. }
  651. /**
  652. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  653. */
  654. protected function readPickMonthPoolCache(string $ym): ?array
  655. {
  656. try {
  657. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  658. if ($raw === false || $raw === null || $raw === '') {
  659. return null;
  660. }
  661. $decoded = json_decode((string)$raw, true);
  662. if (!is_array($decoded)) {
  663. return null;
  664. }
  665. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  666. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  667. return $decoded['rows'];
  668. }
  669. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  670. if ($decoded === []) {
  671. try {
  672. redis()->del('procuremen_pick_pool:' . $ym);
  673. } catch (\Throwable $e) {
  674. }
  675. return null;
  676. }
  677. if (isset($decoded[0]) && is_array($decoded[0])) {
  678. return $decoded;
  679. }
  680. return null;
  681. } catch (\Throwable $e) {
  682. return null;
  683. }
  684. }
  685. /**
  686. * @param array<int, array<string, mixed>> $rows
  687. */
  688. protected function writePickMonthPoolCache(string $ym, array $rows): void
  689. {
  690. try {
  691. redis()->setex(
  692. 'procuremen_pick_pool:' . $ym,
  693. 600,
  694. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  695. );
  696. } catch (\Throwable $e) {
  697. }
  698. }
  699. /**
  700. * @param array<int, array<string, mixed>> $pool
  701. * @return array<int, array<string, mixed>>
  702. */
  703. protected function filterPoolRowsByYm(array $pool, string $ym): array
  704. {
  705. $out = [];
  706. foreach ($pool as $r) {
  707. if (!is_array($r)) {
  708. continue;
  709. }
  710. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  711. continue;
  712. }
  713. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  714. $out[] = $r;
  715. }
  716. }
  717. return $out;
  718. }
  719. /**
  720. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  721. *
  722. * @return array<int, array<string, mixed>>
  723. */
  724. protected function queryPickPoolForYmFromDb(string $ym): array
  725. {
  726. $monthStart = $ym . '-01 00:00:00';
  727. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  728. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  729. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  730. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  731. try {
  732. $list = Db::table('scydgy')
  733. ->alias('a')
  734. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  735. ->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, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  736. ->where([
  737. 'a.bwjg' => 1,
  738. 'a.iEndBz' => 0,
  739. 'a.iType' => 0,
  740. 'a.iStatus' => 10,
  741. ])
  742. ->where('a.dStamp', '>=', $queryStart)
  743. ->where('a.dStamp', '<=', $queryEnd)
  744. ->order('a.dStamp', 'desc')
  745. ->select();
  746. } catch (\Throwable $e) {
  747. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  748. return [];
  749. }
  750. if (!is_array($list)) {
  751. $list = [];
  752. }
  753. $out = $this->filterPoolRowsByYm($list, $ym);
  754. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  755. $this->writePickMonthPoolCache($ym, $out);
  756. try {
  757. $yms = $this->loadProcuremenSidebarYmList();
  758. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  759. $yms[] = $ym;
  760. $this->saveProcuremenSidebarYmList($yms);
  761. }
  762. } catch (\Throwable $e) {
  763. }
  764. return $out;
  765. }
  766. /**
  767. * 整包写入后拆成按月小缓存,供初选列表秒开
  768. *
  769. * @param array<int, array<string, mixed>> $pool
  770. */
  771. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  772. {
  773. if ($pool === []) {
  774. return;
  775. }
  776. $byYm = [];
  777. foreach ($pool as $r) {
  778. if (!is_array($r)) {
  779. continue;
  780. }
  781. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  782. continue;
  783. }
  784. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  785. if ($rowYm === null) {
  786. continue;
  787. }
  788. $byYm[$rowYm][] = $r;
  789. }
  790. if ($byYm === []) {
  791. return;
  792. }
  793. try {
  794. $redis = redis();
  795. foreach ($byYm as $rowYm => $rows) {
  796. $redis->setex(
  797. 'procuremen_pick_pool:' . $rowYm,
  798. 600,
  799. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  800. );
  801. }
  802. try {
  803. $redis->del('procuremen_pick_hidden_scydgy_v1');
  804. } catch (\Throwable $e) {
  805. }
  806. } catch (\Throwable $e) {
  807. }
  808. }
  809. /**
  810. * 刷新整包后清理近月缓存,避免脏读
  811. */
  812. protected function clearPickMonthPoolCaches(int $months = 24): void
  813. {
  814. try {
  815. $redis = redis();
  816. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  817. try {
  818. $redis->del('procuremen_pick_pool:' . $ym);
  819. } catch (\Throwable $e) {
  820. }
  821. }
  822. } catch (\Throwable $e) {
  823. }
  824. $this->invalidatePickHiddenScydgyCache();
  825. }
  826. /**
  827. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  828. */
  829. protected function invalidatePickHiddenScydgyCache(): void
  830. {
  831. $this->pickHiddenScydgySetCache = null;
  832. try {
  833. redis()->del('procuremen_pick_hidden_scydgy_v1');
  834. } catch (\Throwable $e) {
  835. }
  836. }
  837. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  838. protected function procuremenReleaseSessionLock(): void
  839. {
  840. if (session_status() === PHP_SESSION_ACTIVE) {
  841. @session_write_close();
  842. }
  843. }
  844. /**
  845. * @param string[] $ymList 形如 2026-06
  846. * @return array<int, array{year:string, months:array}>
  847. */
  848. protected function buildYearMonthSidebar(array $ymList): array
  849. {
  850. rsort($ymList, SORT_STRING);
  851. $byYear = [];
  852. foreach ($ymList as $ym) {
  853. $y = substr($ym, 0, 4);
  854. $mo = (int)substr($ym, 5, 2);
  855. if (!isset($byYear[$y])) {
  856. $byYear[$y] = [];
  857. }
  858. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  859. }
  860. krsort($byYear, SORT_NUMERIC);
  861. foreach ($byYear as $y => $items) {
  862. usort($byYear[$y], function ($a, $b) {
  863. return strcmp($b['ym'], $a['ym']);
  864. });
  865. }
  866. $sidebar = [];
  867. foreach ($byYear as $y => $months) {
  868. $sidebar[] = ['year' => $y, 'months' => $months];
  869. }
  870. return $sidebar;
  871. }
  872. /**
  873. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  874. */
  875. protected function GetIssuedOrderYearMonths(string $stage): array
  876. {
  877. $ymSet = [];
  878. try {
  879. $query = Db::table('purchase_order');
  880. $this->applyPurchaseOrderNotDeletedWhere($query);
  881. if ($stage === 'audit') {
  882. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  883. } elseif ($stage === 'confirm') {
  884. $this->applyPurchaseOrderConfirmStageWhere($query);
  885. } else {
  886. return $this->GetIndexYearMonths();
  887. }
  888. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  889. if (is_array($rows)) {
  890. foreach ($rows as $r) {
  891. if (!is_array($r)) {
  892. continue;
  893. }
  894. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  895. if ($ym !== null) {
  896. $ymSet[$ym] = true;
  897. }
  898. }
  899. }
  900. } catch (\Throwable $e) {
  901. $ymSet = [];
  902. }
  903. $ymList = array_keys($ymSet);
  904. if ($ymList === []) {
  905. $def = $this->resolveProcuremenDefaultYm($stage);
  906. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  907. }
  908. return $this->buildYearMonthSidebar($ymList);
  909. }
  910. /**
  911. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  912. */
  913. protected function resolveProcuremenDefaultYm(string $stage): string
  914. {
  915. if ($stage === 'pick') {
  916. return date('Y-m');
  917. }
  918. try {
  919. $query = Db::table('purchase_order');
  920. $this->applyPurchaseOrderNotDeletedWhere($query);
  921. if ($stage === 'audit') {
  922. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  923. } elseif ($stage === 'confirm') {
  924. $this->applyPurchaseOrderConfirmStageWhere($query);
  925. } else {
  926. return date('Y-m');
  927. }
  928. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  929. if ($latest === null || $latest === '') {
  930. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  931. }
  932. $t = $this->formatProcuremenDetailTime($latest);
  933. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  934. return $m[1] . '-' . $m[2];
  935. }
  936. } catch (\Throwable $e) {
  937. }
  938. return date('Y-m');
  939. }
  940. protected function applyPurchaseOrderNotDeletedWhere($query): void
  941. {
  942. $query->whereRaw(
  943. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  944. );
  945. }
  946. /**
  947. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  948. */
  949. protected function applyPurchaseOrderConfirmStageWhere($query): void
  950. {
  951. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  952. $quoted = [];
  953. foreach ($vals as $v) {
  954. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  955. }
  956. if ($quoted === []) {
  957. $query->whereRaw('1 = 0');
  958. return;
  959. }
  960. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  961. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  962. }
  963. /**
  964. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  965. *
  966. * @param array<string, mixed> $row
  967. * @return array<string, mixed>
  968. */
  969. protected function normalizePurchaseOrderListTimeRow(array $row): array
  970. {
  971. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  972. $pick = trim((string)($row['pick_time'] ?? ''));
  973. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  974. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  975. $t = trim((string)($row[$key] ?? ''));
  976. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  977. $row['pick_time'] = $t;
  978. break;
  979. }
  980. }
  981. }
  982. return $row;
  983. }
  984. /**
  985. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  986. */
  987. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  988. {
  989. if (!in_array($stage, ['audit', 'confirm'], true)) {
  990. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  991. }
  992. if ($pool === []) {
  993. $def = $this->resolveProcuremenDefaultYm($stage);
  994. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  995. }
  996. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  997. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  998. return false;
  999. }
  1000. $monthStart = $ym . '-01 00:00:00';
  1001. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1002. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1003. return $probe !== [];
  1004. };
  1005. if ($tryYm($requestedYm)) {
  1006. return $requestedYm;
  1007. }
  1008. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1009. if ($tryYm($fallback)) {
  1010. return $fallback;
  1011. }
  1012. $bestYm = '';
  1013. $bestTime = '';
  1014. foreach ($pool as $row) {
  1015. if (!is_array($row)) {
  1016. continue;
  1017. }
  1018. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1019. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1020. continue;
  1021. }
  1022. $ymRow = $m[1];
  1023. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1024. $bestTime = $t;
  1025. $bestYm = $ymRow;
  1026. }
  1027. }
  1028. if ($bestYm !== '') {
  1029. return $bestYm;
  1030. }
  1031. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1032. }
  1033. protected function isPurchaseOrderDetailVoid(array $row): bool
  1034. {
  1035. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1036. return true;
  1037. }
  1038. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1039. }
  1040. /**
  1041. * 仅当前有效下发明细(排除废弃归档)
  1042. */
  1043. protected function applyActivePurchaseOrderDetailWhere($query): void
  1044. {
  1045. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1046. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1047. }
  1048. /**
  1049. * @param array<string, mixed> $detailRow
  1050. */
  1051. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1052. {
  1053. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1054. return false;
  1055. }
  1056. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1057. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1058. }
  1059. /**
  1060. * 废弃退回初选:下发明细标记归档,不物理删除
  1061. *
  1062. * @param array<int, int|string> $scydgyIds
  1063. */
  1064. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1065. {
  1066. $ids = [];
  1067. foreach ($scydgyIds as $sid) {
  1068. $n = (int)$sid;
  1069. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1070. $ids[$n] = true;
  1071. }
  1072. }
  1073. if ($ids === []) {
  1074. return;
  1075. }
  1076. $void = ProcuremenStatus::POD_VOID;
  1077. Db::table('purchase_order_detail')
  1078. ->where('scydgy_id', 'in', array_keys($ids))
  1079. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1080. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1081. ->update([
  1082. 'status' => $void,
  1083. 'status_name' => $void,
  1084. ]);
  1085. }
  1086. /**
  1087. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1088. */
  1089. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1090. {
  1091. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1092. $norm = function (string $col) use ($p): string {
  1093. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1094. };
  1095. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1096. $parts = [];
  1097. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1098. if ($key === 'createtime') {
  1099. $parts[] = $createtime;
  1100. } else {
  1101. $parts[] = $norm($key);
  1102. }
  1103. }
  1104. return 'COALESCE(' . implode(', ', $parts) . ')';
  1105. }
  1106. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1107. {
  1108. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1109. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1110. }
  1111. /**
  1112. * @return array<int, array<string, mixed>>
  1113. */
  1114. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1115. {
  1116. $this->ensurePurchaseOrderCzlyqColumn();
  1117. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1118. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1119. try {
  1120. $query = Db::table('purchase_order')->field($fields);
  1121. $this->applyPurchaseOrderNotDeletedWhere($query);
  1122. if ($stage === 'audit') {
  1123. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1124. } elseif ($stage === 'confirm') {
  1125. $this->applyPurchaseOrderConfirmStageWhere($query);
  1126. } else {
  1127. return [];
  1128. }
  1129. $query->order('pick_time', 'desc')->order('id', 'desc');
  1130. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1131. $monthStart = $ym . '-01 00:00:00';
  1132. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1133. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1134. }
  1135. $rows = $query->select();
  1136. } catch (\Throwable $e) {
  1137. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1138. $rows = [];
  1139. }
  1140. return is_array($rows) ? $rows : [];
  1141. }
  1142. /**
  1143. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1144. */
  1145. protected function resolveProcuremenListStage(): string
  1146. {
  1147. $tab = trim((string)$this->request->request('wff_tab', ''));
  1148. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1149. return $tab;
  1150. }
  1151. $action = strtolower((string)$this->request->action());
  1152. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1153. return $action;
  1154. }
  1155. return 'pick';
  1156. }
  1157. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1158. {
  1159. $this->procuremenReleaseSessionLock();
  1160. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1161. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1162. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1163. $indexPhpRoot = $rootTrue . '/index.php';
  1164. }
  1165. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1166. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1167. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1168. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1169. $this->view->assign('defaultYm', $defaultYm);
  1170. $this->view->assign('sidebarYearMonths', $sidebar);
  1171. $this->view->assign('procuremenStage', $stage);
  1172. $this->view->assign('procuremenPageTitle', $pageTitle);
  1173. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1174. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1175. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1176. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1177. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1178. }
  1179. /**
  1180. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1181. *
  1182. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1183. */
  1184. protected function buildProcuremenFilterOptions(string $stage): array
  1185. {
  1186. $buckets = [
  1187. 'czlyq' => [],
  1188. 'CCLBMMC' => [],
  1189. 'cywyxm' => [],
  1190. 'CGYMC' => [],
  1191. ];
  1192. $maxPerField = 300;
  1193. try {
  1194. if ($stage === 'pick') {
  1195. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1196. return $buckets;
  1197. }
  1198. if (in_array($stage, ['audit', 'confirm'], true)) {
  1199. $this->ensurePurchaseOrderCzlyqColumn();
  1200. foreach (array_keys($buckets) as $field) {
  1201. try {
  1202. $query = Db::table('purchase_order')->field($field);
  1203. $this->applyPurchaseOrderNotDeletedWhere($query);
  1204. if ($stage === 'audit') {
  1205. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1206. } else {
  1207. $this->applyPurchaseOrderConfirmStageWhere($query);
  1208. }
  1209. $query->where($field, '<>', '')->whereNotNull($field);
  1210. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1211. if (!is_array($vals)) {
  1212. continue;
  1213. }
  1214. foreach ($vals as $v) {
  1215. $v = trim((string)$v);
  1216. if ($v !== '') {
  1217. $buckets[$field][$v] = $v;
  1218. }
  1219. }
  1220. } catch (\Throwable $e) {
  1221. // 单字段失败不影响其它
  1222. }
  1223. }
  1224. }
  1225. } catch (\Throwable $e) {
  1226. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1227. }
  1228. foreach ($buckets as &$set) {
  1229. if ($set !== []) {
  1230. ksort($set, SORT_STRING);
  1231. }
  1232. }
  1233. unset($set);
  1234. return $buckets;
  1235. }
  1236. /**
  1237. * filter JSON 是否含有效条件
  1238. *
  1239. * @param array<string, mixed> $filterArr
  1240. */
  1241. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1242. {
  1243. foreach ($filterArr as $v) {
  1244. if (is_array($v)) {
  1245. if (array_filter($v, function ($x) {
  1246. return $x !== '' && $x !== null;
  1247. })) {
  1248. return true;
  1249. }
  1250. } elseif ($v !== '' && $v !== null) {
  1251. return true;
  1252. }
  1253. }
  1254. return false;
  1255. }
  1256. /**
  1257. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1258. *
  1259. * @param array<string, mixed> $filterArr
  1260. * @param array<string, mixed> $opArr
  1261. */
  1262. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1263. {
  1264. if ($search !== '') {
  1265. return false;
  1266. }
  1267. foreach ($filterArr as $fk => $fv) {
  1268. if (is_array($fv)) {
  1269. continue;
  1270. }
  1271. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1272. continue;
  1273. }
  1274. if ($fv === null) {
  1275. continue;
  1276. }
  1277. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1278. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1279. if ($sym === '' || $sym === '=') {
  1280. continue;
  1281. }
  1282. return false;
  1283. }
  1284. return true;
  1285. }
  1286. /**
  1287. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1288. *
  1289. * @param array<int, mixed> $rows
  1290. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1291. */
  1292. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1293. {
  1294. $buckets = [
  1295. 'czlyq' => [],
  1296. 'CCLBMMC' => [],
  1297. 'cywyxm' => [],
  1298. 'CGYMC' => [],
  1299. ];
  1300. foreach ($rows as $r) {
  1301. if (!is_array($r)) {
  1302. continue;
  1303. }
  1304. foreach ($buckets as $field => &$set) {
  1305. if (count($set) >= $maxPerField) {
  1306. continue;
  1307. }
  1308. $v = trim((string)($r[$field] ?? ''));
  1309. if ($v !== '') {
  1310. $set[$v] = $v;
  1311. }
  1312. }
  1313. unset($set);
  1314. $full = true;
  1315. foreach ($buckets as $set) {
  1316. if (count($set) < $maxPerField) {
  1317. $full = false;
  1318. break;
  1319. }
  1320. }
  1321. if ($full) {
  1322. break;
  1323. }
  1324. }
  1325. foreach ($buckets as &$set) {
  1326. if ($set !== []) {
  1327. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1328. $normalized = [];
  1329. foreach ($set as $k => $v) {
  1330. $s = trim((string)(is_scalar($v) ? $v : $k));
  1331. if ($s === '') {
  1332. continue;
  1333. }
  1334. $normalized[$s] = $s;
  1335. }
  1336. ksort($normalized, SORT_STRING);
  1337. $set = $normalized;
  1338. }
  1339. }
  1340. unset($set);
  1341. return $buckets;
  1342. }
  1343. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1344. public function pick()
  1345. {
  1346. $this->request->filter(['strip_tags', 'trim']);
  1347. if (!$this->request->isAjax()) {
  1348. $this->assignProcuremenListPage('pick', '协助下发');
  1349. return $this->view->fetch('procuremen/index');
  1350. }
  1351. return $this->index();
  1352. }
  1353. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1354. public function audit()
  1355. {
  1356. $this->request->filter(['strip_tags', 'trim']);
  1357. if (!$this->request->isAjax()) {
  1358. $this->assignProcuremenListPage('audit', '确认供应商');
  1359. return $this->view->fetch('procuremen/index');
  1360. }
  1361. return $this->index();
  1362. }
  1363. /** 采购确认(定标) */
  1364. public function confirm()
  1365. {
  1366. $this->request->filter(['strip_tags', 'trim']);
  1367. if (!$this->request->isAjax()) {
  1368. $this->assignProcuremenListPage('confirm', '采购确认');
  1369. return $this->view->fetch('procuremen/index');
  1370. }
  1371. return $this->index();
  1372. }
  1373. /**
  1374. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1375. */
  1376. public function index()
  1377. {
  1378. $this->request->filter(['strip_tags', 'trim']);
  1379. if (!$this->request->isAjax()) {
  1380. $this->assignProcuremenListPage('pick', '协助下发');
  1381. return $this->view->fetch('procuremen/index');
  1382. }
  1383. if ($this->request->request('keyField')) {
  1384. return $this->selectpage();
  1385. }
  1386. $this->procuremenReleaseSessionLock();
  1387. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1388. $limit = max(10, min(500, (int)$limit));
  1389. $ym = $this->request->request('ym', '');
  1390. $ym = is_string($ym) ? trim($ym) : '';
  1391. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1392. $wffTab = $this->resolveProcuremenListStage();
  1393. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1394. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1395. ? $this->resolveProcuremenDefaultYm($wffTab)
  1396. : date('Y-m');
  1397. }
  1398. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1399. $ym = date('Y-m');
  1400. }
  1401. $monthStart = $ym . '-01 00:00:00';
  1402. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1403. $search = trim((string)$this->request->get('search', ''));
  1404. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1405. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1406. if (!is_array($filterArr)) {
  1407. $filterArr = [];
  1408. }
  1409. if (!is_array($opArr)) {
  1410. $opArr = [];
  1411. }
  1412. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1413. $bidOpenStatusFilter = '';
  1414. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1415. if (!array_key_exists($bidFk, $filterArr)) {
  1416. continue;
  1417. }
  1418. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1419. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1420. }
  1421. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1422. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1423. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1424. try {
  1425. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1426. if ($wffTab === 'audit') {
  1427. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1428. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1429. );
  1430. } elseif ($wffTab === 'confirm') {
  1431. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1432. if ($dbRows === []) {
  1433. try {
  1434. $dbRows = Db::table('purchase_order')
  1435. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1436. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1437. ->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%\')')
  1438. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1439. ->order('pick_time', 'desc')->order('id', 'desc')
  1440. ->select();
  1441. } catch (\Throwable $e) {
  1442. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1443. $dbRows = [];
  1444. }
  1445. }
  1446. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1447. if ($pool === []) {
  1448. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1449. }
  1450. } else {
  1451. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1452. if ($applyMonthRange) {
  1453. $pool = $this->loadPickPoolForYm($ym);
  1454. } else {
  1455. $pool = $this->procuremenEnsureRedisPool();
  1456. }
  1457. if (!is_array($pool)) {
  1458. $pool = [];
  1459. }
  1460. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1461. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1462. if ($pool !== [] && $hideSet !== []) {
  1463. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1464. if (!is_array($r)) {
  1465. return false;
  1466. }
  1467. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1468. return $id <= 0 || !isset($hideSet[$id]);
  1469. }));
  1470. }
  1471. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1472. if ($pool === []) {
  1473. return json([
  1474. 'total' => 0,
  1475. 'rows' => [],
  1476. 'activeYm' => $ym,
  1477. 'filterOptions' => (
  1478. (int)$offset === 0
  1479. && !$hasActiveSearch
  1480. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1481. )
  1482. ? $this->extractProcuremenFilterOptionsFromRows([])
  1483. : new \stdClass(),
  1484. ]);
  1485. }
  1486. }
  1487. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1488. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1489. $monthStart = $ym . '-01 00:00:00';
  1490. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1491. }
  1492. $filtered = $this->filterProcuremenIndexPool(
  1493. $pool,
  1494. $monthStart,
  1495. $monthEnd,
  1496. $applyMonthRange,
  1497. $search,
  1498. $filterArr,
  1499. $opArr,
  1500. $listTimePrimary
  1501. );
  1502. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1503. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1504. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1505. }
  1506. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1507. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1508. }
  1509. $sortField = 'ID';
  1510. if (is_string($sort) && $sort !== '') {
  1511. $parts = explode(',', $sort);
  1512. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1513. if ($sortField === '') {
  1514. $sortField = 'ID';
  1515. }
  1516. }
  1517. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1518. $nFiltered = count($filtered);
  1519. if ($nFiltered > 1) {
  1520. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1521. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1522. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1523. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1524. if ($ta === $tb) {
  1525. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1526. }
  1527. if ($ta === '') {
  1528. return 1;
  1529. }
  1530. if ($tb === '') {
  1531. return -1;
  1532. }
  1533. return strcmp($ta, $tb) * $ord;
  1534. });
  1535. } elseif ($sortField === 'ID') {
  1536. $sortKeys = [];
  1537. foreach ($filtered as $i => $row) {
  1538. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1539. }
  1540. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1541. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1542. } elseif ($sortField === 'CCYDH') {
  1543. usort($filtered, function ($a, $b) use ($ord) {
  1544. $sa = trim((string)($a['CCYDH'] ?? ''));
  1545. $sb = trim((string)($b['CCYDH'] ?? ''));
  1546. if ($sa === $sb) {
  1547. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1548. }
  1549. if ($sa === '') {
  1550. return 1;
  1551. }
  1552. if ($sb === '') {
  1553. return -1;
  1554. }
  1555. return strcmp($sa, $sb) * $ord;
  1556. });
  1557. } else {
  1558. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1559. $va = $a[$sortField] ?? null;
  1560. $vb = $b[$sortField] ?? null;
  1561. $sa = (string)$va;
  1562. $sb = (string)$vb;
  1563. if ($sa === $sb) {
  1564. return 0;
  1565. }
  1566. return strcmp($sa, $sb) * $ord;
  1567. });
  1568. }
  1569. }
  1570. $offset = max(0, (int)$offset);
  1571. $limit = max(1, (int)$limit);
  1572. $rows = array_slice($filtered, $offset, $limit);
  1573. foreach ($rows as &$rw) {
  1574. if (!is_array($rw)) {
  1575. continue;
  1576. }
  1577. $rid = (int)($rw['ID'] ?? 0);
  1578. $rw['_iss_out'] = ($wffTab !== 'pick');
  1579. }
  1580. unset($rw);
  1581. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1582. $idList = [];
  1583. foreach ($rows as $rw) {
  1584. if (!is_array($rw)) {
  1585. continue;
  1586. }
  1587. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1588. foreach ($rw['_order_merge_rows'] as $mr) {
  1589. $mid = (int)($mr['ID'] ?? 0);
  1590. if ($this->isValidScydgyRowId($mid)) {
  1591. $idList[$mid] = true;
  1592. }
  1593. }
  1594. }
  1595. $id = (int)($rw['ID'] ?? 0);
  1596. if ($this->isValidScydgyRowId($id)) {
  1597. $idList[$id] = true;
  1598. }
  1599. }
  1600. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1601. foreach ($rows as &$rw) {
  1602. if (!is_array($rw)) {
  1603. continue;
  1604. }
  1605. $mergeIds = [];
  1606. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1607. foreach ($rw['_order_merge_rows'] as $mr) {
  1608. $mid = (int)($mr['ID'] ?? 0);
  1609. if ($this->isValidScydgyRowId($mid)) {
  1610. $mergeIds[$mid] = true;
  1611. }
  1612. }
  1613. }
  1614. $rid = (int)($rw['ID'] ?? 0);
  1615. if ($this->isValidScydgyRowId($rid)) {
  1616. $mergeIds[$rid] = true;
  1617. }
  1618. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1619. $rw['po_detail_count'] = $s['cnt'];
  1620. $rw['po_amount_fill_cnt'] = $s['amt'];
  1621. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1622. }
  1623. unset($rw);
  1624. }
  1625. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1626. $idList = [];
  1627. foreach ($rows as $rw) {
  1628. if (!is_array($rw)) {
  1629. continue;
  1630. }
  1631. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1632. foreach ($rw['_order_merge_rows'] as $mr) {
  1633. $mid = (int)($mr['ID'] ?? 0);
  1634. if ($this->isValidScydgyRowId($mid)) {
  1635. $idList[$mid] = true;
  1636. }
  1637. }
  1638. }
  1639. $id = (int)($rw['ID'] ?? 0);
  1640. if ($this->isValidScydgyRowId($id)) {
  1641. $idList[$id] = true;
  1642. }
  1643. }
  1644. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1645. $bidOpenSet = [];
  1646. $manualPickSet = [];
  1647. if ($wffTab === 'audit') {
  1648. $ccydhList = [];
  1649. foreach ($rows as $rw0) {
  1650. if (!is_array($rw0)) {
  1651. continue;
  1652. }
  1653. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1654. if ($c0 !== '') {
  1655. $ccydhList[] = $c0;
  1656. }
  1657. }
  1658. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1659. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1660. }
  1661. foreach ($rows as &$rw) {
  1662. if (!is_array($rw)) {
  1663. continue;
  1664. }
  1665. $mergeIds = [];
  1666. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1667. foreach ($rw['_order_merge_rows'] as $mr) {
  1668. $mid = (int)($mr['ID'] ?? 0);
  1669. if ($this->isValidScydgyRowId($mid)) {
  1670. $mergeIds[$mid] = true;
  1671. }
  1672. }
  1673. }
  1674. $rid = (int)($rw['ID'] ?? 0);
  1675. if ($this->isValidScydgyRowId($rid)) {
  1676. $mergeIds[$rid] = true;
  1677. }
  1678. $buckets = [];
  1679. foreach (array_keys($mergeIds) as $mid) {
  1680. if (isset($quoteBucket[$mid])) {
  1681. $buckets[] = $quoteBucket[$mid];
  1682. }
  1683. }
  1684. $supplierText = $buckets !== []
  1685. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1686. : '';
  1687. if ($wffTab === 'confirm') {
  1688. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1689. if ($picked === '') {
  1690. // 兜底:从合并工序行取
  1691. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1692. foreach ($rw['_order_merge_rows'] as $mr) {
  1693. if (!is_array($mr)) {
  1694. continue;
  1695. }
  1696. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1697. if ($pn !== '') {
  1698. $picked = $pn;
  1699. break;
  1700. }
  1701. }
  1702. }
  1703. }
  1704. $rw['picked_supplier_name'] = $picked;
  1705. } else {
  1706. $rw['notify_supplier_text'] = $supplierText;
  1707. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1708. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1709. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1710. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1711. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1712. if ($verified) {
  1713. $rw['bid_open_status_text'] = '已开标';
  1714. } elseif ($manualPicked) {
  1715. $rw['bid_open_status_text'] = '已指定供应商';
  1716. } else {
  1717. $rw['bid_open_status_text'] = '待开标';
  1718. }
  1719. }
  1720. }
  1721. unset($rw);
  1722. }
  1723. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1724. $this->enrichProcuremenListMilestoneTimes($rows);
  1725. $this->syncCollapsedOrderQtyPriceForList($rows);
  1726. }
  1727. if ($wffTab === 'all' && count($rows) > 0) {
  1728. $this->mergePurchaseOrder($rows);
  1729. }
  1730. if ($wffTab === 'pick' && count($rows) > 0) {
  1731. $this->mergePurchaseOrder($rows);
  1732. }
  1733. foreach ($rows as &$rwClean) {
  1734. if (is_array($rwClean)) {
  1735. unset($rwClean['_order_merge_rows']);
  1736. if (array_key_exists('NGZL', $rwClean)) {
  1737. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1738. }
  1739. }
  1740. }
  1741. unset($rwClean);
  1742. return json([
  1743. 'total' => count($filtered),
  1744. 'rows' => $rows,
  1745. 'activeYm' => $ym,
  1746. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1747. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1748. ? $this->loadProcuremenSidebarYmList()
  1749. : [],
  1750. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1751. 'filterOptions' => (
  1752. (int)$offset === 0
  1753. && !$hasActiveSearch
  1754. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1755. )
  1756. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1757. : new \stdClass(),
  1758. ]);
  1759. } catch (\Throwable $e) {
  1760. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1761. return json([
  1762. 'total' => 0,
  1763. 'rows' => [],
  1764. ]);
  1765. }
  1766. }
  1767. /**
  1768. * @param array<int, array<string, mixed>> $pool
  1769. * @return int[]
  1770. */
  1771. protected function extractScydgyIdsFromPool(array $pool): array
  1772. {
  1773. $ids = [];
  1774. foreach ($pool as $r) {
  1775. if (!is_array($r)) {
  1776. continue;
  1777. }
  1778. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1779. if ($id > 0) {
  1780. $ids[$id] = $id;
  1781. }
  1782. }
  1783. return array_values($ids);
  1784. }
  1785. /**
  1786. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1787. *
  1788. * @param int[] $scydgyIds
  1789. * @return array<int, true>
  1790. */
  1791. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1792. {
  1793. $hideSet = [];
  1794. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1795. return $id > 0;
  1796. }));
  1797. if ($scydgyIds === []) {
  1798. return $hideSet;
  1799. }
  1800. // 分批,避免 whereIn 过长
  1801. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1802. try {
  1803. $poIds = Db::table('purchase_order')
  1804. ->where('scydgy_id', 'in', $chunk)
  1805. ->where(function ($q) {
  1806. $q->whereIn('wflow_status', array_merge(
  1807. ProcuremenStatus::wflowPendingConfirmValues(),
  1808. ProcuremenStatus::wflowPendingApprovalValues()
  1809. ))
  1810. ->whereOr(function ($q1) {
  1811. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1812. })
  1813. ->whereOr(function ($q2) {
  1814. $q2->whereNotNull('pick_time')
  1815. ->where('pick_time', '<>', '')
  1816. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1817. })
  1818. ->whereOr(function ($q3) {
  1819. $q3->whereNotNull('mod_rq')
  1820. ->where('mod_rq', '<>', '')
  1821. ->where('mod_rq', 'not like', '0000-00-00%');
  1822. });
  1823. })
  1824. ->column('scydgy_id');
  1825. if (is_array($poIds)) {
  1826. foreach ($poIds as $pid) {
  1827. $k = (int)$pid;
  1828. if ($k !== 0) {
  1829. $hideSet[$k] = true;
  1830. }
  1831. }
  1832. }
  1833. } catch (\Throwable $e) {
  1834. }
  1835. try {
  1836. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1837. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1838. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1839. if (is_array($detIds)) {
  1840. foreach ($detIds as $pid) {
  1841. $k = (int)$pid;
  1842. if ($this->isValidScydgyRowId($k)) {
  1843. $hideSet[$k] = true;
  1844. }
  1845. }
  1846. }
  1847. } catch (\Throwable $e) {
  1848. }
  1849. }
  1850. return $hideSet;
  1851. }
  1852. /**
  1853. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1854. *
  1855. * @return array<int, true>
  1856. */
  1857. protected function loadPickHiddenScydgySet(): array
  1858. {
  1859. if ($this->pickHiddenScydgySetCache !== null) {
  1860. return $this->pickHiddenScydgySetCache;
  1861. }
  1862. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1863. try {
  1864. $raw = redis()->get($cacheKey);
  1865. if ($raw !== false && $raw !== null && $raw !== '') {
  1866. $ids = json_decode((string)$raw, true);
  1867. if (is_array($ids)) {
  1868. $hideSet = [];
  1869. foreach ($ids as $pid) {
  1870. $k = (int)$pid;
  1871. if ($k !== 0) {
  1872. $hideSet[$k] = true;
  1873. }
  1874. }
  1875. $this->pickHiddenScydgySetCache = $hideSet;
  1876. return $hideSet;
  1877. }
  1878. }
  1879. } catch (\Throwable $e) {
  1880. }
  1881. $hideSet = [];
  1882. try {
  1883. $poIds = Db::table('purchase_order')
  1884. ->where(function ($q) {
  1885. $q->whereIn('wflow_status', array_merge(
  1886. ProcuremenStatus::wflowPendingConfirmValues(),
  1887. ProcuremenStatus::wflowPendingApprovalValues()
  1888. ))
  1889. ->whereOr(function ($q1) {
  1890. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1891. })
  1892. ->whereOr(function ($q2) {
  1893. $q2->whereNotNull('pick_time')
  1894. ->where('pick_time', '<>', '')
  1895. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1896. })
  1897. ->whereOr(function ($q3) {
  1898. $q3->whereNotNull('mod_rq')
  1899. ->where('mod_rq', '<>', '')
  1900. ->where('mod_rq', 'not like', '0000-00-00%');
  1901. });
  1902. })
  1903. ->column('scydgy_id');
  1904. if (is_array($poIds)) {
  1905. foreach ($poIds as $pid) {
  1906. $k = (int)$pid;
  1907. if ($k !== 0) {
  1908. $hideSet[$k] = true;
  1909. }
  1910. }
  1911. }
  1912. } catch (\Throwable $e) {
  1913. }
  1914. try {
  1915. $detIdsQuery = Db::table('purchase_order_detail');
  1916. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1917. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1918. if (is_array($detIds)) {
  1919. foreach ($detIds as $pid) {
  1920. $k = (int)$pid;
  1921. if ($this->isValidScydgyRowId($k)) {
  1922. $hideSet[$k] = true;
  1923. }
  1924. }
  1925. }
  1926. } catch (\Throwable $e) {
  1927. }
  1928. $this->pickHiddenScydgySetCache = $hideSet;
  1929. try {
  1930. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1931. } catch (\Throwable $e) {
  1932. }
  1933. return $hideSet;
  1934. }
  1935. /**
  1936. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1937. *
  1938. * @return array<int, array<string, mixed>>
  1939. */
  1940. protected function loadPickManualOrderRows(): array
  1941. {
  1942. try {
  1943. $dbRows = Db::table('purchase_order')
  1944. ->where('scydgy_id', '<', 0)
  1945. ->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%\')')
  1946. ->order('scydgy_id', 'asc')
  1947. ->select();
  1948. } catch (\Throwable $e) {
  1949. try {
  1950. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1951. } catch (\Throwable $e2) {
  1952. return [];
  1953. }
  1954. }
  1955. if (!is_array($dbRows) || $dbRows === []) {
  1956. return [];
  1957. }
  1958. $detailSidSet = [];
  1959. try {
  1960. $negIds = [];
  1961. foreach ($dbRows as $dbRow) {
  1962. if (!is_array($dbRow)) {
  1963. continue;
  1964. }
  1965. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1966. if ($sid < 0) {
  1967. $negIds[$sid] = true;
  1968. }
  1969. }
  1970. if ($negIds !== []) {
  1971. $detQuery = Db::table('purchase_order_detail')
  1972. ->where('scydgy_id', 'in', array_keys($negIds));
  1973. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1974. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1975. if (is_array($detRows)) {
  1976. foreach ($detRows as $did) {
  1977. $detailSidSet[(int)$did] = true;
  1978. }
  1979. }
  1980. }
  1981. } catch (\Throwable $e) {
  1982. }
  1983. $pool = [];
  1984. foreach ($dbRows as $dbRow) {
  1985. if (!is_array($dbRow)) {
  1986. continue;
  1987. }
  1988. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1989. if ($sid >= 0) {
  1990. continue;
  1991. }
  1992. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  1993. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1994. continue;
  1995. }
  1996. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  1997. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  1998. continue;
  1999. }
  2000. if (isset($detailSidSet[$sid])) {
  2001. continue;
  2002. }
  2003. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2004. $r['_is_manual'] = 1;
  2005. $pool[] = $r;
  2006. }
  2007. return $pool;
  2008. }
  2009. /**
  2010. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2011. */
  2012. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2013. {
  2014. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2015. foreach ($keys as $k) {
  2016. $t = trim((string)($row[$k] ?? ''));
  2017. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2018. return $t;
  2019. }
  2020. }
  2021. return '';
  2022. }
  2023. /**
  2024. * 分配手工新增工序行 ID(负数递减)
  2025. */
  2026. protected function allocateManualScydgyId(): int
  2027. {
  2028. try {
  2029. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2030. $min = (int)$min;
  2031. return $min < 0 ? $min - 1 : -1;
  2032. } catch (\Throwable $e) {
  2033. return -1;
  2034. }
  2035. }
  2036. /**
  2037. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2038. */
  2039. protected function allocateManualOrderCcydh(): string
  2040. {
  2041. $prefix = 'YW' . date('Ymd');
  2042. $maxSeq = 0;
  2043. try {
  2044. $rows = Db::table('purchase_order')
  2045. ->where('CCYDH', 'like', $prefix . '%')
  2046. ->column('CCYDH');
  2047. if (is_array($rows)) {
  2048. foreach ($rows as $ccydh) {
  2049. $ccydh = trim((string)$ccydh);
  2050. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2051. $maxSeq = max($maxSeq, (int)$m[1]);
  2052. }
  2053. }
  2054. }
  2055. } catch (\Throwable $e) {
  2056. }
  2057. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2058. }
  2059. /**
  2060. * purchase_order.mod_rq 是否有有效软删除时间
  2061. */
  2062. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2063. {
  2064. $t = trim((string)$modRq);
  2065. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2066. }
  2067. /**
  2068. * 列表行 → purchase_order 写入字段
  2069. *
  2070. * @return array<string, mixed>
  2071. */
  2072. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2073. {
  2074. return [
  2075. 'scydgy_id' => $scydgyId,
  2076. 'CCYDH' => $row['CCYDH'] ?? null,
  2077. 'CYJMC' => $row['CYJMC'] ?? null,
  2078. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2079. 'CDXMC' => $row['CDXMC'] ?? null,
  2080. 'CGYBH' => $row['CGYBH'] ?? null,
  2081. 'CGYMC' => $row['CGYMC'] ?? null,
  2082. 'CDW' => $row['CDW'] ?? null,
  2083. 'czlyq' => $row['czlyq'] ?? null,
  2084. 'NGZL' => $row['NGZL'] ?? null,
  2085. 'CDF' => $row['CDF'] ?? null,
  2086. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2087. 'MBZ' => $row['MBZ'] ?? null,
  2088. 'bwjg' => $row['bwjg'] ?? null,
  2089. 'iStatus' => $row['iStatus'] ?? null,
  2090. 'dStamp' => $row['dStamp'] ?? null,
  2091. 'dputrecord' => $row['dputrecord'] ?? null,
  2092. 'cywyxm' => $row['cywyxm'] ?? null,
  2093. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2094. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2095. ];
  2096. }
  2097. /**
  2098. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2099. *
  2100. * @return array{po:?array<string,mixed>, hidden:bool}
  2101. */
  2102. protected function resolvePickRowPoContext(int $sid): array
  2103. {
  2104. $po = null;
  2105. try {
  2106. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2107. if (is_array($found)) {
  2108. $po = $found;
  2109. }
  2110. } catch (\Throwable $e) {
  2111. }
  2112. $hideSet = $this->loadPickHiddenScydgySet();
  2113. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2114. }
  2115. /**
  2116. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2117. */
  2118. protected function assertPickRowCanDelete(int $sid, array $row): void
  2119. {
  2120. $ctx = $this->resolvePickRowPoContext($sid);
  2121. $po = $ctx['po'];
  2122. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2123. return;
  2124. }
  2125. if (is_array($po)) {
  2126. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2127. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2128. }
  2129. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2130. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2131. }
  2132. }
  2133. if ($ctx['hidden']) {
  2134. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2135. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2136. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2137. }
  2138. }
  2139. /**
  2140. * 初选直接完结前校验
  2141. */
  2142. protected function assertPickRowCanComplete(int $sid, array $row): void
  2143. {
  2144. $ctx = $this->resolvePickRowPoContext($sid);
  2145. $po = $ctx['po'];
  2146. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2147. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2148. }
  2149. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2150. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2151. }
  2152. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2153. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2154. }
  2155. }
  2156. /**
  2157. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2158. */
  2159. protected function softDeleteProcuremenPickRow(array $row): void
  2160. {
  2161. $sid = $this->extractScydgyRowId($row);
  2162. if (!$this->isValidScydgyRowId($sid)) {
  2163. throw new \InvalidArgumentException('无效的行主键');
  2164. }
  2165. $this->assertPickRowCanDelete($sid, $row);
  2166. $po = $this->resolvePickRowPoContext($sid)['po'];
  2167. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2168. return;
  2169. }
  2170. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2171. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2172. }
  2173. $now = date('Y-m-d H:i:s');
  2174. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2175. if (is_array($exists)) {
  2176. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2177. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2178. } else {
  2179. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2180. $data['mod_rq'] = $now;
  2181. $data['createtime'] = $now;
  2182. Db::table('purchase_order')->insert($data);
  2183. $poIdLog = (int)Db::getLastInsID();
  2184. }
  2185. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2186. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2187. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2188. if ($gymcLog !== '') {
  2189. $logTail .= ' / ' . $gymcLog;
  2190. }
  2191. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2192. }
  2193. /**
  2194. * 手工新增协助工序(写入 purchase_order)
  2195. *
  2196. * @param array<string, mixed> $params
  2197. * @return int scydgy_id
  2198. */
  2199. protected function saveManualPickOrder(array $params): int
  2200. {
  2201. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2202. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2203. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2204. if ($ccydh === '') {
  2205. $ccydh = $this->allocateManualOrderCcydh();
  2206. }
  2207. $now = date('Y-m-d H:i:s');
  2208. $sid = $this->allocateManualScydgyId();
  2209. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2210. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2211. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2212. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2213. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2214. $data = [
  2215. 'scydgy_id' => $sid,
  2216. 'CCYDH' => $ccydh,
  2217. 'CYJMC' => $cyjmc,
  2218. 'CGYMC' => $cgymc,
  2219. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2220. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2221. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2222. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2223. 'cGzzxMc' => $supplierName,
  2224. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2225. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2226. 'notify_salesman' => $notifySalesman,
  2227. 'rfq_salesman_notified' => 0,
  2228. 'rfq_salesman_notify_time' => null,
  2229. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2230. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2231. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2232. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2233. 'createtime' => $now,
  2234. 'dStamp' => $now,
  2235. 'dputrecord' => $now,
  2236. ];
  2237. Db::table('purchase_order')->insert($data);
  2238. $poId = (int)Db::getLastInsID();
  2239. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2240. return $sid;
  2241. }
  2242. protected function formatProcuremenRowLabel(array $row): string
  2243. {
  2244. $dh = trim((string)($row['CCYDH'] ?? ''));
  2245. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2246. if ($dh !== '' && $gymc !== '') {
  2247. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2248. }
  2249. if ($dh !== '') {
  2250. return '订单「' . $dh . '」';
  2251. }
  2252. if ($gymc !== '') {
  2253. return '工序「' . $gymc . '」';
  2254. }
  2255. $id = $this->extractScydgyRowId($row);
  2256. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2257. }
  2258. /**
  2259. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2260. */
  2261. protected function extractScydgyRowId(array $row): int
  2262. {
  2263. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2264. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2265. return (int)$row['scydgy_id'];
  2266. }
  2267. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2268. return (int)$row['SCYDGY_ID'];
  2269. }
  2270. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2271. }
  2272. protected function isValidScydgyRowId(int $id): bool
  2273. {
  2274. return ProcuremenGuard::isValidScydgyId($id);
  2275. }
  2276. protected function isManualScydgyRowId(int $id): bool
  2277. {
  2278. return $id < 0;
  2279. }
  2280. /**
  2281. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2282. *
  2283. * @param int[] $scydgyIds
  2284. * @return array<int, string[]>
  2285. */
  2286. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2287. {
  2288. $out = [];
  2289. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2290. if ($scydgyIds === []) {
  2291. return $out;
  2292. }
  2293. try {
  2294. $rows = Db::table('purchase_order_detail')
  2295. ->where('scydgy_id', 'in', $scydgyIds)
  2296. ->field('scydgy_id,company_name')
  2297. ->order('company_name', 'asc')
  2298. ->select();
  2299. } catch (\Throwable $e) {
  2300. $rows = [];
  2301. }
  2302. if (!is_array($rows)) {
  2303. return $out;
  2304. }
  2305. foreach ($rows as $r) {
  2306. if (!is_array($r)) {
  2307. continue;
  2308. }
  2309. $sid = (int)($r['scydgy_id'] ?? 0);
  2310. $cn = trim((string)($r['company_name'] ?? ''));
  2311. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2312. continue;
  2313. }
  2314. if (!isset($out[$sid])) {
  2315. $out[$sid] = [];
  2316. }
  2317. if (!in_array($cn, $out[$sid], true)) {
  2318. $out[$sid][] = $cn;
  2319. }
  2320. }
  2321. return $out;
  2322. }
  2323. /**
  2324. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2325. *
  2326. * @param string[] $names
  2327. */
  2328. protected function formatNotifySupplierDisplay(array $names): string
  2329. {
  2330. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2331. return trim((string)$n);
  2332. }, $names))));
  2333. if ($names === []) {
  2334. return '';
  2335. }
  2336. sort($names, SORT_STRING);
  2337. return implode("\n", $names);
  2338. }
  2339. /**
  2340. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2341. *
  2342. * @param int[] $scydgyIds
  2343. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2344. */
  2345. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2346. {
  2347. $out = [];
  2348. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2349. if ($scydgyIds === []) {
  2350. return $out;
  2351. }
  2352. try {
  2353. $rows = Db::table('purchase_order_detail')
  2354. ->where('scydgy_id', 'in', $scydgyIds)
  2355. ->field('scydgy_id,company_name,amount')
  2356. ->select();
  2357. } catch (\Throwable $e) {
  2358. $rows = [];
  2359. }
  2360. if (!is_array($rows)) {
  2361. return $out;
  2362. }
  2363. foreach ($rows as $r) {
  2364. if (!is_array($r)) {
  2365. continue;
  2366. }
  2367. $sid = (int)($r['scydgy_id'] ?? 0);
  2368. $cn = trim((string)($r['company_name'] ?? ''));
  2369. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2370. continue;
  2371. }
  2372. if (!isset($out[$sid])) {
  2373. $out[$sid] = ['all' => [], 'quoted' => []];
  2374. }
  2375. $out[$sid]['all'][$cn] = true;
  2376. $am = trim((string)($r['amount'] ?? ''));
  2377. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2378. $out[$sid]['quoted'][$cn] = true;
  2379. }
  2380. }
  2381. return $out;
  2382. }
  2383. /**
  2384. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2385. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2386. */
  2387. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2388. {
  2389. $merged = ['all' => [], 'quoted' => []];
  2390. foreach ($buckets as $b) {
  2391. if (!is_array($b)) {
  2392. continue;
  2393. }
  2394. foreach ($b['all'] ?? [] as $cn => $_) {
  2395. $merged['all'][$cn] = true;
  2396. }
  2397. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2398. $merged['quoted'][$cn] = true;
  2399. }
  2400. }
  2401. return $merged;
  2402. }
  2403. /**
  2404. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2405. */
  2406. protected function formatQuotedSupplierLines(array $bucket): string
  2407. {
  2408. $all = array_keys($bucket['all'] ?? []);
  2409. if ($all === []) {
  2410. return '';
  2411. }
  2412. sort($all, SORT_STRING);
  2413. $lines = [];
  2414. foreach ($all as $cn) {
  2415. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2416. $lines[] = $cn . '(' . $status . ')';
  2417. }
  2418. return implode("\n", $lines);
  2419. }
  2420. /**
  2421. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2422. */
  2423. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2424. {
  2425. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2426. $this->view->engine->layout(false);
  2427. try {
  2428. $bodyHtml = $this->view->fetch($view);
  2429. $this->view->assign('dialogBody', $bodyHtml);
  2430. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2431. return $this->view->fetch('procuremen/dialog_lite_shell');
  2432. } finally {
  2433. if ($restoreLayout) {
  2434. $this->view->engine->layout($restoreLayout);
  2435. }
  2436. }
  2437. }
  2438. /**
  2439. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2440. */
  2441. protected function resolveBundleSysRq(array $bundle): string
  2442. {
  2443. foreach ($bundle['pos'] ?? [] as $po) {
  2444. if (!is_array($po)) {
  2445. continue;
  2446. }
  2447. $sr = trim((string)($po['sys_rq'] ?? ''));
  2448. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2449. return $sr;
  2450. }
  2451. }
  2452. return '';
  2453. }
  2454. /**
  2455. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2456. */
  2457. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2458. {
  2459. $raw = trim((string)$sysRq);
  2460. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2461. return true;
  2462. }
  2463. $ts = strtotime(str_replace('T', ' ', $raw));
  2464. if ($ts === false || $ts <= 0) {
  2465. return true;
  2466. }
  2467. return time() >= $ts;
  2468. }
  2469. /**
  2470. * 开标前校验:必须已过报价截止时间
  2471. *
  2472. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2473. */
  2474. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2475. {
  2476. $sysRq = $this->resolveBundleSysRq($bundle);
  2477. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2478. $this->error('未到招标截止日期');
  2479. }
  2480. }
  2481. /**
  2482. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2483. *
  2484. * @param array<string, mixed> $d
  2485. * @param string $deliveryYmd
  2486. */
  2487. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2488. {
  2489. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2490. return max(0, (int)$d['lead_days']);
  2491. }
  2492. if ($deliveryYmd === '') {
  2493. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2494. }
  2495. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2496. return null;
  2497. }
  2498. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2499. $t2 = strtotime($m[1] . ' 00:00:00');
  2500. if ($t1 === false || $t2 === false) {
  2501. return null;
  2502. }
  2503. return max(0, (int)round(($t2 - $t1) / 86400));
  2504. }
  2505. /**
  2506. * @param int|null $days
  2507. */
  2508. protected function formatProcuremenLeadDaysText($days): string
  2509. {
  2510. if ($days === null || $days === '') {
  2511. return '未填写';
  2512. }
  2513. if (!is_numeric($days)) {
  2514. return '未填写';
  2515. }
  2516. return ((int)$days) . '天';
  2517. }
  2518. /**
  2519. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2520. *
  2521. * @param array<string, mixed> $line
  2522. */
  2523. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2524. {
  2525. $amountFilled = !empty($line['amount_filled']);
  2526. $deliveryFilled = !empty($line['delivery_filled']);
  2527. $leadFilled = !empty($line['lead_days_filled']);
  2528. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2529. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2530. $line['amount_show'] = '';
  2531. if (array_key_exists('amount_text', $line)) {
  2532. $line['amount_text'] = $line['unit_price_text'];
  2533. }
  2534. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2535. $line['delivery_show'] = $deliveryText;
  2536. if (array_key_exists('delivery_text', $line)) {
  2537. $line['delivery_text'] = $deliveryText;
  2538. }
  2539. $line['delivery_ymd'] = '';
  2540. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2541. $line['lead_days_show'] = $leadText;
  2542. $line['lead_days_text'] = $leadText;
  2543. $line['lead_days'] = '';
  2544. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2545. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2546. $line['subtotal_num'] = null;
  2547. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2548. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2549. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2550. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2551. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2552. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2553. $line['amount_filled'] = false;
  2554. $line['delivery_filled'] = false;
  2555. $line['lead_days_filled'] = false;
  2556. $line['is_quoted'] = false;
  2557. if (array_key_exists('quote_label', $line)) {
  2558. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2559. }
  2560. }
  2561. protected function ensurePurchaseOrderBidOpenTable(): void
  2562. {
  2563. static $ready = false;
  2564. if ($ready) {
  2565. return;
  2566. }
  2567. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2568. try {
  2569. if (Cache::get($cacheKey)) {
  2570. $ready = true;
  2571. return;
  2572. }
  2573. } catch (\Throwable $e) {
  2574. }
  2575. try {
  2576. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2577. $ready = true;
  2578. try {
  2579. Cache::set($cacheKey, 1, 86400);
  2580. } catch (\Throwable $e) {
  2581. }
  2582. } catch (\Throwable $e) {
  2583. Db::execute(
  2584. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2585. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2586. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2587. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2588. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2589. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2590. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2591. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2592. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2593. `createtime` datetime DEFAULT NULL,
  2594. PRIMARY KEY (`id`),
  2595. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2596. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2597. );
  2598. $ready = true;
  2599. try {
  2600. Cache::set($cacheKey, 1, 86400);
  2601. } catch (\Throwable $e2) {
  2602. }
  2603. }
  2604. }
  2605. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2606. {
  2607. $ccydh = trim($ccydh);
  2608. if ($ccydh === '') {
  2609. return false;
  2610. }
  2611. $this->ensurePurchaseOrderBidOpenTable();
  2612. try {
  2613. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2614. return is_array($row);
  2615. } catch (\Throwable $e) {
  2616. return false;
  2617. }
  2618. }
  2619. /**
  2620. * 批量查询订单是否已开标验证
  2621. *
  2622. * @param array<int, string> $ccydhs
  2623. * @return array<string, bool> ccydh => true
  2624. */
  2625. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2626. {
  2627. $set = [];
  2628. $list = [];
  2629. foreach ($ccydhs as $c) {
  2630. $c = trim((string)$c);
  2631. if ($c !== '') {
  2632. $list[$c] = true;
  2633. }
  2634. }
  2635. if ($list === []) {
  2636. return $set;
  2637. }
  2638. $this->ensurePurchaseOrderBidOpenTable();
  2639. try {
  2640. $rows = Db::table('purchase_order_bid_open')
  2641. ->where('ccydh', 'in', array_keys($list))
  2642. ->field('ccydh')
  2643. ->select();
  2644. foreach ($rows as $row) {
  2645. if (!is_array($row)) {
  2646. continue;
  2647. }
  2648. $c = trim((string)($row['ccydh'] ?? ''));
  2649. if ($c !== '') {
  2650. $set[$c] = true;
  2651. }
  2652. }
  2653. } catch (\Throwable $e) {
  2654. return [];
  2655. }
  2656. return $set;
  2657. }
  2658. /**
  2659. * 批量查询订单是否已指定供应商(免开标)
  2660. *
  2661. * @param array<int, string> $ccydhs
  2662. * @return array<string, bool> ccydh => true
  2663. */
  2664. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2665. {
  2666. $set = [];
  2667. $list = [];
  2668. foreach ($ccydhs as $c) {
  2669. $c = trim((string)$c);
  2670. if ($c !== '') {
  2671. $list[$c] = true;
  2672. }
  2673. }
  2674. if ($list === []) {
  2675. return $set;
  2676. }
  2677. $this->ensurePurchaseOrderManualPickColumns();
  2678. try {
  2679. $rows = Db::table('purchase_order')
  2680. ->where('CCYDH', 'in', array_keys($list))
  2681. ->where('manual_pick', 1)
  2682. ->field('CCYDH')
  2683. ->select();
  2684. foreach ($rows as $row) {
  2685. if (!is_array($row)) {
  2686. continue;
  2687. }
  2688. $c = trim((string)($row['CCYDH'] ?? ''));
  2689. if ($c !== '') {
  2690. $set[$c] = true;
  2691. }
  2692. }
  2693. } catch (\Throwable $e) {
  2694. return [];
  2695. }
  2696. return $set;
  2697. }
  2698. /**
  2699. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2700. *
  2701. * @param array<int, array<string, mixed>> $pool
  2702. * @return array<int, array<string, mixed>>
  2703. */
  2704. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2705. {
  2706. $status = trim($status);
  2707. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2708. return $pool;
  2709. }
  2710. $ccydhList = [];
  2711. foreach ($pool as $rw) {
  2712. if (!is_array($rw)) {
  2713. continue;
  2714. }
  2715. $c = trim((string)($rw['CCYDH'] ?? ''));
  2716. if ($c !== '') {
  2717. $ccydhList[] = $c;
  2718. }
  2719. }
  2720. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2721. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2722. $out = [];
  2723. foreach ($pool as $rw) {
  2724. if (!is_array($rw)) {
  2725. continue;
  2726. }
  2727. $c = trim((string)($rw['CCYDH'] ?? ''));
  2728. if ($c !== '' && isset($bidOpenSet[$c])) {
  2729. $t = '已开标';
  2730. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2731. $t = '已指定供应商';
  2732. } else {
  2733. $t = '待开标';
  2734. }
  2735. if ($t === $status) {
  2736. $out[] = $rw;
  2737. }
  2738. }
  2739. return $out;
  2740. }
  2741. /**
  2742. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2743. *
  2744. * @param array<string, mixed> $group
  2745. */
  2746. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2747. {
  2748. if ($quoteVisible) {
  2749. $group['remark_quote_pending'] = 0;
  2750. return;
  2751. }
  2752. $group['remark'] = '';
  2753. $group['remark_quote_pending'] = 0;
  2754. }
  2755. /**
  2756. * @param array{ccydh?:string} $bundle
  2757. */
  2758. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2759. {
  2760. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2761. }
  2762. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2763. {
  2764. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2765. return true;
  2766. }
  2767. return $this->isProcuremenManualPickedForBundle($bundle);
  2768. }
  2769. /**
  2770. * 确保 purchase_order 自选供应商字段
  2771. */
  2772. protected function ensurePurchaseOrderManualPickColumns(): void
  2773. {
  2774. static $done = false;
  2775. if ($done) {
  2776. return;
  2777. }
  2778. $done = true;
  2779. $adds = [
  2780. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2781. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2782. ];
  2783. foreach ($adds as $col => $ddl) {
  2784. try {
  2785. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2786. if (!is_array($cols) || $cols === []) {
  2787. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2788. }
  2789. } catch (\Throwable $e) {
  2790. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2791. }
  2792. }
  2793. }
  2794. /**
  2795. * 是否已自选供应商(免开标查看报价)
  2796. *
  2797. * @param array{pos?:array} $bundle
  2798. */
  2799. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2800. {
  2801. $this->ensurePurchaseOrderManualPickColumns();
  2802. foreach ($bundle['pos'] ?? [] as $poRow) {
  2803. if (!is_array($poRow)) {
  2804. continue;
  2805. }
  2806. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2807. return true;
  2808. }
  2809. }
  2810. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2811. if ($ccydh === '') {
  2812. return false;
  2813. }
  2814. try {
  2815. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2816. return $v !== null && $v !== false && (int)$v > 0;
  2817. } catch (\Throwable $e) {
  2818. return false;
  2819. }
  2820. }
  2821. /**
  2822. * @param array{pos?:array} $bundle
  2823. * @return array{company:string,reason:string}
  2824. */
  2825. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2826. {
  2827. $this->ensurePurchaseOrderManualPickColumns();
  2828. foreach ($bundle['pos'] ?? [] as $poRow) {
  2829. if (!is_array($poRow)) {
  2830. continue;
  2831. }
  2832. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2833. continue;
  2834. }
  2835. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2836. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2837. return ['company' => $cn, 'reason' => $reason];
  2838. }
  2839. return ['company' => '', 'reason' => ''];
  2840. }
  2841. protected function loadBidOpenAdminUser(int $adminId): ?array
  2842. {
  2843. if ($adminId <= 0) {
  2844. return null;
  2845. }
  2846. try {
  2847. $row = Db::name('admin')->where('id', $adminId)->find();
  2848. } catch (\Throwable $e) {
  2849. return null;
  2850. }
  2851. if (!is_array($row)) {
  2852. return null;
  2853. }
  2854. $status = strtolower(trim((string)($row['status'] ?? '')));
  2855. if ($status !== '' && $status !== 'normal') {
  2856. return null;
  2857. }
  2858. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2859. return null;
  2860. }
  2861. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2862. if (!preg_match('/^1\d{10}$/', $phone)) {
  2863. return null;
  2864. }
  2865. $name = trim((string)($row['nickname'] ?? ''));
  2866. if ($name === '') {
  2867. $name = trim((string)($row['username'] ?? ''));
  2868. }
  2869. return [
  2870. 'id' => (int)$row['id'],
  2871. 'username' => trim((string)($row['username'] ?? '')),
  2872. 'nickname' => $name,
  2873. 'mobile' => $phone,
  2874. ];
  2875. }
  2876. /**
  2877. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2878. */
  2879. protected function bidOpenVerifierAuthGroupRootId(): int
  2880. {
  2881. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2882. return $id > 0 ? $id : 10;
  2883. }
  2884. /**
  2885. * @return int[]
  2886. */
  2887. protected function loadBidOpenVerifierAuthGroupIds(): array
  2888. {
  2889. static $memo = [];
  2890. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2891. if (isset($memo[$rootId])) {
  2892. return $memo[$rootId];
  2893. }
  2894. try {
  2895. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2896. } catch (\Throwable $e) {
  2897. $memo[$rootId] = [$rootId];
  2898. return $memo[$rootId];
  2899. }
  2900. if (!is_array($groups) || $groups === []) {
  2901. $memo[$rootId] = [$rootId];
  2902. return $memo[$rootId];
  2903. }
  2904. $groupList = [];
  2905. foreach ($groups as $g) {
  2906. if (is_array($g)) {
  2907. $groupList[] = $g;
  2908. }
  2909. }
  2910. if ($groupList === []) {
  2911. $memo[$rootId] = [$rootId];
  2912. return $memo[$rootId];
  2913. }
  2914. $tree = \fast\Tree::instance();
  2915. $tree->init($groupList);
  2916. $ids = $tree->getChildrenIds($rootId, true);
  2917. if (!is_array($ids) || $ids === []) {
  2918. $memo[$rootId] = [$rootId];
  2919. return $memo[$rootId];
  2920. }
  2921. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2922. return $memo[$rootId];
  2923. }
  2924. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2925. {
  2926. if ($adminId <= 0) {
  2927. return false;
  2928. }
  2929. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2930. if ($groupIds === []) {
  2931. return false;
  2932. }
  2933. try {
  2934. return (bool)Db::name('auth_group_access')
  2935. ->where('uid', $adminId)
  2936. ->where('group_id', 'in', $groupIds)
  2937. ->count();
  2938. } catch (\Throwable $e) {
  2939. return false;
  2940. }
  2941. }
  2942. /**
  2943. * @return array<int, array<string, mixed>>
  2944. */
  2945. protected function listBidOpenVerifierCandidates(): array
  2946. {
  2947. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2948. if ($groupIds === []) {
  2949. return [];
  2950. }
  2951. try {
  2952. $adminIds = Db::name('auth_group_access')
  2953. ->where('group_id', 'in', $groupIds)
  2954. ->column('uid');
  2955. } catch (\Throwable $e) {
  2956. $adminIds = [];
  2957. }
  2958. $adminIds = is_array($adminIds)
  2959. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2960. : [];
  2961. if ($adminIds === []) {
  2962. return [];
  2963. }
  2964. try {
  2965. $rows = Db::name('admin')
  2966. ->where('status', 'normal')
  2967. ->where('id', 'in', $adminIds)
  2968. ->where('mobile', '<>', '')
  2969. ->order('id', 'asc')
  2970. ->select();
  2971. } catch (\Throwable $e) {
  2972. return [];
  2973. }
  2974. if (!is_array($rows)) {
  2975. return [];
  2976. }
  2977. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2978. $out = [];
  2979. foreach ($rows as $row) {
  2980. if (!is_array($row)) {
  2981. continue;
  2982. }
  2983. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2984. if ($one === null) {
  2985. continue;
  2986. }
  2987. $out[] = [
  2988. 'id' => $one['id'],
  2989. 'username' => $one['username'],
  2990. 'nickname' => $one['nickname'],
  2991. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2992. 'mobile' => mask_phone($one['mobile']),
  2993. ];
  2994. }
  2995. return $out;
  2996. }
  2997. /**
  2998. * @param int[] $adminIds
  2999. * @return array<int, string>
  3000. */
  3001. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3002. {
  3003. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3004. if ($adminIds === []) {
  3005. return [];
  3006. }
  3007. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3008. try {
  3009. $rows = Db::name('auth_group_access')
  3010. ->alias('aga')
  3011. ->join('auth_group ag', 'aga.group_id = ag.id')
  3012. ->where('aga.uid', 'in', $adminIds)
  3013. ->where('aga.group_id', 'in', $groupIds)
  3014. ->field('aga.uid,ag.name')
  3015. ->order('aga.uid', 'asc')
  3016. ->order('aga.group_id', 'asc')
  3017. ->select();
  3018. } catch (\Throwable $e) {
  3019. return [];
  3020. }
  3021. if (!is_array($rows)) {
  3022. return [];
  3023. }
  3024. $out = [];
  3025. foreach ($rows as $row) {
  3026. if (!is_array($row)) {
  3027. continue;
  3028. }
  3029. $uid = (int)($row['uid'] ?? 0);
  3030. $name = trim((string)($row['name'] ?? ''));
  3031. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3032. continue;
  3033. }
  3034. $out[$uid] = $name;
  3035. }
  3036. return $out;
  3037. }
  3038. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3039. {
  3040. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3041. }
  3042. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3043. {
  3044. return 'procuremen_bidopen_wait_' . $adminId;
  3045. }
  3046. protected function renderBidOpenVerifySms(string $code): string
  3047. {
  3048. $tpl = '';
  3049. try {
  3050. $row = $this->loadNotifyTemplateRow('bid_open');
  3051. if (is_array($row)) {
  3052. $tpl = trim((string)($row['content'] ?? ''));
  3053. }
  3054. } catch (\Throwable $e) {
  3055. $tpl = '';
  3056. }
  3057. if ($tpl === '') {
  3058. $tpl = '【可集达】您的短信验证码是{code}';
  3059. }
  3060. return str_replace('{code}', $code, $tpl);
  3061. }
  3062. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3063. {
  3064. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3065. }
  3066. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3067. {
  3068. $code = trim($code);
  3069. if (!preg_match('/^\d{6}$/', $code)) {
  3070. return false;
  3071. }
  3072. $mock = Config::get('mproc.mock_sms_code');
  3073. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3074. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3075. return true;
  3076. }
  3077. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3078. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3079. return false;
  3080. }
  3081. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3082. return true;
  3083. }
  3084. /**
  3085. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3086. */
  3087. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3088. {
  3089. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3090. if ($ccydh === '') {
  3091. throw new \InvalidArgumentException('订单号无效');
  3092. }
  3093. $this->ensurePurchaseOrderBidOpenTable();
  3094. list($operatorId, $operatorName) = $this->GetUseName();
  3095. $now = date('Y-m-d H:i:s');
  3096. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3097. $payload = [
  3098. 'ccydh' => $ccydh,
  3099. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3100. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3101. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3102. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3103. 'operator_id' => (int)$operatorId,
  3104. 'operator_name' => trim((string)$operatorName),
  3105. 'createtime' => $now,
  3106. ];
  3107. if (is_array($exists)) {
  3108. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3109. } else {
  3110. Db::table('purchase_order_bid_open')->insert($payload);
  3111. }
  3112. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3113. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3114. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3115. (int)$payload['verifier1_id'],
  3116. (int)$payload['verifier2_id'],
  3117. ]);
  3118. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3119. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3120. }
  3121. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3122. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3123. }
  3124. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3125. $seenSid = [];
  3126. foreach ($bundle['pos'] ?? [] as $poRow) {
  3127. if (!is_array($poRow)) {
  3128. continue;
  3129. }
  3130. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3131. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3132. continue;
  3133. }
  3134. $seenSid[$sid] = true;
  3135. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3136. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3137. }
  3138. if ($seenSid === []) {
  3139. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3140. if ($this->isValidScydgyRowId($anchor)) {
  3141. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3142. }
  3143. }
  3144. // 开标通过后计算并写入供应商服务评分
  3145. try {
  3146. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3147. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3148. } catch (\Throwable $e) {
  3149. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3150. }
  3151. }
  3152. /**
  3153. * 报价行展示字段默认值(模板安全访问)
  3154. *
  3155. * @param array<string, mixed> $line
  3156. * @return array<string, mixed>
  3157. */
  3158. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3159. {
  3160. if (!array_key_exists('amount_quote_pending', $line)) {
  3161. $line['amount_quote_pending'] = 0;
  3162. }
  3163. if (!array_key_exists('delivery_quote_pending', $line)) {
  3164. $line['delivery_quote_pending'] = 0;
  3165. }
  3166. if (!array_key_exists('quote_before_deadline', $line)) {
  3167. $line['quote_before_deadline'] = 0;
  3168. }
  3169. if (!array_key_exists('amount_filled', $line)) {
  3170. $line['amount_filled'] = 0;
  3171. }
  3172. if (!array_key_exists('delivery_filled', $line)) {
  3173. $line['delivery_filled'] = 0;
  3174. }
  3175. if (!array_key_exists('lead_days_filled', $line)) {
  3176. $line['lead_days_filled'] = 0;
  3177. }
  3178. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3179. $line['lead_days_quote_pending'] = 0;
  3180. }
  3181. if (!array_key_exists('lead_days_show', $line)) {
  3182. $line['lead_days_show'] = '未填写';
  3183. }
  3184. if (!array_key_exists('lead_days_text', $line)) {
  3185. $line['lead_days_text'] = $line['lead_days_show'];
  3186. }
  3187. return $line;
  3188. }
  3189. /**
  3190. * 审核弹窗:按供应商汇总报价明细
  3191. *
  3192. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3193. * @return array<int, array<string, mixed>>
  3194. */
  3195. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3196. {
  3197. $sids = [];
  3198. foreach ($bundle['pos'] ?? [] as $po) {
  3199. if (!is_array($po)) {
  3200. continue;
  3201. }
  3202. $sid = (int)($po['scydgy_id'] ?? 0);
  3203. if ($this->isValidScydgyRowId($sid)) {
  3204. $sids[$sid] = true;
  3205. }
  3206. }
  3207. if ($sids === []) {
  3208. return [];
  3209. }
  3210. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3211. $gymcMap = [];
  3212. $qtyBySid = [];
  3213. $orderedSids = [];
  3214. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3215. if (!is_array($mr)) {
  3216. continue;
  3217. }
  3218. $gid = $this->extractScydgyRowId($mr);
  3219. if ($this->isValidScydgyRowId($gid)) {
  3220. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3221. $orderedSids[] = $gid;
  3222. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3223. if ($qty === '') {
  3224. $qty = trim((string)($mr['NGZL'] ?? ''));
  3225. }
  3226. $qtyBySid[$gid] = $qty;
  3227. }
  3228. }
  3229. foreach ($bundle['pos'] ?? [] as $po) {
  3230. if (!is_array($po)) {
  3231. continue;
  3232. }
  3233. $gid = (int)($po['scydgy_id'] ?? 0);
  3234. if ($this->isValidScydgyRowId($gid)) {
  3235. $nm = trim((string)($po['CGYMC'] ?? ''));
  3236. if ($nm !== '') {
  3237. $gymcMap[$gid] = $nm;
  3238. }
  3239. if (!in_array($gid, $orderedSids, true)) {
  3240. $orderedSids[] = $gid;
  3241. }
  3242. }
  3243. }
  3244. try {
  3245. $detailsQuery = Db::table('purchase_order_detail')
  3246. ->where('scydgy_id', 'in', array_keys($sids));
  3247. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3248. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3249. } catch (\Throwable $e) {
  3250. try {
  3251. $detailsQuery = Db::table('purchase_order_detail')
  3252. ->where('scydgy_id', 'in', array_keys($sids));
  3253. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3254. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3255. } catch (\Throwable $e2) {
  3256. $details = [];
  3257. }
  3258. }
  3259. if (!is_array($details)) {
  3260. $details = [];
  3261. }
  3262. $byCompany = [];
  3263. foreach ($details as $d) {
  3264. if (!is_array($d)) {
  3265. continue;
  3266. }
  3267. $cn = trim((string)($d['company_name'] ?? ''));
  3268. if ($cn === '') {
  3269. continue;
  3270. }
  3271. if (!isset($byCompany[$cn])) {
  3272. $ph = trim((string)($d['phone'] ?? ''));
  3273. $username = trim((string)($d['username'] ?? ''));
  3274. if ($username === '') {
  3275. $username = $this->resolveCustomerContactName($ph, $cn);
  3276. }
  3277. $byCompany[$cn] = [
  3278. 'name' => $cn,
  3279. 'email' => trim((string)($d['email'] ?? '')),
  3280. 'phone' => $ph,
  3281. 'username' => $username,
  3282. 'remark' => '',
  3283. 'has_quote' => false,
  3284. 'lines_map' => [],
  3285. ];
  3286. }
  3287. if ($byCompany[$cn]['remark'] === '') {
  3288. $rm = '';
  3289. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3290. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3291. $rm = trim((string)$d[$rk]);
  3292. break;
  3293. }
  3294. }
  3295. if ($rm !== '') {
  3296. $byCompany[$cn]['remark'] = $rm;
  3297. }
  3298. }
  3299. $sid = (int)($d['scydgy_id'] ?? 0);
  3300. $am = trim((string)($d['amount'] ?? ''));
  3301. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3302. if ($gymc === '') {
  3303. $gymc = '工序';
  3304. }
  3305. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3306. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3307. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3308. $deliveryShow = $deliveryRaw;
  3309. }
  3310. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3311. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3312. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3313. $subtotal = null;
  3314. if ($amountNum !== null) {
  3315. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3316. }
  3317. $unitPriceText = $amountFilled
  3318. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3319. : '未填写';
  3320. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3321. $leadFilled = ($leadDays !== null);
  3322. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3323. $lineRow = [
  3324. 'cgymc' => $gymc,
  3325. 'amount' => $am,
  3326. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3327. 'amount_filled' => $amountFilled,
  3328. 'unit_price_text' => $unitPriceText,
  3329. 'delivery' => $deliveryRaw,
  3330. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3331. 'delivery_filled' => $deliveryFilled,
  3332. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3333. 'lead_days' => $leadFilled ? $leadDays : '',
  3334. 'lead_days_filled'=> $leadFilled,
  3335. 'lead_days_show' => $leadText,
  3336. 'lead_days_text' => $leadText,
  3337. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3338. 'subtotal_num' => $subtotal,
  3339. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3340. 'is_quoted' => $amountFilled,
  3341. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3342. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3343. ];
  3344. if (!$quoteVisible) {
  3345. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3346. }
  3347. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3348. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3349. }
  3350. foreach ($byCompany as $cn => $g) {
  3351. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3352. $lines = [];
  3353. $usedSids = [];
  3354. foreach ($orderedSids as $sid) {
  3355. if (!isset($linesMap[$sid])) {
  3356. continue;
  3357. }
  3358. $lines[] = $linesMap[$sid];
  3359. $usedSids[$sid] = true;
  3360. }
  3361. foreach ($linesMap as $sid => $ln) {
  3362. if (isset($usedSids[$sid])) {
  3363. continue;
  3364. }
  3365. $lines[] = $ln;
  3366. }
  3367. $total = count($lines);
  3368. $quoted = 0;
  3369. $groupTotal = 0.0;
  3370. $groupHasTotal = false;
  3371. if ($quoteVisible) {
  3372. foreach ($lines as $ln) {
  3373. $am = trim((string)($ln['amount'] ?? ''));
  3374. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3375. $quoted++;
  3376. }
  3377. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3378. $groupTotal += (float)$ln['subtotal_num'];
  3379. $groupHasTotal = true;
  3380. }
  3381. }
  3382. }
  3383. unset($byCompany[$cn]['lines_map']);
  3384. $byCompany[$cn]['lines'] = $lines;
  3385. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3386. $byCompany[$cn]['line_count'] = $total;
  3387. $byCompany[$cn]['has_total'] = $total > 0;
  3388. $byCompany[$cn]['has_remark'] = $total > 0;
  3389. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3390. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3391. // 工序行 + 备注行 + 总计行
  3392. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3393. }
  3394. $groups = array_values($byCompany);
  3395. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3396. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3397. }
  3398. /**
  3399. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3400. *
  3401. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3402. * @return array<int, array<string, mixed>>
  3403. */
  3404. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3405. {
  3406. $sids = [];
  3407. $poIdMap = [];
  3408. foreach ($bundle['pos'] ?? [] as $po) {
  3409. if (!is_array($po)) {
  3410. continue;
  3411. }
  3412. $sid = (int)($po['scydgy_id'] ?? 0);
  3413. if ($this->isValidScydgyRowId($sid)) {
  3414. $sids[$sid] = true;
  3415. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3416. }
  3417. }
  3418. if ($sids === []) {
  3419. return [];
  3420. }
  3421. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3422. $gymcMap = [];
  3423. $qtyBySid = [];
  3424. $orderedSids = [];
  3425. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3426. if (!is_array($mr)) {
  3427. continue;
  3428. }
  3429. $gid = $this->extractScydgyRowId($mr);
  3430. if ($this->isValidScydgyRowId($gid)) {
  3431. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3432. $orderedSids[] = $gid;
  3433. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3434. if ($qty === '') {
  3435. $qty = trim((string)($mr['NGZL'] ?? ''));
  3436. }
  3437. $qtyBySid[$gid] = $qty;
  3438. }
  3439. }
  3440. foreach ($bundle['pos'] ?? [] as $po) {
  3441. if (!is_array($po)) {
  3442. continue;
  3443. }
  3444. $gid = (int)($po['scydgy_id'] ?? 0);
  3445. if ($this->isValidScydgyRowId($gid)) {
  3446. $nm = trim((string)($po['CGYMC'] ?? ''));
  3447. if ($nm !== '') {
  3448. $gymcMap[$gid] = $nm;
  3449. }
  3450. }
  3451. }
  3452. try {
  3453. $details = Db::table('purchase_order_detail')
  3454. ->where('scydgy_id', 'in', array_keys($sids))
  3455. ->order('company_name', 'asc')
  3456. ->order('id', 'asc')
  3457. ->select();
  3458. } catch (\Throwable $e) {
  3459. try {
  3460. $details = Db::table('purchase_order_detail')
  3461. ->where('scydgy_id', 'in', array_keys($sids))
  3462. ->order('company_name', 'asc')
  3463. ->order('ID', 'asc')
  3464. ->select();
  3465. } catch (\Throwable $e2) {
  3466. $details = [];
  3467. }
  3468. }
  3469. if (!is_array($details)) {
  3470. $details = [];
  3471. }
  3472. $byCompany = [];
  3473. foreach ($details as $d) {
  3474. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3475. continue;
  3476. }
  3477. $cn = trim((string)($d['company_name'] ?? ''));
  3478. if ($cn === '') {
  3479. continue;
  3480. }
  3481. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3482. $sid = (int)($d['scydgy_id'] ?? 0);
  3483. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3484. continue;
  3485. }
  3486. if (!isset($byCompany[$cn])) {
  3487. $ph = trim((string)($d['phone'] ?? ''));
  3488. $username = trim((string)($d['username'] ?? ''));
  3489. if ($username === '') {
  3490. $username = $this->resolveCustomerContactName($ph, $cn);
  3491. }
  3492. $byCompany[$cn] = [
  3493. 'name' => $cn,
  3494. 'email' => trim((string)($d['email'] ?? '')),
  3495. 'phone' => $ph,
  3496. 'username' => $username,
  3497. 'remark' => '',
  3498. 'pick_lines' => [],
  3499. 'detail_picks' => [],
  3500. ];
  3501. }
  3502. if ($byCompany[$cn]['remark'] === '') {
  3503. $rm = '';
  3504. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3505. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3506. $rm = trim((string)$d[$rk]);
  3507. break;
  3508. }
  3509. }
  3510. if ($rm !== '') {
  3511. $byCompany[$cn]['remark'] = $rm;
  3512. }
  3513. }
  3514. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3515. if ($gymc === '') {
  3516. $gymc = '工序';
  3517. }
  3518. $am = trim((string)($d['amount'] ?? ''));
  3519. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3520. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3521. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3522. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3523. $deliveryShow = $deliveryRaw;
  3524. }
  3525. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3526. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3527. $subtotal = null;
  3528. if ($amountNum !== null) {
  3529. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3530. }
  3531. $unitPriceText = $amountFilled
  3532. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3533. : '未填写';
  3534. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3535. $leadFilled = ($leadDays !== null);
  3536. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3537. $pickLine = [
  3538. 'cgymc' => $gymc,
  3539. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3540. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3541. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3542. 'amount_filled' => $amountFilled,
  3543. 'delivery_filled' => $deliveryFilled,
  3544. 'unit_price_text' => $unitPriceText,
  3545. 'lead_days' => $leadFilled ? $leadDays : '',
  3546. 'lead_days_filled'=> $leadFilled,
  3547. 'lead_days_show' => $leadText,
  3548. 'lead_days_text' => $leadText,
  3549. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3550. 'subtotal_num' => $subtotal,
  3551. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3552. 'is_quoted' => $amountFilled,
  3553. ];
  3554. if (!$quoteVisible) {
  3555. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3556. }
  3557. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3558. $byCompany[$cn]['detail_picks'][$sid] = [
  3559. 'scydgy_id' => $sid,
  3560. 'detail_id' => $detailId,
  3561. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3562. 'cgymc' => $gymc,
  3563. ];
  3564. }
  3565. $out = [];
  3566. foreach ($byCompany as $g) {
  3567. $pickLinesMap = $g['pick_lines'] ?? [];
  3568. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3569. continue;
  3570. }
  3571. $pickLines = [];
  3572. $usedLineSids = [];
  3573. foreach ($orderedSids as $sid) {
  3574. if (!isset($pickLinesMap[$sid])) {
  3575. continue;
  3576. }
  3577. $pickLines[] = $pickLinesMap[$sid];
  3578. $usedLineSids[$sid] = true;
  3579. }
  3580. foreach ($pickLinesMap as $sid => $ln) {
  3581. if (isset($usedLineSids[$sid])) {
  3582. continue;
  3583. }
  3584. $pickLines[] = $ln;
  3585. }
  3586. $groupTotal = 0.0;
  3587. $groupHasTotal = false;
  3588. if ($quoteVisible) {
  3589. foreach ($pickLines as $ln) {
  3590. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3591. $groupTotal += (float)$ln['subtotal_num'];
  3592. $groupHasTotal = true;
  3593. }
  3594. }
  3595. }
  3596. $lineCount = count($pickLines);
  3597. $g['pick_lines'] = $pickLines;
  3598. $g['line_count'] = $lineCount;
  3599. $g['has_total'] = $lineCount > 0;
  3600. $g['has_remark'] = $lineCount > 0;
  3601. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3602. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3603. // 工序行 + 备注行 + 总计行
  3604. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3605. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3606. $detailPicks = [];
  3607. $usedPickSids = [];
  3608. foreach ($orderedSids as $sid) {
  3609. if (!isset($detailPicksMap[$sid])) {
  3610. continue;
  3611. }
  3612. $detailPicks[] = $detailPicksMap[$sid];
  3613. $usedPickSids[$sid] = true;
  3614. }
  3615. foreach ($detailPicksMap as $sid => $dp) {
  3616. if (isset($usedPickSids[$sid])) {
  3617. continue;
  3618. }
  3619. $detailPicks[] = $dp;
  3620. }
  3621. $g['detail_picks'] = $detailPicks;
  3622. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3623. unset($g['detail_picks']);
  3624. $out[] = $g;
  3625. }
  3626. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3627. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3628. }
  3629. /**
  3630. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3631. * @return array<int, int[]> scydgy_id => detail_id[]
  3632. */
  3633. protected function mapDetailIdsByScydgyId(array $details): array
  3634. {
  3635. $out = [];
  3636. foreach ($details as $d) {
  3637. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3638. continue;
  3639. }
  3640. $sid = (int)($d['scydgy_id'] ?? 0);
  3641. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3642. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3643. continue;
  3644. }
  3645. if (!isset($out[$sid])) {
  3646. $out[$sid] = [];
  3647. }
  3648. $out[$sid][] = $pk;
  3649. }
  3650. foreach ($out as $sid => $ids) {
  3651. $out[$sid] = array_values(array_unique($ids));
  3652. }
  3653. return $out;
  3654. }
  3655. /**
  3656. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3657. *
  3658. * @param array<string, mixed> $dbRow
  3659. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3660. */
  3661. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3662. {
  3663. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3664. $r = [
  3665. 'ID' => $sid,
  3666. 'scydgy_id' => $sid,
  3667. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3668. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3669. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3670. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3671. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3672. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3673. 'CDW' => $dbRow['CDW'] ?? '',
  3674. 'czlyq' => $dbRow['czlyq'] ?? '',
  3675. 'NGZL' => $dbRow['NGZL'] ?? '',
  3676. 'CDF' => $dbRow['CDF'] ?? '',
  3677. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3678. 'MBZ' => $dbRow['MBZ'] ?? '',
  3679. 'bwjg' => $dbRow['bwjg'] ?? '',
  3680. 'iStatus' => $dbRow['iStatus'] ?? '',
  3681. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3682. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3683. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3684. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3685. 'dStamp' => $dbRow['dStamp'] ?? '',
  3686. 'pick_time' => $dbRow['pick_time'] ?? '',
  3687. ];
  3688. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3689. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3690. if ($sid > 0 && isset($dStampMap[$sid])) {
  3691. $t = trim((string)$dStampMap[$sid]);
  3692. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3693. $r['dStamp'] = $dStampMap[$sid];
  3694. }
  3695. }
  3696. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3697. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3698. $ct = $dbRow['createtime'];
  3699. if (is_numeric($ct) && (int)$ct > 946684800) {
  3700. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3701. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3702. $r['dStamp'] = trim($ct);
  3703. }
  3704. }
  3705. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3706. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3707. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3708. $fallback = trim((string)($r['dStamp'] ?? ''));
  3709. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3710. $r['dputrecord'] = $fallback;
  3711. }
  3712. }
  3713. if (array_key_exists('id', $dbRow)) {
  3714. $r['purchase_order_id'] = (int)$dbRow['id'];
  3715. }
  3716. if ($sid < 0) {
  3717. $r['_is_manual'] = 1;
  3718. }
  3719. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3720. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3721. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3722. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3723. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3724. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3725. $r['pick_time'] = $pickFallback;
  3726. break;
  3727. }
  3728. }
  3729. }
  3730. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3731. if ($pickNm !== '') {
  3732. $r['pick_company_name'] = $pickNm;
  3733. $r['picked_supplier_name'] = $pickNm;
  3734. }
  3735. return $r;
  3736. }
  3737. /**
  3738. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3739. *
  3740. * @return array<int, array<string, mixed>>
  3741. */
  3742. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3743. {
  3744. $pool = [];
  3745. if (!is_array($dbRows) || $dbRows === []) {
  3746. return $pool;
  3747. }
  3748. $dStampMap = [];
  3749. $sidList = [];
  3750. foreach ($dbRows as $tmpRow) {
  3751. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3752. $sid = (int)$tmpRow['scydgy_id'];
  3753. if ($sid > 0) {
  3754. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3755. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3756. $sidList[$sid] = true;
  3757. }
  3758. }
  3759. }
  3760. }
  3761. if ($sidList !== []) {
  3762. try {
  3763. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3764. } catch (\Throwable $e) {
  3765. $dStampMap = [];
  3766. }
  3767. }
  3768. foreach ($dbRows as $dbRow) {
  3769. if (!is_array($dbRow)) {
  3770. continue;
  3771. }
  3772. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3773. }
  3774. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3775. $needCcydh = [];
  3776. foreach ($pool as $row) {
  3777. if (!is_array($row)) {
  3778. continue;
  3779. }
  3780. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3781. continue;
  3782. }
  3783. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3784. if ($ccydh !== '') {
  3785. $needCcydh[$ccydh] = true;
  3786. }
  3787. }
  3788. if ($needCcydh !== []) {
  3789. $czMap = [];
  3790. try {
  3791. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3792. } catch (\Throwable $e) {
  3793. $czMap = [];
  3794. }
  3795. if (is_array($czMap) && $czMap !== []) {
  3796. foreach ($pool as &$row) {
  3797. if (!is_array($row)) {
  3798. continue;
  3799. }
  3800. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3801. continue;
  3802. }
  3803. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3804. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3805. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3806. }
  3807. }
  3808. unset($row);
  3809. }
  3810. }
  3811. return $pool;
  3812. }
  3813. /**
  3814. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3815. *
  3816. * @param int[] $scydgyIds
  3817. * @return array<int, array<string, mixed>>
  3818. */
  3819. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3820. {
  3821. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3822. if ($scydgyIds === []) {
  3823. return [];
  3824. }
  3825. try {
  3826. $list = Db::table('purchase_order_detail')
  3827. ->where('scydgy_id', 'in', $scydgyIds)
  3828. ->field('scydgy_id,company_name,amount,delivery')
  3829. ->select();
  3830. } catch (\Throwable $e) {
  3831. $list = [];
  3832. }
  3833. return is_array($list) ? $list : [];
  3834. }
  3835. /**
  3836. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3837. *
  3838. * @param int[] $scydgyIds
  3839. * @param array<int, array<string, mixed>> $allRows
  3840. * @return array{cnt:int, amt:int, deliv:int}
  3841. */
  3842. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3843. {
  3844. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3845. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3846. if ($scydgyIds === [] || $allRows === []) {
  3847. return $out;
  3848. }
  3849. $idSet = array_flip($scydgyIds);
  3850. $all = [];
  3851. $withAmt = [];
  3852. $withDeliv = [];
  3853. foreach ($allRows as $r) {
  3854. if (!is_array($r)) {
  3855. continue;
  3856. }
  3857. $sid = (int)($r['scydgy_id'] ?? 0);
  3858. if (!isset($idSet[$sid])) {
  3859. continue;
  3860. }
  3861. $cn = trim((string)($r['company_name'] ?? ''));
  3862. if ($cn === '') {
  3863. continue;
  3864. }
  3865. $all[$cn] = true;
  3866. $am = $r['amount'] ?? null;
  3867. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3868. $withAmt[$cn] = true;
  3869. }
  3870. $dv = $r['delivery'] ?? null;
  3871. if ($dv !== null && trim((string)$dv) !== '') {
  3872. $withDeliv[$cn] = true;
  3873. }
  3874. }
  3875. return [
  3876. 'cnt' => count($all),
  3877. 'amt' => count($withAmt),
  3878. 'deliv' => count($withDeliv),
  3879. ];
  3880. }
  3881. /**
  3882. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3883. *
  3884. * @param array<string, mixed> $row
  3885. */
  3886. protected function resolveProcuremenThisQuantity(array $row): string
  3887. {
  3888. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3889. if ($q !== '') {
  3890. return $q;
  3891. }
  3892. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3893. if (!is_scalar($ngzl)) {
  3894. return '';
  3895. }
  3896. $s = trim((string)$ngzl);
  3897. if ($s === '') {
  3898. return '';
  3899. }
  3900. if (is_numeric($s) && (float)$s === 0.0) {
  3901. return '';
  3902. }
  3903. return $s;
  3904. }
  3905. /**
  3906. * @param array<string, mixed> $row
  3907. */
  3908. protected function resolveProcuremenCeilingPrice(array $row): string
  3909. {
  3910. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3911. }
  3912. /**
  3913. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3914. *
  3915. * @param array<int, mixed> $parts
  3916. */
  3917. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3918. {
  3919. $out = [];
  3920. foreach ($parts as $p) {
  3921. $s = trim((string)$p);
  3922. if ($s !== '') {
  3923. $out[] = $s;
  3924. }
  3925. }
  3926. return $out === [] ? '' : implode($sep, $out);
  3927. }
  3928. /**
  3929. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3930. *
  3931. * @param array<int, array<string, mixed>> $rows
  3932. */
  3933. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3934. {
  3935. if ($rows === []) {
  3936. return;
  3937. }
  3938. $idList = [];
  3939. foreach ($rows as $rw) {
  3940. if (!is_array($rw)) {
  3941. continue;
  3942. }
  3943. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3944. foreach ($rw['_order_merge_rows'] as $mr) {
  3945. if (!is_array($mr)) {
  3946. continue;
  3947. }
  3948. $mid = (int)($mr['ID'] ?? 0);
  3949. if ($this->isValidScydgyRowId($mid)) {
  3950. $idList[$mid] = true;
  3951. }
  3952. }
  3953. }
  3954. $id = (int)($rw['ID'] ?? 0);
  3955. if ($this->isValidScydgyRowId($id)) {
  3956. $idList[$id] = true;
  3957. }
  3958. }
  3959. if ($idList === []) {
  3960. return;
  3961. }
  3962. try {
  3963. $list = Db::table('purchase_order')
  3964. ->where('scydgy_id', 'in', array_keys($idList))
  3965. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  3966. ->select();
  3967. } catch (\Throwable $e) {
  3968. return;
  3969. }
  3970. if (!is_array($list)) {
  3971. return;
  3972. }
  3973. $byId = [];
  3974. foreach ($list as $dbRow) {
  3975. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3976. continue;
  3977. }
  3978. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3979. }
  3980. foreach ($rows as &$rw) {
  3981. if (!is_array($rw)) {
  3982. continue;
  3983. }
  3984. $mergeRows = [];
  3985. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3986. $mergeRows = $rw['_order_merge_rows'];
  3987. } else {
  3988. $mergeRows = [$rw];
  3989. }
  3990. $qtyList = [];
  3991. $priceList = [];
  3992. $picked = '';
  3993. foreach ($mergeRows as $mr) {
  3994. if (!is_array($mr)) {
  3995. continue;
  3996. }
  3997. $sid = (int)($mr['ID'] ?? 0);
  3998. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  3999. $src = $mr;
  4000. if (is_array($db)) {
  4001. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4002. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4003. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4004. if ($qDb !== '') {
  4005. $src['This_quantity'] = $qDb;
  4006. }
  4007. if ($pDb !== '') {
  4008. $src['ceilingPrice'] = $pDb;
  4009. }
  4010. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4011. $src['NGZL'] = $ngzlDb;
  4012. }
  4013. if ($picked === '') {
  4014. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4015. }
  4016. }
  4017. if ($picked === '') {
  4018. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4019. }
  4020. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4021. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4022. }
  4023. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4024. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4025. if ($picked !== '') {
  4026. $rw['pick_company_name'] = $picked;
  4027. $rw['picked_supplier_name'] = $picked;
  4028. }
  4029. }
  4030. unset($rw);
  4031. }
  4032. /**
  4033. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4034. *
  4035. * @param int[] $scydgyIds
  4036. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4037. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4038. */
  4039. protected function OrderDetailSummary(array $scydgyIds)
  4040. {
  4041. $out = [];
  4042. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4043. if ($scydgyIds === []) {
  4044. return $out;
  4045. }
  4046. $list = [];
  4047. try {
  4048. $list = Db::table('purchase_order_detail')
  4049. ->where('scydgy_id', 'in', $scydgyIds)
  4050. ->field('id,scydgy_id,amount,delivery')
  4051. ->select();
  4052. } catch (\Throwable $e) {
  4053. $list = [];
  4054. }
  4055. if (!is_array($list)) {
  4056. return $out;
  4057. }
  4058. foreach ($list as $r) {
  4059. if (!is_array($r)) {
  4060. continue;
  4061. }
  4062. $ids = (int)($r['scydgy_id'] ?? 0);
  4063. if (!$this->isValidScydgyRowId($ids)) {
  4064. continue;
  4065. }
  4066. if (!isset($out[$ids])) {
  4067. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4068. }
  4069. $out[$ids]['cnt']++;
  4070. $am = $r['amount'] ?? null;
  4071. if ($am !== null && $am !== '') {
  4072. if (!(is_string($am) && trim($am) === '')) {
  4073. $out[$ids]['amt']++;
  4074. }
  4075. }
  4076. $dv = $r['delivery'] ?? null;
  4077. if ($dv !== null && trim((string)$dv) !== '') {
  4078. $out[$ids]['deliv']++;
  4079. }
  4080. }
  4081. return $out;
  4082. }
  4083. /**
  4084. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4085. *
  4086. * @return array
  4087. */
  4088. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4089. {
  4090. $strContains = function ($haystack, $needle) {
  4091. if ($needle === '') {
  4092. return false;
  4093. }
  4094. $haystack = (string)$haystack;
  4095. if (function_exists('mb_stripos')) {
  4096. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4097. }
  4098. return stripos($haystack, $needle) !== false;
  4099. };
  4100. $stripAlias = function ($f) {
  4101. return preg_replace('/^[ab]\./i', '', (string)$f);
  4102. };
  4103. $searchColNames = [];
  4104. foreach (explode(',', $this->searchFields) as $colRaw) {
  4105. $c = $stripAlias(trim($colRaw));
  4106. if ($c !== '') {
  4107. $searchColNames[] = $c;
  4108. }
  4109. }
  4110. // 等值条件先行(表头下拉),减少后续日期解析量
  4111. $eqFilters = [];
  4112. $otherFilters = [];
  4113. foreach ($filterArr as $fk => $fv) {
  4114. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4115. continue;
  4116. }
  4117. if (is_array($fv)) {
  4118. continue;
  4119. }
  4120. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4121. continue;
  4122. }
  4123. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4124. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4125. $field = $stripAlias($fk);
  4126. if ($sym === '=' || $sym === '') {
  4127. $eqFilters[$field] = trim((string)$fv);
  4128. } else {
  4129. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4130. }
  4131. }
  4132. $ymTarget = '';
  4133. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4134. $ymTarget = $ymM[1];
  4135. }
  4136. $filtered = [];
  4137. foreach ($pool as $r) {
  4138. if (!is_array($r)) {
  4139. continue;
  4140. }
  4141. foreach ($eqFilters as $field => $fv) {
  4142. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4143. continue 2;
  4144. }
  4145. }
  4146. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4147. // 初选池不应含手工单;若混入则直接剔除
  4148. if ($isManual) {
  4149. continue;
  4150. }
  4151. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4152. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4153. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4154. continue;
  4155. }
  4156. if ($applyMonthRange) {
  4157. $mo = (int)$m[2];
  4158. if ($mo < 1 || $mo > 12) {
  4159. continue;
  4160. }
  4161. if ($ymTarget !== '') {
  4162. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4163. if ($ymRow !== $ymTarget) {
  4164. continue;
  4165. }
  4166. } else {
  4167. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4168. $rowMonthStart = $ymRow . '-01 00:00:00';
  4169. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4170. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4171. continue;
  4172. }
  4173. }
  4174. }
  4175. if ($search !== '') {
  4176. $hitSearch = false;
  4177. foreach ($searchColNames as $c) {
  4178. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4179. if ($cell !== '' && $strContains($cell, $search)) {
  4180. $hitSearch = true;
  4181. break;
  4182. }
  4183. }
  4184. if (!$hitSearch) {
  4185. continue;
  4186. }
  4187. }
  4188. foreach ($otherFilters as $item) {
  4189. $fv = $item['fv'];
  4190. $sym = $item['sym'];
  4191. $field = $item['field'];
  4192. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4193. $cellStr = trim((string)$cell);
  4194. switch ($sym) {
  4195. case '<>':
  4196. if ((string)$cell === (string)$fv) {
  4197. continue 3;
  4198. }
  4199. break;
  4200. case 'LIKE':
  4201. case 'NOT LIKE':
  4202. $needle = trim((string)$fv);
  4203. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4204. if ($sym === 'LIKE' && !$hit) {
  4205. continue 3;
  4206. }
  4207. if ($sym === 'NOT LIKE' && $hit) {
  4208. continue 3;
  4209. }
  4210. break;
  4211. case 'BETWEEN':
  4212. case 'RANGE':
  4213. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4214. if (count($parts) < 2) {
  4215. $parts = is_string($fv) ? explode(',', $fv) : [];
  4216. }
  4217. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4218. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4219. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4220. continue 3;
  4221. }
  4222. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4223. continue 3;
  4224. }
  4225. break;
  4226. case '>':
  4227. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4228. continue 3;
  4229. }
  4230. break;
  4231. case '>=':
  4232. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4233. continue 3;
  4234. }
  4235. break;
  4236. case '<':
  4237. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4238. continue 3;
  4239. }
  4240. break;
  4241. case '<=':
  4242. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4243. continue 3;
  4244. }
  4245. break;
  4246. default:
  4247. if ((string)$cell !== (string)$fv) {
  4248. continue 3;
  4249. }
  4250. break;
  4251. }
  4252. }
  4253. $filtered[] = $r;
  4254. }
  4255. return $filtered;
  4256. }
  4257. /**
  4258. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4259. */
  4260. public function snapshotToProcure()
  4261. {
  4262. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4263. $this->error(__('Invalid parameters'));
  4264. }
  4265. $row = json_decode($this->request->post('row_json', ''), true);
  4266. if (!is_array($row)) {
  4267. $this->error(__('Invalid parameters'));
  4268. }
  4269. try {
  4270. $ids = $this->extractScydgyRowId($row);
  4271. if (!$this->isValidScydgyRowId($ids)) {
  4272. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4273. }
  4274. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4275. $data = [
  4276. 'scydgy_id' => $ids,
  4277. 'CCYDH' => $row['CCYDH'] ?? null,
  4278. 'CYJMC' => $row['CYJMC'] ?? null,
  4279. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4280. 'CDXMC' => $row['CDXMC'] ?? null,
  4281. 'CGYBH' => $row['CGYBH'] ?? null,
  4282. 'CGYMC' => $row['CGYMC'] ?? null,
  4283. 'CDW' => $row['CDW'] ?? null,
  4284. 'czlyq' => $row['czlyq'] ?? null,
  4285. 'NGZL' => $row['NGZL'] ?? null,
  4286. 'CDF' => $row['CDF'] ?? null,
  4287. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4288. 'MBZ' => $row['MBZ'] ?? null,
  4289. 'bwjg' => $row['bwjg'] ?? null,
  4290. 'iStatus' => $row['iStatus'] ?? null,
  4291. 'dStamp' => $row['dStamp'] ?? null,
  4292. 'dputrecord' => $row['dputrecord'] ?? null,
  4293. 'cywyxm' => $row['cywyxm'] ?? null,
  4294. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4295. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4296. ];
  4297. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4298. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4299. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4300. $this->success('操作成功');
  4301. return;
  4302. }
  4303. if ($exists) {
  4304. $upd = $data;
  4305. unset($upd['scydgy_id'], $upd['status']);
  4306. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4307. } else {
  4308. // 新增:不写 status(空/走库默认);仅写创建时间
  4309. $data['createtime'] = date('Y-m-d H:i:s');
  4310. Db::table('purchase_order')->insert($data);
  4311. }
  4312. } catch (\Throwable $e) {
  4313. $this->error($e->getMessage());
  4314. }
  4315. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4316. $this->success('操作成功');
  4317. }
  4318. /**
  4319. * 未发列表
  4320. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4321. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4322. */
  4323. public function completeDirectly()
  4324. {
  4325. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4326. $this->error(__('参数错误'));
  4327. }
  4328. if (!$this->procuremenCanComplete()) {
  4329. $this->error(__('You have no permission'));
  4330. }
  4331. $row = json_decode($this->request->post('row_json', ''), true);
  4332. if (!is_array($row)) {
  4333. $this->error(__('Invalid parameters'));
  4334. }
  4335. $finishRaw = $this->request->post('finish', '1');
  4336. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4337. $poIdLog = null;
  4338. try {
  4339. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4340. $ids = $this->extractScydgyRowId($row);
  4341. if (!$this->isValidScydgyRowId($ids)) {
  4342. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4343. }
  4344. if ($asComplete) {
  4345. $this->assertPickRowCanComplete($ids, $row);
  4346. }
  4347. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4348. $data = [
  4349. 'scydgy_id' => $ids,
  4350. 'CCYDH' => $row['CCYDH'] ?? null,
  4351. 'CYJMC' => $row['CYJMC'] ?? null,
  4352. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4353. 'CDXMC' => $row['CDXMC'] ?? null,
  4354. 'CGYBH' => $row['CGYBH'] ?? null,
  4355. 'CGYMC' => $row['CGYMC'] ?? null,
  4356. 'CDW' => $row['CDW'] ?? null,
  4357. 'czlyq' => $row['czlyq'] ?? null,
  4358. 'NGZL' => $row['NGZL'] ?? null,
  4359. 'CDF' => $row['CDF'] ?? null,
  4360. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4361. 'MBZ' => $row['MBZ'] ?? null,
  4362. 'bwjg' => $row['bwjg'] ?? null,
  4363. 'iStatus' => $row['iStatus'] ?? null,
  4364. 'dStamp' => $row['dStamp'] ?? null,
  4365. 'dputrecord' => $row['dputrecord'] ?? null,
  4366. 'cywyxm' => $row['cywyxm'] ?? null,
  4367. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4368. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4369. ];
  4370. if ($asComplete) {
  4371. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4372. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4373. }
  4374. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4375. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4376. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4377. $this->success('操作成功');
  4378. return;
  4379. }
  4380. if ($exists) {
  4381. $upd = $data;
  4382. unset($upd['scydgy_id']);
  4383. if (!$asComplete) {
  4384. unset($upd['status']);
  4385. }
  4386. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4387. } else {
  4388. // 新增:不写 status;完结时 $data 已含 status=1
  4389. $data['createtime'] = date('Y-m-d H:i:s');
  4390. Db::table('purchase_order')->insert($data);
  4391. }
  4392. } catch (\Throwable $e) {
  4393. $this->error($e->getMessage());
  4394. }
  4395. try {
  4396. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4397. if (is_array($rpo)) {
  4398. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4399. $poIdLog = $tid > 0 ? $tid : null;
  4400. }
  4401. } catch (\Throwable $e) {
  4402. $poIdLog = null;
  4403. }
  4404. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4405. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4406. if ($asComplete) {
  4407. $this->addOrderLog(
  4408. $ids,
  4409. 'mark_complete',
  4410. '点击「完结」,已标记为已完结',
  4411. $poIdLog
  4412. );
  4413. try {
  4414. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4415. if ($pdfPublicPath === '') {
  4416. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4417. }
  4418. } catch (\Throwable $e) {
  4419. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4420. }
  4421. } else {
  4422. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4423. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4424. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4425. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4426. $this->addOrderLog(
  4427. $ids,
  4428. 'save_qty_price',
  4429. '保存本次数量、最高限价:' . $detail,
  4430. $poIdLog
  4431. );
  4432. }
  4433. $this->pickHiddenScydgySetCache = null;
  4434. $this->success("操作成功");
  4435. }
  4436. /**
  4437. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4438. *
  4439. * @param array<int, array> $rows 引用传递当前页行
  4440. */
  4441. protected function mergePurchaseOrder(array &$rows)
  4442. {
  4443. if ($rows === []) {
  4444. return;
  4445. }
  4446. $ids = [];
  4447. foreach ($rows as $rw) {
  4448. if (!is_array($rw)) {
  4449. continue;
  4450. }
  4451. $id = (int)($rw['ID'] ?? 0);
  4452. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4453. if ($this->isValidScydgyRowId($id)) {
  4454. $ids[$id] = true;
  4455. }
  4456. }
  4457. $idList = array_keys($ids);
  4458. if ($idList === []) {
  4459. return;
  4460. }
  4461. try {
  4462. $list = Db::table('purchase_order')
  4463. ->where('scydgy_id', 'in', $idList)
  4464. ->field('scydgy_id,This_quantity,ceilingPrice')
  4465. ->select();
  4466. } catch (\Throwable $e) {
  4467. return;
  4468. }
  4469. if (!is_array($list)) {
  4470. return;
  4471. }
  4472. $byId = [];
  4473. foreach ($list as $dbRow) {
  4474. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4475. continue;
  4476. }
  4477. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4478. }
  4479. foreach ($rows as &$rw) {
  4480. if (!is_array($rw)) {
  4481. continue;
  4482. }
  4483. $sid = (int)($rw['ID'] ?? 0);
  4484. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4485. continue;
  4486. }
  4487. $db = $byId[$sid];
  4488. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4489. if (array_key_exists('This_quantity', $db)) {
  4490. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4491. }
  4492. if (array_key_exists('ceilingPrice', $db)) {
  4493. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4494. } elseif (array_key_exists('ceiling_price', $db)) {
  4495. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4496. }
  4497. }
  4498. unset($rw);
  4499. }
  4500. /**
  4501. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4502. */
  4503. public function purchaseConfirmPick()
  4504. {
  4505. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4506. $this->error(__('Invalid parameters'));
  4507. }
  4508. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4509. $this->error(__('You have no permission'));
  4510. }
  4511. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4512. if ($batchRaw !== '') {
  4513. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4514. return;
  4515. }
  4516. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4517. $sid = (int)$scydgyId;
  4518. if (!$this->isValidScydgyRowId($sid)) {
  4519. $this->error('参数无效');
  4520. }
  4521. $parseIdList = function ($raw) {
  4522. if (is_array($raw)) {
  4523. $arr = $raw;
  4524. } else {
  4525. $decoded = json_decode((string)$raw, true);
  4526. $arr = is_array($decoded) ? $decoded : [];
  4527. }
  4528. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4529. };
  4530. $selectedRaw = $this->request->post('selected_ids', null);
  4531. if ($selectedRaw === null || $selectedRaw === '') {
  4532. $legacy = (int)$this->request->post('selected_id', 0);
  4533. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4534. } else {
  4535. $selectedIds = $parseIdList($selectedRaw);
  4536. }
  4537. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4538. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4539. try {
  4540. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4541. } catch (\InvalidArgumentException $e) {
  4542. $this->error($e->getMessage());
  4543. } catch (\Throwable $e) {
  4544. $this->error($e->getMessage());
  4545. }
  4546. $this->pickHiddenScydgySetCache = null;
  4547. $this->success('操作成功', '', $result);
  4548. }
  4549. /**
  4550. * 整单采购确认(多道工序一次提交)
  4551. */
  4552. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4553. {
  4554. $decoded = json_decode($batchRaw, true);
  4555. if (!is_array($decoded) || $decoded === []) {
  4556. $this->error('提交数据无效');
  4557. }
  4558. $picks = [];
  4559. foreach ($decoded as $item) {
  4560. if (!is_array($item)) {
  4561. continue;
  4562. }
  4563. $sid = (int)($item['scydgy_id'] ?? 0);
  4564. if (!$this->isValidScydgyRowId($sid)) {
  4565. continue;
  4566. }
  4567. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4568. if (!is_array($sel)) {
  4569. $sel = [(int)$sel];
  4570. }
  4571. $unsel = $item['unselected_ids'] ?? [];
  4572. if (!is_array($unsel)) {
  4573. $unsel = json_decode((string)$unsel, true);
  4574. $unsel = is_array($unsel) ? $unsel : [];
  4575. }
  4576. $picks[] = [
  4577. 'scydgy_id' => $sid,
  4578. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4579. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4580. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4581. ];
  4582. }
  4583. if ($picks === []) {
  4584. $this->error('提交数据无效');
  4585. }
  4586. Db::startTrans();
  4587. $results = [];
  4588. try {
  4589. foreach ($picks as $pick) {
  4590. $results[] = $this->runPurchaseConfirmPick(
  4591. (int)$pick['scydgy_id'],
  4592. $pick['selected_ids'],
  4593. $pick['unselected_ids'],
  4594. (int)$pick['purchase_order_id'],
  4595. false,
  4596. false
  4597. );
  4598. }
  4599. Db::commit();
  4600. } catch (\Throwable $e) {
  4601. Db::rollback();
  4602. $msg = $e->getMessage();
  4603. $this->error($msg !== '' ? $msg : '提交失败');
  4604. }
  4605. try {
  4606. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4607. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4608. } catch (\Throwable $e) {
  4609. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4610. }
  4611. $this->pickHiddenScydgySetCache = null;
  4612. $this->success('操作成功', '', ['batch' => $results]);
  4613. }
  4614. /**
  4615. * @return array<string, mixed>
  4616. */
  4617. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4618. {
  4619. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4620. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4621. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4622. $scydgyId = (string)$sid;
  4623. if ($selectedIds === []) {
  4624. throw new \InvalidArgumentException('请至少勾选一条明细');
  4625. }
  4626. $inter = array_intersect($selectedIds, $unselectedIds);
  4627. if ($inter !== []) {
  4628. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4629. }
  4630. $allIds = $this->purchaseOrderDetail($sid);
  4631. if ($allIds === []) {
  4632. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4633. }
  4634. foreach ($selectedIds as $id) {
  4635. if (!in_array($id, $allIds, true)) {
  4636. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4637. }
  4638. }
  4639. foreach ($unselectedIds as $id) {
  4640. if (!in_array($id, $allIds, true)) {
  4641. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4642. }
  4643. }
  4644. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4645. sort($union, SORT_NUMERIC);
  4646. $expect = $allIds;
  4647. sort($expect, SORT_NUMERIC);
  4648. if ($union !== $expect) {
  4649. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4650. }
  4651. if ($manageTransaction) {
  4652. Db::startTrans();
  4653. }
  4654. try {
  4655. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4656. $aff = 0;
  4657. try {
  4658. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4659. } catch (\Throwable $e) {
  4660. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4661. }
  4662. if ($aff < 1) {
  4663. throw new \Exception('更新选中状态失败');
  4664. }
  4665. $poPayload = [
  4666. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4667. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4668. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4669. ];
  4670. if ($purchaseOrderId > 0) {
  4671. $poAff = (int)Db::table('purchase_order')
  4672. ->where('id', $purchaseOrderId)
  4673. ->where('scydgy_id', $sid)
  4674. ->update($poPayload);
  4675. if ($poAff < 1) {
  4676. throw new \Exception('主表订单不存在或与工序行不匹配');
  4677. }
  4678. } else {
  4679. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4680. if ($poAff < 1) {
  4681. throw new \Exception('未找到');
  4682. }
  4683. }
  4684. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4685. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4686. if ($manageTransaction) {
  4687. Db::commit();
  4688. }
  4689. } catch (\Throwable $e) {
  4690. if ($manageTransaction) {
  4691. Db::rollback();
  4692. }
  4693. throw $e;
  4694. }
  4695. $poIdFinal = $purchaseOrderId;
  4696. if ($poIdFinal <= 0) {
  4697. try {
  4698. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4699. if (is_array($rpo)) {
  4700. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4701. }
  4702. } catch (\Throwable $e) {
  4703. $poIdFinal = 0;
  4704. }
  4705. }
  4706. $pickNames = [];
  4707. foreach ($selectedIds as $pid) {
  4708. $dr = $this->purchaseOrderDetai($sid, $pid);
  4709. $nm = trim((string)($dr['company_name'] ?? ''));
  4710. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4711. }
  4712. $this->addOrderLog(
  4713. $sid,
  4714. 'purchase_confirm',
  4715. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4716. $poIdFinal > 0 ? $poIdFinal : null
  4717. );
  4718. if ($sendNotifications) {
  4719. try {
  4720. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4721. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4722. 'scydgy_id' => $sid,
  4723. 'selected_ids' => $selectedIds,
  4724. 'unselected_ids' => $unselectedIds,
  4725. 'purchase_order_id' => $purchaseOrderId,
  4726. ]]);
  4727. } catch (\Throwable $e) {
  4728. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4729. }
  4730. }
  4731. Log::write(sprintf(
  4732. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4733. $scydgyId,
  4734. $purchaseOrderId,
  4735. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4736. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4737. ), 'notice');
  4738. $pdfPublicPath = '';
  4739. try {
  4740. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4741. } catch (\Throwable $e) {
  4742. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4743. }
  4744. return [
  4745. 'scydgy_id' => $scydgyId,
  4746. 'purchase_order_id' => $purchaseOrderId,
  4747. 'selected_ids' => $selectedIds,
  4748. 'unselected_ids' => $unselectedIds,
  4749. 'purchase_confirm_pdf' => $pdfPublicPath,
  4750. ];
  4751. }
  4752. /**
  4753. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4754. *
  4755. * @param int[]|string[] $scydgyIds
  4756. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4757. */
  4758. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4759. {
  4760. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4761. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4762. if ($scydgyIds === []) {
  4763. return $empty;
  4764. }
  4765. $pos = [];
  4766. try {
  4767. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4768. } catch (\Throwable $e) {
  4769. $rows = [];
  4770. }
  4771. if (is_array($rows)) {
  4772. foreach ($rows as $po) {
  4773. if (is_array($po)) {
  4774. $pos[] = $po;
  4775. }
  4776. }
  4777. }
  4778. if ($pos === []) {
  4779. return $empty;
  4780. }
  4781. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4782. return [
  4783. 'ccydh' => $ccydh,
  4784. 'pos' => $pos,
  4785. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4786. ];
  4787. }
  4788. /**
  4789. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4790. *
  4791. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4792. * @param array<int, array<string, mixed>> $picks
  4793. */
  4794. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4795. {
  4796. if ($picks === []) {
  4797. return;
  4798. }
  4799. $fallbackDetailId = 0;
  4800. $winners = [];
  4801. $losers = [];
  4802. foreach ($picks as $pick) {
  4803. if (!is_array($pick)) {
  4804. continue;
  4805. }
  4806. $sid = (int)($pick['scydgy_id'] ?? 0);
  4807. if (!$this->isValidScydgyRowId($sid)) {
  4808. continue;
  4809. }
  4810. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4811. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4812. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4813. $fallbackDetailId = (int)$selectedIds[0];
  4814. }
  4815. foreach ($selectedIds as $pid) {
  4816. $dr = $this->purchaseOrderDetai($sid, $pid);
  4817. if (!is_array($dr)) {
  4818. continue;
  4819. }
  4820. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4821. }
  4822. foreach ($unselectedIds as $pid) {
  4823. $dr = $this->purchaseOrderDetai($sid, $pid);
  4824. if (!is_array($dr)) {
  4825. continue;
  4826. }
  4827. $key = $this->notifySupplierDedupeKey($dr);
  4828. if (!isset($winners[$key])) {
  4829. $losers[$key] = $dr;
  4830. }
  4831. }
  4832. }
  4833. if ($winners === [] && $losers === []) {
  4834. return;
  4835. }
  4836. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4837. $sendSmsSafe = function ($phone, $content) {
  4838. $phone = trim((string)$phone);
  4839. if ($phone === '') {
  4840. return;
  4841. }
  4842. try {
  4843. $this->smsbao($phone, $content);
  4844. } catch (\Throwable $e) {
  4845. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4846. }
  4847. };
  4848. foreach ($winners as $dr) {
  4849. $cname = trim((string)($dr['company_name'] ?? ''));
  4850. $ph = trim((string)($dr['phone'] ?? ''));
  4851. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4852. 'company_name' => $cname,
  4853. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4854. 'phone' => $ph,
  4855. ]));
  4856. $sendSmsSafe($ph, $sms);
  4857. }
  4858. foreach ($losers as $dr) {
  4859. $cname = trim((string)($dr['company_name'] ?? ''));
  4860. $ph = trim((string)($dr['phone'] ?? ''));
  4861. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4862. 'company_name' => $cname,
  4863. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4864. 'phone' => $ph,
  4865. ]));
  4866. $sendSmsSafe($ph, $sms);
  4867. }
  4868. }
  4869. /**
  4870. * 短信去重键:优先手机号,否则公司名
  4871. */
  4872. protected function notifySupplierDedupeKey(array $detailRow): string
  4873. {
  4874. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4875. if ($ph !== '') {
  4876. return 'p:' . $ph;
  4877. }
  4878. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4879. return 'c:' . $cn;
  4880. }
  4881. /**
  4882. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4883. *
  4884. * @param int[] $detailIds
  4885. */
  4886. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4887. {
  4888. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4889. if ($detailIds === []) {
  4890. return;
  4891. }
  4892. $payload = ['status_name' => $statusName];
  4893. try {
  4894. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4895. } catch (\Throwable $e) {
  4896. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4897. }
  4898. }
  4899. /**
  4900. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4901. */
  4902. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4903. {
  4904. try {
  4905. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4906. } catch (\Throwable $e) {
  4907. return;
  4908. }
  4909. if (!is_array($rows)) {
  4910. return;
  4911. }
  4912. foreach ($rows as $dr) {
  4913. if (!is_array($dr)) {
  4914. continue;
  4915. }
  4916. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4917. if ($id <= 0) {
  4918. continue;
  4919. }
  4920. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4921. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4922. try {
  4923. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4924. } catch (\Throwable $e) {
  4925. }
  4926. }
  4927. }
  4928. /**
  4929. * @param array<string, mixed> $detailRow
  4930. */
  4931. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4932. {
  4933. $am = $detailRow['amount'] ?? null;
  4934. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4935. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4936. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4937. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4938. }
  4939. /**
  4940. * @return int[]
  4941. */
  4942. protected function purchaseOrderDetail(int $scydgyId): array
  4943. {
  4944. if (!$this->isValidScydgyRowId($scydgyId)) {
  4945. return [];
  4946. }
  4947. try {
  4948. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4949. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  4950. $list = $listQuery->select();
  4951. } catch (\Throwable $e) {
  4952. return [];
  4953. }
  4954. if (!is_array($list)) {
  4955. return [];
  4956. }
  4957. $ids = [];
  4958. foreach ($list as $r) {
  4959. if (!is_array($r)) {
  4960. continue;
  4961. }
  4962. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  4963. if ($pk > 0) {
  4964. $ids[] = $pk;
  4965. }
  4966. }
  4967. return array_values(array_unique($ids));
  4968. }
  4969. /**
  4970. * 获取当前登录用户信息 [id, 展示名]
  4971. */
  4972. protected function GetUseName(): array
  4973. {
  4974. $id = 0;
  4975. $name = '';
  4976. try {
  4977. if ($this->auth && $this->auth->isLogin()) {
  4978. $u = $this->auth->getUserInfo();
  4979. if (is_array($u)) {
  4980. $id = (int)($u['id'] ?? 0);
  4981. $name = trim((string)($u['nickname'] ?? ''));
  4982. if ($name === '') {
  4983. $name = trim((string)($u['username'] ?? ''));
  4984. }
  4985. }
  4986. }
  4987. } catch (\Throwable $e) {
  4988. }
  4989. if ($name === '') {
  4990. $name = '未知用户';
  4991. }
  4992. return [$id, $name];
  4993. }
  4994. /**
  4995. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  4996. */
  4997. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  4998. {
  4999. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5000. }
  5001. /**
  5002. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5003. *
  5004. * @param array<int, array<string, mixed>> $rows
  5005. */
  5006. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5007. {
  5008. $sidList = [];
  5009. foreach ($rows as $rw) {
  5010. if (!is_array($rw)) {
  5011. continue;
  5012. }
  5013. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5014. foreach ($rw['_order_merge_rows'] as $mr) {
  5015. $mid = (int)($mr['ID'] ?? 0);
  5016. if ($this->isValidScydgyRowId($mid)) {
  5017. $sidList[$mid] = true;
  5018. }
  5019. }
  5020. }
  5021. $id = (int)($rw['ID'] ?? 0);
  5022. if ($this->isValidScydgyRowId($id)) {
  5023. $sidList[$id] = true;
  5024. }
  5025. }
  5026. $sids = array_keys($sidList);
  5027. $issueBySid = [];
  5028. $confirmBySid = [];
  5029. $approveBySid = [];
  5030. if ($sids !== []) {
  5031. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5032. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5033. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5034. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5035. try {
  5036. $logs = Db::table('purchase_order_oper_log')
  5037. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5038. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5039. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5040. ->order('id', 'asc')
  5041. ->select();
  5042. } catch (\Throwable $e) {
  5043. $logs = [];
  5044. }
  5045. if (is_array($logs)) {
  5046. $issueSet = array_fill_keys($issueActs, true);
  5047. $confirmSet = array_fill_keys($confirmActs, true);
  5048. $approveSet = array_fill_keys($approveActs, true);
  5049. foreach ($logs as $lg) {
  5050. if (!is_array($lg)) {
  5051. continue;
  5052. }
  5053. $lg = ProcuremenOperLog::normalizeRow($lg);
  5054. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5055. if ($sid === 0) {
  5056. continue;
  5057. }
  5058. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5059. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5060. if ($t === '') {
  5061. continue;
  5062. }
  5063. if (isset($issueSet[$action])) {
  5064. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5065. $issueBySid[$sid] = $t;
  5066. }
  5067. }
  5068. if (isset($confirmSet[$action])) {
  5069. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5070. $confirmBySid[$sid] = $t;
  5071. }
  5072. }
  5073. if (isset($approveSet[$action])) {
  5074. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5075. $approveBySid[$sid] = $t;
  5076. }
  5077. }
  5078. }
  5079. }
  5080. }
  5081. foreach ($rows as &$rw) {
  5082. if (!is_array($rw)) {
  5083. continue;
  5084. }
  5085. $mergeSids = [];
  5086. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5087. foreach ($rw['_order_merge_rows'] as $mr) {
  5088. $mid = (int)($mr['ID'] ?? 0);
  5089. if ($this->isValidScydgyRowId($mid)) {
  5090. $mergeSids[] = $mid;
  5091. }
  5092. }
  5093. }
  5094. $rid = (int)($rw['ID'] ?? 0);
  5095. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5096. $mergeSids[] = $rid;
  5097. }
  5098. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5099. $issue = $pick;
  5100. $confirm = '';
  5101. $approve = '';
  5102. foreach ($mergeSids as $sid) {
  5103. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5104. $issue = $issueBySid[$sid];
  5105. }
  5106. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5107. $confirm = $confirmBySid[$sid];
  5108. }
  5109. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5110. $approve = $approveBySid[$sid];
  5111. }
  5112. }
  5113. if ($issue === '' && $pick !== '') {
  5114. $issue = $pick;
  5115. }
  5116. $rw['issue_time'] = $issue;
  5117. $rw['confirm_time'] = $confirm;
  5118. $rw['approve_time'] = $approve;
  5119. }
  5120. unset($rw);
  5121. }
  5122. /**
  5123. * 按主键取一条
  5124. */
  5125. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5126. {
  5127. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5128. return [];
  5129. }
  5130. try {
  5131. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5132. if (is_array($one)) {
  5133. return $one;
  5134. }
  5135. } catch (\Throwable $e) {
  5136. }
  5137. try {
  5138. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5139. if (is_array($one)) {
  5140. return $one;
  5141. }
  5142. } catch (\Throwable $e) {
  5143. }
  5144. return [];
  5145. }
  5146. /**
  5147. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5148. */
  5149. protected function formatProcuremenDetailTime($v): string
  5150. {
  5151. if ($v === null || $v === '') {
  5152. return '';
  5153. }
  5154. if (is_numeric($v) && (int)$v > 946684800) {
  5155. return date('Y-m-d H:i:s', (int)$v);
  5156. }
  5157. return ProcuremenTime::formatDisplayDateTime($v);
  5158. }
  5159. /**
  5160. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5161. */
  5162. protected function formatDeliveryYmd($v): string
  5163. {
  5164. if ($v === null || $v === '') {
  5165. return '';
  5166. }
  5167. $s = trim((string)$v);
  5168. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5169. return '';
  5170. }
  5171. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5172. return $m[1];
  5173. }
  5174. $ts = strtotime($s);
  5175. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5176. }
  5177. /**
  5178. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5179. */
  5180. protected function detailRowSupplierOperated(array $r): bool
  5181. {
  5182. $am = $r['amount'] ?? null;
  5183. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5184. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5185. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5186. return $okAmt || $okDel;
  5187. }
  5188. /**
  5189. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5190. */
  5191. protected function resolveDetailSupplierOperTime(array $r): string
  5192. {
  5193. if (!$this->detailRowSupplierOperated($r)) {
  5194. return '';
  5195. }
  5196. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5197. if ($t !== '') {
  5198. return $t;
  5199. }
  5200. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5201. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5202. continue;
  5203. }
  5204. $t = $this->formatProcuremenDetailTime($r[$col]);
  5205. if ($t !== '') {
  5206. return $t;
  5207. }
  5208. }
  5209. return '';
  5210. }
  5211. /**
  5212. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5213. */
  5214. protected function detailRowSupplierAccepted(array $r): bool
  5215. {
  5216. $am = $r['amount'] ?? null;
  5217. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5218. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5219. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5220. return $okAmt && $okDel;
  5221. }
  5222. /**
  5223. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5224. */
  5225. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5226. {
  5227. if ($detailCount > 0) {
  5228. return true;
  5229. }
  5230. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5231. return true;
  5232. }
  5233. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5234. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5235. return true;
  5236. }
  5237. return false;
  5238. }
  5239. /**
  5240. * 下发时间:优先 pick_time,其次首条下发明细时间
  5241. */
  5242. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5243. {
  5244. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5245. if ($issueTime !== '') {
  5246. return $issueTime;
  5247. }
  5248. foreach ($details as $dr) {
  5249. if (!is_array($dr)) {
  5250. continue;
  5251. }
  5252. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5253. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5254. $issueTime = $t;
  5255. }
  5256. }
  5257. if ($issueTime !== '') {
  5258. return $issueTime;
  5259. }
  5260. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5261. }
  5262. /**
  5263. * 直接点「完结」时间:优先操作记录 mark_complete
  5264. */
  5265. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5266. {
  5267. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5268. }
  5269. /**
  5270. * 操作记录时间(取指定 action 最近一条)
  5271. *
  5272. * @param string|array<int, string> $actions
  5273. */
  5274. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5275. {
  5276. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5277. }
  5278. /**
  5279. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5280. *
  5281. * @param array $main purchase_order 一行
  5282. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5283. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5284. */
  5285. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5286. {
  5287. $issueCnt = count($details);
  5288. $acceptCnt = 0;
  5289. $pickedName = '';
  5290. $pickedTime = '';
  5291. foreach ($details as $dr) {
  5292. if (!is_array($dr)) {
  5293. continue;
  5294. }
  5295. if ($this->detailRowSupplierAccepted($dr)) {
  5296. $acceptCnt++;
  5297. }
  5298. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5299. if ($pickedName === '') {
  5300. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5301. }
  5302. if ($pickedTime === '') {
  5303. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5304. if ($pickedTime === '') {
  5305. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5306. }
  5307. }
  5308. }
  5309. }
  5310. $hasMain = $main !== [];
  5311. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5312. if ($poTime === '') {
  5313. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5314. }
  5315. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5316. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5317. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5318. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5319. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5320. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5321. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5322. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5323. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5324. $inboundResult = '';
  5325. if ($scydgyId > 0) {
  5326. try {
  5327. $inRow = Db::table('purchase_order_inbound_score')
  5328. ->where('scydgy_id', $scydgyId)
  5329. ->field('result,updatetime,createtime')
  5330. ->find();
  5331. } catch (\Throwable $e) {
  5332. $inRow = null;
  5333. }
  5334. if (is_array($inRow) && $inRow !== []) {
  5335. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5336. if ($inboundScoreTime === '') {
  5337. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5338. }
  5339. }
  5340. }
  5341. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5342. $supplierTime = '';
  5343. if ($acceptCnt > 0) {
  5344. foreach ($details as $dr) {
  5345. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5346. continue;
  5347. }
  5348. $t = $this->resolveDetailSupplierOperTime($dr);
  5349. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5350. $supplierTime = $t;
  5351. }
  5352. }
  5353. }
  5354. $directComplete = ($mainCompleted && !$issued);
  5355. $doneTime = '';
  5356. if ($mainCompleted) {
  5357. if ($directComplete) {
  5358. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5359. }
  5360. if ($doneTime === '' && $inboundScoreTime !== '') {
  5361. $doneTime = $inboundScoreTime;
  5362. }
  5363. if ($doneTime === '') {
  5364. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5365. }
  5366. if ($doneTime === '') {
  5367. foreach ($details as $dr) {
  5368. if (!is_array($dr)) {
  5369. continue;
  5370. }
  5371. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5372. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5373. $doneTime = $t;
  5374. }
  5375. }
  5376. }
  5377. if ($doneTime === '') {
  5378. $doneTime = $poTime;
  5379. }
  5380. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5381. if ($doneTime === '' && $confirmApproveTime !== '') {
  5382. $doneTime = $confirmApproveTime;
  5383. }
  5384. }
  5385. if ($directComplete) {
  5386. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5387. $step1Done = $hasMain;
  5388. $step2Done = false;
  5389. $step3Done = false;
  5390. $step4Done = false;
  5391. $step5Done = false;
  5392. $stepInboundDone = $inboundScored;
  5393. $step6Done = $mainCompleted && $inboundScored;
  5394. } else {
  5395. $step1Done = $issued;
  5396. $step2Done = $issued;
  5397. $step3Done = $acceptCnt > 0;
  5398. $step4Done = $wflowPendingApproval;
  5399. if (!$step4Done) {
  5400. foreach ($details as $dr) {
  5401. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5402. $step4Done = true;
  5403. break;
  5404. }
  5405. }
  5406. }
  5407. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5408. $stepInboundDone = $inboundScored;
  5409. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5410. $step6Done = $mainCompleted && $inboundScored;
  5411. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5412. if ($mainCompleted && $issued) {
  5413. $step3Done = true;
  5414. $step4Done = true;
  5415. $step5Done = true;
  5416. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5417. if ($supplierTime === '') {
  5418. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5419. if ($fillT !== '') {
  5420. $supplierTime = $fillT;
  5421. }
  5422. }
  5423. if ($pickedTime === '') {
  5424. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5425. if ($fillT !== '') {
  5426. $pickedTime = $fillT;
  5427. }
  5428. }
  5429. if ($auditSelectTime === '') {
  5430. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5431. if ($fillT !== '') {
  5432. $auditSelectTime = $fillT;
  5433. }
  5434. }
  5435. if ($confirmApproveTime === '') {
  5436. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5437. if ($fillT !== '') {
  5438. $confirmApproveTime = $fillT;
  5439. }
  5440. }
  5441. }
  5442. }
  5443. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5444. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5445. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5446. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5447. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5448. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5449. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5450. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5451. $deadlineLines = [];
  5452. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5453. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5454. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5455. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5456. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5457. }
  5458. }
  5459. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5460. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5461. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5462. if ($deliveryDisp === '') {
  5463. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5464. }
  5465. if ($deliveryDisp !== '') {
  5466. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5467. }
  5468. }
  5469. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5470. $deadlineText = implode("\n", $deadlineLines);
  5471. $prefixOperTime = static function (string $t): string {
  5472. $t = trim($t);
  5473. if ($t === '' || $t === '—') {
  5474. return $t;
  5475. }
  5476. if (strpos($t, '操作时间') === 0) {
  5477. return $t;
  5478. }
  5479. return '操作时间:' . $t;
  5480. };
  5481. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5482. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5483. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5484. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5485. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5486. $steps = [
  5487. [
  5488. 'title' => '未发',
  5489. 'subtitle' => '',
  5490. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5491. 'done' => $step1Done,
  5492. ],
  5493. [
  5494. 'title' => '下发',
  5495. 'subtitle' => $deadlineText,
  5496. 'time' => $prefixOperTime($step2Time),
  5497. 'done' => $step2Done,
  5498. ],
  5499. [
  5500. 'title' => '供应商接单',
  5501. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5502. 'time' => '',
  5503. 'done' => $step3Done,
  5504. ],
  5505. [
  5506. 'title' => '待确认',
  5507. 'subtitle' => $step4Done
  5508. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5509. : ($issued ? '待选供应商' : ''),
  5510. 'time' => $prefixOperTime($step4Time),
  5511. 'done' => $step4Done,
  5512. ],
  5513. [
  5514. 'title' => '待审批',
  5515. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5516. 'time' => $prefixOperTime($step5Time),
  5517. 'done' => $step5Done,
  5518. ],
  5519. [
  5520. 'title' => '是否合格',
  5521. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5522. 'time' => $prefixOperTime($stepInboundTime),
  5523. 'done' => $stepInboundDone,
  5524. ],
  5525. [
  5526. 'title' => '已完结',
  5527. 'subtitle' => '',
  5528. 'time' => $prefixOperTime($step6Time),
  5529. 'done' => $step6Done,
  5530. ],
  5531. ];
  5532. $currentIdx = count($steps) - 1;
  5533. if ($directComplete) {
  5534. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5535. if (!$step6Done) {
  5536. foreach ($steps as $i => $s) {
  5537. if (($s['title'] ?? '') === '是否合格') {
  5538. $currentIdx = $i;
  5539. break;
  5540. }
  5541. }
  5542. }
  5543. } else {
  5544. foreach ($steps as $i => $s) {
  5545. if (!$s['done']) {
  5546. $currentIdx = $i;
  5547. break;
  5548. }
  5549. }
  5550. }
  5551. $nSteps = count($steps);
  5552. foreach ($steps as $idx => &$s) {
  5553. $s['current'] = ($idx === $currentIdx);
  5554. if ($idx === 0) {
  5555. $s['pdf_left_bg'] = '';
  5556. } else {
  5557. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5558. }
  5559. if ($idx >= $nSteps - 1) {
  5560. $s['pdf_right_bg'] = '';
  5561. } else {
  5562. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5563. }
  5564. }
  5565. unset($s);
  5566. $labelMap = [
  5567. 'CCYDH' => '订单号',
  5568. 'CYJMC' => '印件名称',
  5569. 'CCLBMMC' => '承揽部门',
  5570. 'CGYMC' => '工序名称',
  5571. 'CDW' => '单位',
  5572. 'czlyq' => '类型',
  5573. 'NGZL' => '工作量',
  5574. 'CDF' => '单价',
  5575. 'cGzzxMc' => '工作中心',
  5576. 'MBZ' => '备注',
  5577. 'This_quantity' => '本次数量',
  5578. 'ceilingPrice' => '最高限价',
  5579. ];
  5580. $orderSummary = [];
  5581. foreach ($labelMap as $key => $lab) {
  5582. if (!array_key_exists($key, $main)) {
  5583. continue;
  5584. }
  5585. $val = $main[$key];
  5586. if ($val === null) {
  5587. $val = '';
  5588. } elseif (!is_scalar($val)) {
  5589. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5590. } else {
  5591. $val = (string)$val;
  5592. }
  5593. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5594. }
  5595. $orderSummary[] = [
  5596. 'label' => '是否合格',
  5597. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5598. ];
  5599. $orderSummaryGrid = [];
  5600. $n = count($orderSummary);
  5601. for ($i = 0; $i < $n; $i += 2) {
  5602. $left = $orderSummary[$i];
  5603. $hasRight = ($i + 1) < $n;
  5604. $orderSummaryGrid[] = [
  5605. 'l1' => $left['label'],
  5606. 'v1' => $left['value'],
  5607. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5608. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5609. ];
  5610. }
  5611. return [
  5612. 'steps' => $steps,
  5613. 'orderSummary' => $orderSummary,
  5614. 'orderSummaryGrid' => $orderSummaryGrid,
  5615. 'inbound_result' => $inboundResult,
  5616. 'inbound_score_time'=> $inboundScoreTime,
  5617. 'detailRows' => $details,
  5618. ];
  5619. }
  5620. /**
  5621. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5622. *
  5623. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5624. */
  5625. protected function prepareProcuremenDetailsView(string $ids): array
  5626. {
  5627. $main = [];
  5628. try {
  5629. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5630. $main = is_array($one) ? $one : [];
  5631. } catch (\Throwable $e) {
  5632. $main = [];
  5633. }
  5634. $details = [];
  5635. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5636. if ($mergeRows === []) {
  5637. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5638. if ($mergeRows === [] && $main !== []) {
  5639. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5640. }
  5641. }
  5642. $detailSidList = [];
  5643. $anchorSid = (int)$ids;
  5644. if ($anchorSid !== 0) {
  5645. $detailSidList[$anchorSid] = true;
  5646. }
  5647. foreach ($mergeRows as $mr) {
  5648. if (!is_array($mr)) {
  5649. continue;
  5650. }
  5651. $sid = $this->extractScydgyRowId($mr);
  5652. if ($sid !== 0) {
  5653. $detailSidList[$sid] = true;
  5654. }
  5655. }
  5656. try {
  5657. if ($detailSidList !== []) {
  5658. $details = Db::table('purchase_order_detail')
  5659. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5660. ->order('id', 'asc')
  5661. ->select();
  5662. }
  5663. } catch (\Throwable $e) {
  5664. $details = [];
  5665. }
  5666. if (!is_array($details)) {
  5667. $details = [];
  5668. }
  5669. foreach ($details as &$r) {
  5670. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5671. $r['id'] = $r['ID'];
  5672. }
  5673. if (isset($r['createtime'])) {
  5674. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5675. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5676. } else {
  5677. $r['createtime_text'] = (string)$r['createtime'];
  5678. }
  5679. } else {
  5680. $r['createtime_text'] = '';
  5681. }
  5682. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5683. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5684. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5685. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5686. if (is_array($r)) {
  5687. $r = $this->maskSupplierContactFields($r);
  5688. }
  5689. }
  5690. unset($r);
  5691. $activeDetails = [];
  5692. foreach ($details as $r) {
  5693. if (is_array($r) && empty($r['is_void'])) {
  5694. $activeDetails[] = $r;
  5695. }
  5696. }
  5697. $operLogs = [];
  5698. try {
  5699. $operSidList = array_keys($detailSidList);
  5700. if ($operSidList === [] && (int)$ids !== 0) {
  5701. $operSidList = [(int)$ids];
  5702. }
  5703. if ($operSidList !== []) {
  5704. $operLogs = Db::table('purchase_order_oper_log')
  5705. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5706. ->order('id', 'asc')
  5707. ->select();
  5708. }
  5709. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5710. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5711. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5712. if ($poId > 0) {
  5713. $operLogs = Db::table('purchase_order_oper_log')
  5714. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5715. ->order('id', 'asc')
  5716. ->select();
  5717. }
  5718. }
  5719. } catch (\Throwable $e) {
  5720. $operLogs = [];
  5721. }
  5722. if (!is_array($operLogs)) {
  5723. $operLogs = [];
  5724. }
  5725. $operLogsRaw = $operLogs;
  5726. $processNameBySid = [];
  5727. foreach ($mergeRows as $mr) {
  5728. if (!is_array($mr)) {
  5729. continue;
  5730. }
  5731. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5732. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5733. if ($psid !== 0 && $gymc !== '') {
  5734. $processNameBySid[$psid] = $gymc;
  5735. }
  5736. }
  5737. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5738. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5739. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5740. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5741. if ($ccydh === '') {
  5742. foreach ($details as $r) {
  5743. if (!is_array($r)) {
  5744. continue;
  5745. }
  5746. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5747. if ($ccydh !== '') {
  5748. break;
  5749. }
  5750. }
  5751. }
  5752. $this->view->assign('ccydh', $ccydh);
  5753. $this->view->assign('steps', $bundle['steps']);
  5754. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5755. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5756. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5757. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5758. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5759. $this->view->assign('processCount', count($mergeRows));
  5760. $this->view->assign('detailRows', $details);
  5761. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5762. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5763. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5764. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5765. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5766. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5767. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5768. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5769. $this->view->assign('operLogs', $operLogs);
  5770. $sg = $quoteView['supplier_groups'] ?? [];
  5771. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5772. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5773. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5774. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5775. return [
  5776. 'ok' => $main !== [] || $details !== [],
  5777. 'ccydh' => $ccydh,
  5778. ];
  5779. }
  5780. /**
  5781. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5782. */
  5783. public function details()
  5784. {
  5785. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5786. if (is_array($ids)) {
  5787. $ids = isset($ids[0]) ? $ids[0] : '';
  5788. }
  5789. $ids = trim((string)$ids);
  5790. if ($ids === '') {
  5791. $this->error(__('Invalid parameters'));
  5792. }
  5793. $this->assertManualOrderDetailsViewable((int)$ids);
  5794. $this->prepareProcuremenDetailsView($ids);
  5795. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5796. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5797. $this->view->engine->layout(false);
  5798. try {
  5799. return $this->view->fetch('procuremen/details_dialog_shell');
  5800. } finally {
  5801. if ($restoreLayout) {
  5802. $this->view->engine->layout($restoreLayout);
  5803. }
  5804. }
  5805. }
  5806. /**
  5807. * 解析合并审核工序行(订单号须一致,且均未协助)
  5808. *
  5809. * @return array<int, array<string, mixed>>
  5810. */
  5811. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5812. {
  5813. $primary = json_decode($rowJson, true);
  5814. if (!is_array($primary)) {
  5815. $this->error(__('Invalid parameters'));
  5816. }
  5817. $merge = json_decode($mergeRowsJson, true);
  5818. if (!is_array($merge) || $merge === []) {
  5819. $merge = [$primary];
  5820. }
  5821. $seen = [];
  5822. $out = [];
  5823. foreach ($merge as $r) {
  5824. if (!is_array($r)) {
  5825. continue;
  5826. }
  5827. $id = $this->extractScydgyRowId($r);
  5828. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5829. continue;
  5830. }
  5831. $seen[$id] = true;
  5832. $out[] = $r;
  5833. }
  5834. if ($out === []) {
  5835. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5836. }
  5837. $ccydh = null;
  5838. foreach ($out as $r) {
  5839. $dh = trim((string)($r['CCYDH'] ?? ''));
  5840. if ($ccydh === null) {
  5841. $ccydh = $dh;
  5842. } elseif ($dh !== $ccydh) {
  5843. $this->error('合并审核要求所选行的订单号一致');
  5844. }
  5845. }
  5846. $ids = [];
  5847. foreach ($out as $r) {
  5848. $id = $this->extractScydgyRowId($r);
  5849. if ($this->isValidScydgyRowId($id)) {
  5850. $ids[$id] = true;
  5851. }
  5852. }
  5853. $poBySid = [];
  5854. $detCntBySid = [];
  5855. if ($ids !== []) {
  5856. $idList = array_keys($ids);
  5857. try {
  5858. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5859. if (is_array($poList)) {
  5860. foreach ($poList as $po) {
  5861. if (!is_array($po)) {
  5862. continue;
  5863. }
  5864. $sid = (int)($po['scydgy_id'] ?? 0);
  5865. if ($this->isValidScydgyRowId($sid)) {
  5866. $poBySid[$sid] = $po;
  5867. }
  5868. }
  5869. }
  5870. } catch (\Throwable $e) {
  5871. }
  5872. try {
  5873. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5874. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5875. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5876. if (is_array($detRows)) {
  5877. foreach ($detRows as $dr) {
  5878. if (!is_array($dr)) {
  5879. continue;
  5880. }
  5881. $sid = (int)($dr['scydgy_id'] ?? 0);
  5882. if ($this->isValidScydgyRowId($sid)) {
  5883. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5884. }
  5885. }
  5886. }
  5887. } catch (\Throwable $e) {
  5888. }
  5889. }
  5890. foreach ($out as $r) {
  5891. $id = $this->extractScydgyRowId($r);
  5892. if (!$this->isValidScydgyRowId($id)) {
  5893. continue;
  5894. }
  5895. $po = $poBySid[$id] ?? null;
  5896. if (!is_array($po)) {
  5897. continue;
  5898. }
  5899. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5900. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5901. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5902. }
  5903. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5904. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5905. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5906. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5907. }
  5908. }
  5909. return $out;
  5910. }
  5911. /**
  5912. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5913. */
  5914. protected function maskSupplierContactFields(array $item): array
  5915. {
  5916. if (array_key_exists('email', $item)) {
  5917. $item['email'] = mask_email((string)$item['email']);
  5918. }
  5919. if (array_key_exists('phone', $item)) {
  5920. $item['phone'] = mask_phone((string)$item['phone']);
  5921. }
  5922. return $item;
  5923. }
  5924. /**
  5925. * @param array<int, array<string, mixed>> $list
  5926. * @return array<int, array<string, mixed>>
  5927. */
  5928. protected function maskSupplierContactList(array $list): array
  5929. {
  5930. $out = [];
  5931. foreach ($list as $item) {
  5932. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5933. }
  5934. return $out;
  5935. }
  5936. /**
  5937. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5938. *
  5939. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5940. * @return array<string, string>|null
  5941. */
  5942. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  5943. {
  5944. if (!is_array($row)) {
  5945. return null;
  5946. }
  5947. $norm = [];
  5948. foreach ($row as $k => $v) {
  5949. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  5950. }
  5951. $row = $norm;
  5952. $st = $row['status'] ?? '';
  5953. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  5954. return null;
  5955. }
  5956. $companyName = '';
  5957. foreach (['company_name', 'name'] as $nk) {
  5958. if (!empty($row[$nk])) {
  5959. $companyName = trim((string)$row[$nk]);
  5960. break;
  5961. }
  5962. }
  5963. if ($companyName === '') {
  5964. return null;
  5965. }
  5966. $username = '';
  5967. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  5968. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  5969. $username = trim((string)$row[$uk]);
  5970. break;
  5971. }
  5972. }
  5973. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  5974. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  5975. if ($phone === '' && isset($row['account'])) {
  5976. $phone = trim((string)$row['account']);
  5977. }
  5978. if ($phone === '' && isset($row['mobile'])) {
  5979. $phone = trim((string)$row['mobile']);
  5980. }
  5981. if ($requireContactChannels && $email === '' && $phone === '') {
  5982. return null;
  5983. }
  5984. $category = '';
  5985. foreach (['company_type', 'category', 'type_name'] as $ck) {
  5986. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  5987. $category = trim((string)$row[$ck]);
  5988. break;
  5989. }
  5990. }
  5991. return [
  5992. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  5993. 'name' => $companyName,
  5994. 'company_name' => $companyName,
  5995. 'username' => $username,
  5996. 'email' => $email,
  5997. 'phone' => $phone,
  5998. 'category' => $category,
  5999. 'company_type' => $category,
  6000. ];
  6001. }
  6002. /**
  6003. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6004. */
  6005. protected function resolveCustomerContactById(string $id): ?array
  6006. {
  6007. $id = trim($id);
  6008. if ($id === '' || !ctype_digit($id)) {
  6009. return null;
  6010. }
  6011. try {
  6012. $row = Db::table('customer')->where('id', (int)$id)->find();
  6013. } catch (\Throwable $e) {
  6014. return null;
  6015. }
  6016. return $this->buildCustomerContactPayloadFromRow($row);
  6017. }
  6018. /**
  6019. * 按供应商名称解析联系信息(兼容旧提交数据)
  6020. *
  6021. * @param bool $requireContactChannels true 时须有邮箱或手机
  6022. */
  6023. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6024. {
  6025. $name = trim($name);
  6026. if ($name === '') {
  6027. return null;
  6028. }
  6029. try {
  6030. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6031. $row = Db::table('customer')
  6032. ->where('company_name', $name)
  6033. ->order('id', 'desc')
  6034. ->find();
  6035. } catch (\Throwable $e) {
  6036. return null;
  6037. }
  6038. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6039. }
  6040. /**
  6041. * 规范化下发/确认时勾选的供应商
  6042. *
  6043. * @param array<int, mixed> $companies
  6044. * @return array<int, array<string, string>>
  6045. */
  6046. protected function normalizePickCompanies(array $companies): array
  6047. {
  6048. $out = [];
  6049. foreach ($companies as $c) {
  6050. if (!is_array($c)) {
  6051. continue;
  6052. }
  6053. $resolved = null;
  6054. $cid = trim((string)($c['id'] ?? ''));
  6055. if ($cid !== '') {
  6056. $resolved = $this->resolveCustomerContactById($cid);
  6057. }
  6058. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6059. if ($resolved === null && $name !== '') {
  6060. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6061. }
  6062. if ($resolved === null) {
  6063. continue;
  6064. }
  6065. $out[] = $resolved;
  6066. }
  6067. return $out;
  6068. }
  6069. /**
  6070. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6071. *
  6072. * @param array<int, array<string, mixed>> $pool
  6073. * @return array<int, array<string, mixed>>
  6074. */
  6075. protected function collapseProcuremenPoolByOrder(array $pool): array
  6076. {
  6077. if ($pool === []) {
  6078. return [];
  6079. }
  6080. $groups = [];
  6081. foreach ($pool as $row) {
  6082. if (!is_array($row)) {
  6083. continue;
  6084. }
  6085. $dh = trim((string)($row['CCYDH'] ?? ''));
  6086. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6087. if (!isset($groups[$key])) {
  6088. $groups[$key] = [];
  6089. }
  6090. $groups[$key][] = $row;
  6091. }
  6092. $out = [];
  6093. foreach ($groups as $ccydh => $rows) {
  6094. if ($rows === []) {
  6095. continue;
  6096. }
  6097. usort($rows, function ($a, $b) {
  6098. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6099. });
  6100. $head = $rows[0];
  6101. $gymcList = [];
  6102. foreach ($rows as $r) {
  6103. $g = trim((string)($r['CGYMC'] ?? ''));
  6104. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6105. $gymcList[] = $g;
  6106. }
  6107. }
  6108. $merged = $head;
  6109. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6110. $merged['process_count'] = count($rows);
  6111. $merged['_order_merge_rows'] = $rows;
  6112. $qtyList = [];
  6113. $priceList = [];
  6114. foreach ($rows as $r) {
  6115. if (!is_array($r)) {
  6116. continue;
  6117. }
  6118. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6119. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6120. }
  6121. if (count($rows) > 1) {
  6122. $merged['CGYMC'] = implode('、', $gymcList);
  6123. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6124. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6125. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6126. } else {
  6127. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6128. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6129. }
  6130. // 已选供应商:取合并行中首个非空 pick_company_name
  6131. $pickedName = '';
  6132. foreach ($rows as $r) {
  6133. if (!is_array($r)) {
  6134. continue;
  6135. }
  6136. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6137. if ($pn !== '') {
  6138. $pickedName = $pn;
  6139. break;
  6140. }
  6141. }
  6142. if ($pickedName !== '') {
  6143. $merged['pick_company_name'] = $pickedName;
  6144. $merged['picked_supplier_name'] = $pickedName;
  6145. }
  6146. $mergedPickTime = '';
  6147. foreach ($rows as $r) {
  6148. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6149. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6150. $mergedPickTime = $t;
  6151. }
  6152. }
  6153. if ($mergedPickTime !== '') {
  6154. $merged['pick_time'] = $mergedPickTime;
  6155. }
  6156. $out[] = $merged;
  6157. }
  6158. usort($out, function ($a, $b) {
  6159. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6160. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6161. if ($ta === $tb) {
  6162. $ida = (int)($a['purchase_order_id'] ?? 0);
  6163. $idb = (int)($b['purchase_order_id'] ?? 0);
  6164. if ($ida !== $idb) {
  6165. return $idb <=> $ida;
  6166. }
  6167. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6168. }
  6169. if ($ta === '') {
  6170. return 1;
  6171. }
  6172. if ($tb === '') {
  6173. return -1;
  6174. }
  6175. return strcmp($tb, $ta);
  6176. });
  6177. return $out;
  6178. }
  6179. /**
  6180. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6181. *
  6182. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6183. */
  6184. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6185. {
  6186. $scydgyId = trim($scydgyId);
  6187. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6188. if ($scydgyId === '') {
  6189. return $empty;
  6190. }
  6191. try {
  6192. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6193. } catch (\Throwable $e) {
  6194. $anchor = null;
  6195. }
  6196. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6197. return $empty;
  6198. }
  6199. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6200. if ($ccydh === '') {
  6201. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6202. }
  6203. try {
  6204. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6205. } catch (\Throwable $e) {
  6206. $pos = [$anchor];
  6207. }
  6208. if (!is_array($pos) || $pos === []) {
  6209. $pos = [$anchor];
  6210. }
  6211. return [
  6212. 'ccydh' => $ccydh,
  6213. 'pos' => $pos,
  6214. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6215. ];
  6216. }
  6217. /**
  6218. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6219. */
  6220. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6221. {
  6222. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6223. return false;
  6224. }
  6225. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6226. return false;
  6227. }
  6228. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6229. return true;
  6230. }
  6231. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6232. $sid = (int)($po['scydgy_id'] ?? 0);
  6233. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6234. }
  6235. return false;
  6236. }
  6237. /**
  6238. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6239. *
  6240. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6241. */
  6242. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6243. {
  6244. $scydgyId = trim($scydgyId);
  6245. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6246. if ($scydgyId === '') {
  6247. return $empty;
  6248. }
  6249. try {
  6250. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6251. } catch (\Throwable $e) {
  6252. $anchor = null;
  6253. }
  6254. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6255. return $empty;
  6256. }
  6257. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6258. if ($ccydh === '') {
  6259. return [
  6260. 'ccydh' => '',
  6261. 'pos' => [$anchor],
  6262. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6263. ];
  6264. }
  6265. try {
  6266. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6267. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6268. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6269. } catch (\Throwable $e) {
  6270. $pos = [$anchor];
  6271. }
  6272. if (!is_array($pos) || $pos === []) {
  6273. $pos = [$anchor];
  6274. }
  6275. $pos = array_values(array_filter($pos, function ($po) {
  6276. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6277. }));
  6278. if ($pos === []) {
  6279. $pos = [$anchor];
  6280. }
  6281. return [
  6282. 'ccydh' => $ccydh,
  6283. 'pos' => $pos,
  6284. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6285. ];
  6286. }
  6287. /**
  6288. * @param array<int, array<string, mixed>> $purchaseOrders
  6289. * @return array<int, array<string, mixed>>
  6290. */
  6291. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6292. {
  6293. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6294. $byId = [];
  6295. foreach ($pool as $r) {
  6296. if (!is_array($r)) {
  6297. continue;
  6298. }
  6299. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6300. if ($this->isValidScydgyRowId($sid)) {
  6301. $byId[$sid] = $r;
  6302. }
  6303. }
  6304. $out = [];
  6305. foreach ($purchaseOrders as $po) {
  6306. if (!is_array($po)) {
  6307. continue;
  6308. }
  6309. $sid = (int)($po['scydgy_id'] ?? 0);
  6310. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6311. $out[] = $byId[$sid];
  6312. }
  6313. }
  6314. return $out;
  6315. }
  6316. /**
  6317. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6318. *
  6319. * @return array<int, array<string, mixed>>
  6320. */
  6321. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6322. {
  6323. $scydgyId = trim($scydgyId);
  6324. if ($scydgyId === '') {
  6325. return [];
  6326. }
  6327. try {
  6328. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6329. } catch (\Throwable $e) {
  6330. $anchor = null;
  6331. }
  6332. if (!is_array($anchor)) {
  6333. return [];
  6334. }
  6335. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6336. return [];
  6337. }
  6338. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6339. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6340. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6341. try {
  6342. $q = Db::table('purchase_order');
  6343. if ($ccydh !== '') {
  6344. $q->where('CCYDH', $ccydh);
  6345. } else {
  6346. $q->where('scydgy_id', $scydgyId);
  6347. }
  6348. if ($isValidPick) {
  6349. $q->where('pick_time', $pickTime);
  6350. }
  6351. $pos = $q->order('scydgy_id', 'asc')->select();
  6352. } catch (\Throwable $e) {
  6353. $pos = [$anchor];
  6354. }
  6355. if (!is_array($pos) || $pos === []) {
  6356. $pos = [$anchor];
  6357. }
  6358. $pos = array_values(array_filter($pos, function ($po) {
  6359. if (!is_array($po)) {
  6360. return false;
  6361. }
  6362. $mr = $po['mod_rq'] ?? null;
  6363. if ($mr === null || $mr === '') {
  6364. return true;
  6365. }
  6366. $mrs = trim((string)$mr);
  6367. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6368. }));
  6369. if ($pos === []) {
  6370. $pos = [$anchor];
  6371. }
  6372. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6373. if ($rows === []) {
  6374. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6375. }
  6376. return $rows;
  6377. }
  6378. /**
  6379. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6380. *
  6381. * @param array<int, array<string, mixed>> $mergeRows
  6382. * @return array<int, array<string, mixed>>
  6383. */
  6384. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6385. {
  6386. $list = array_values($mergeRows);
  6387. $n = count($list);
  6388. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6389. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6390. $mergeSame = $n > 1 && $orderKey0 !== '';
  6391. if ($mergeSame) {
  6392. foreach ($list as $rr) {
  6393. if (!is_array($rr)) {
  6394. $mergeSame = false;
  6395. break;
  6396. }
  6397. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6398. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6399. $mergeSame = false;
  6400. break;
  6401. }
  6402. }
  6403. }
  6404. $out = [];
  6405. foreach ($list as $idx => $r) {
  6406. if (!is_array($r)) {
  6407. continue;
  6408. }
  6409. $qty = $this->resolveProcuremenThisQuantity($r);
  6410. $price = $this->resolveProcuremenCeilingPrice($r);
  6411. $sid = $this->extractScydgyRowId($r);
  6412. $out[] = [
  6413. 'seq' => $idx + 1,
  6414. 'scydgy_id' => $sid,
  6415. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6416. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6417. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6418. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6419. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6420. 'NGZL' => $r['NGZL'] ?? '',
  6421. 'This_quantity' => $qty,
  6422. 'ceilingPrice' => $price,
  6423. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6424. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6425. 'show_order_cells' => !$mergeSame || $idx === 0,
  6426. 'order_rowspan' => $mergeSame ? $n : 1,
  6427. ];
  6428. }
  6429. return $out;
  6430. }
  6431. /**
  6432. * 解析金额/数量(去千分位等非数字字符)
  6433. */
  6434. protected function parseProcuremenMoneyNumber($value): ?float
  6435. {
  6436. if ($value === null || $value === '') {
  6437. return null;
  6438. }
  6439. if (is_numeric($value)) {
  6440. return (float)$value;
  6441. }
  6442. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6443. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6444. }
  6445. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6446. {
  6447. if ($amount === null) {
  6448. return '';
  6449. }
  6450. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6451. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6452. return $s === '' ? '0' : $s;
  6453. }
  6454. /**
  6455. * 列表/详情展示:工作量为 0 时显示空
  6456. */
  6457. protected function formatProcuremenWorkloadDisplay($value): string
  6458. {
  6459. if ($value === null || $value === '') {
  6460. return '';
  6461. }
  6462. $s = trim((string)$value);
  6463. if ($s === '') {
  6464. return '';
  6465. }
  6466. if (is_numeric($s) && (float)$s == 0) {
  6467. return '';
  6468. }
  6469. return $s;
  6470. }
  6471. /**
  6472. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6473. */
  6474. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6475. {
  6476. foreach ($details as $d) {
  6477. if (!is_array($d)) {
  6478. continue;
  6479. }
  6480. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6481. $cn = trim((string)($d['company_name'] ?? ''));
  6482. if ($cn !== '') {
  6483. return $cn;
  6484. }
  6485. }
  6486. }
  6487. return trim((string)($main['pick_company_name'] ?? ''));
  6488. }
  6489. /**
  6490. * 详情报价小计:单价 × 本工序本次数量
  6491. */
  6492. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6493. {
  6494. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6495. if ($unit === null) {
  6496. return null;
  6497. }
  6498. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6499. if ($qty === null || $qty <= 0) {
  6500. return null;
  6501. }
  6502. return $unit * $qty;
  6503. }
  6504. /**
  6505. * 详情页:工序小计 + 供应商分组报价与总计
  6506. *
  6507. * @param array<int, array<string, mixed>> $mergeRows
  6508. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6509. * @return array{
  6510. * process_rows: array,
  6511. * supplier_groups: array,
  6512. * order_total_text: string,
  6513. * order_total_has: bool,
  6514. * selected_company: string
  6515. * }
  6516. */
  6517. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6518. {
  6519. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6520. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6521. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6522. || ((int)($main['manual_pick'] ?? 0) === 1);
  6523. $qtyBySid = [];
  6524. $gymcBySid = [];
  6525. $orderedSids = [];
  6526. foreach ($mergeRows as $mr) {
  6527. if (!is_array($mr)) {
  6528. continue;
  6529. }
  6530. $sid = $this->extractScydgyRowId($mr);
  6531. if ($this->isValidScydgyRowId($sid)) {
  6532. $orderedSids[] = $sid;
  6533. }
  6534. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6535. if ($qty === '') {
  6536. $qty = trim((string)($mr['NGZL'] ?? ''));
  6537. }
  6538. $qtyBySid[$sid] = $qty;
  6539. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6540. }
  6541. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6542. $detailByCompanySid = [];
  6543. foreach ($details as $d) {
  6544. if (!is_array($d)) {
  6545. continue;
  6546. }
  6547. $cn = trim((string)($d['company_name'] ?? ''));
  6548. $sid = (int)($d['scydgy_id'] ?? 0);
  6549. if ($cn === '' || $sid === 0) {
  6550. continue;
  6551. }
  6552. if (!isset($detailByCompanySid[$cn])) {
  6553. $detailByCompanySid[$cn] = [];
  6554. }
  6555. $detailByCompanySid[$cn][$sid] = $d;
  6556. }
  6557. $supplierGroups = [];
  6558. foreach ($detailByCompanySid as $cn => $bySid) {
  6559. $lines = [];
  6560. $groupTotal = 0.0;
  6561. $groupHas = false;
  6562. $groupVoid = true;
  6563. $usedSids = [];
  6564. $appendLine = function (int $sid, array $d) use (
  6565. &$lines,
  6566. &$groupTotal,
  6567. &$groupHas,
  6568. &$groupVoid,
  6569. $qtyBySid,
  6570. $gymcBySid,
  6571. $quoteVisible
  6572. ) {
  6573. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6574. if (!$isVoid) {
  6575. $groupVoid = false;
  6576. }
  6577. $qtyStr = $qtyBySid[$sid] ?? '';
  6578. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6579. $am = trim((string)($d['amount'] ?? ''));
  6580. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6581. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6582. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6583. $sub = null;
  6584. if (!$isVoid && $amountNum !== null) {
  6585. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6586. }
  6587. $ct = $this->resolveDetailSupplierOperTime($d);
  6588. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6589. $leadFilled = ($leadDays !== null);
  6590. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6591. $line = [
  6592. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6593. 'amount' => $am,
  6594. 'unit_price_text' => $amountFilled
  6595. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6596. : '未填写',
  6597. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6598. 'delivery_ymd' => $deliveryYmd,
  6599. 'amount_filled' => $amountFilled,
  6600. 'delivery_filled' => $deliveryFilled,
  6601. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6602. 'lead_days' => $leadFilled ? $leadDays : '',
  6603. 'lead_days_filled'=> $leadFilled,
  6604. 'lead_days_show' => $leadText,
  6605. 'lead_days_text' => $leadText,
  6606. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6607. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6608. 'is_void' => $isVoid,
  6609. 'oper_time_text' => $ct,
  6610. ];
  6611. if (!$quoteVisible && !$isVoid) {
  6612. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6613. } elseif ($sub !== null) {
  6614. $groupTotal += $sub;
  6615. $groupHas = true;
  6616. }
  6617. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6618. };
  6619. foreach ($orderedSids as $sid) {
  6620. if (!isset($bySid[$sid])) {
  6621. continue;
  6622. }
  6623. $usedSids[$sid] = true;
  6624. $appendLine($sid, $bySid[$sid]);
  6625. }
  6626. foreach ($bySid as $sid => $d) {
  6627. if (isset($usedSids[$sid])) {
  6628. continue;
  6629. }
  6630. $appendLine((int)$sid, $d);
  6631. }
  6632. $firstDetail = null;
  6633. foreach ($bySid as $d) {
  6634. if (is_array($d)) {
  6635. $firstDetail = $d;
  6636. break;
  6637. }
  6638. }
  6639. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6640. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6641. if ($username === '' && $ph !== '') {
  6642. $username = $this->resolveCustomerContactName($ph, $cn);
  6643. }
  6644. $remark = '';
  6645. foreach ($bySid as $d) {
  6646. if (!is_array($d)) {
  6647. continue;
  6648. }
  6649. $rm = '';
  6650. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6651. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6652. $rm = trim((string)$d[$rk]);
  6653. break;
  6654. }
  6655. }
  6656. if ($rm !== '') {
  6657. $remark = $rm;
  6658. break;
  6659. }
  6660. }
  6661. $lineCount = count($lines);
  6662. $hasRemark = $lineCount > 0;
  6663. $supplierGroup = [
  6664. 'company_name' => $cn,
  6665. 'username' => $username,
  6666. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6667. 'phone' => $ph,
  6668. 'remark' => $remark,
  6669. 'has_remark' => $hasRemark,
  6670. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6671. 'is_void' => $groupVoid,
  6672. 'lines' => $lines,
  6673. 'line_count' => $lineCount,
  6674. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6675. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6676. 'has_total' => $lineCount > 0,
  6677. ];
  6678. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6679. $supplierGroups[] = $supplierGroup;
  6680. }
  6681. usort($supplierGroups, function ($a, $b) {
  6682. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6683. return ($a['is_void'] ?? false) ? 1 : -1;
  6684. }
  6685. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6686. return ($a['is_selected'] ?? false) ? -1 : 1;
  6687. }
  6688. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6689. });
  6690. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6691. return [
  6692. 'process_rows' => $processRows,
  6693. 'supplier_groups' => $supplierGroups,
  6694. 'order_total_text' => '',
  6695. 'order_total_has' => false,
  6696. 'selected_company' => $selectedCompany,
  6697. ];
  6698. }
  6699. /**
  6700. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6701. */
  6702. protected function buildProcessLinesPlain(array $mergeRows): string
  6703. {
  6704. $lines = [];
  6705. $i = 1;
  6706. foreach ($mergeRows as $r) {
  6707. if (!is_array($r)) {
  6708. continue;
  6709. }
  6710. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6711. $dw = trim((string)($r['CDW'] ?? ''));
  6712. $gzl = trim((string)($r['NGZL'] ?? ''));
  6713. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6714. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6715. if ($dw !== '') {
  6716. $parts[] = '单位:' . $dw;
  6717. }
  6718. if ($gzl !== '') {
  6719. $parts[] = '工作量:' . $gzl;
  6720. }
  6721. if ($qty !== '') {
  6722. $parts[] = '本次数量:' . $qty;
  6723. }
  6724. $lines[] = implode(' ', $parts);
  6725. $i++;
  6726. }
  6727. return implode("\n", $lines);
  6728. }
  6729. /**
  6730. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6731. *
  6732. * @return array<string, string>
  6733. */
  6734. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6735. {
  6736. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6737. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6738. }
  6739. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6740. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6741. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6742. $cyjmc = '';
  6743. foreach ($mergeRows as $mr) {
  6744. if (!is_array($mr)) {
  6745. continue;
  6746. }
  6747. if ($ccydh === '') {
  6748. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6749. }
  6750. if ($cyjmc === '') {
  6751. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6752. }
  6753. }
  6754. if ($pos !== []) {
  6755. $firstPo = $pos[0];
  6756. if (is_array($firstPo)) {
  6757. if ($ccydh === '') {
  6758. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6759. }
  6760. if ($cyjmc === '') {
  6761. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6762. }
  6763. }
  6764. }
  6765. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6766. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6767. if (is_array($any)) {
  6768. if ($ccydh === '') {
  6769. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6770. }
  6771. if ($cyjmc === '') {
  6772. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6773. }
  6774. }
  6775. }
  6776. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6777. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6778. $cgymc = '';
  6779. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6780. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6781. }
  6782. return [
  6783. 'ccydh' => $ccydh,
  6784. 'cyjmc' => $cyjmc,
  6785. 'cgymc' => $cgymc,
  6786. 'process_lines' => $processLines,
  6787. 'process_lines_html' => '',
  6788. ];
  6789. }
  6790. /**
  6791. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6792. */
  6793. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6794. {
  6795. $lines = [];
  6796. if ($ccydh !== '') {
  6797. $lines[] = '订单号:' . $ccydh;
  6798. }
  6799. if ($cyjmc !== '') {
  6800. $lines[] = '印件名称:' . $cyjmc;
  6801. }
  6802. if ($processPlain !== '') {
  6803. $lines[] = $processPlain;
  6804. }
  6805. return implode("\n", $lines);
  6806. }
  6807. /**
  6808. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6809. *
  6810. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6811. */
  6812. protected function buildPlatformLinksPlain(array $detailLinks): string
  6813. {
  6814. $lines = [];
  6815. $i = 1;
  6816. foreach ($detailLinks as $lk) {
  6817. if (!is_array($lk)) {
  6818. continue;
  6819. }
  6820. $url = trim((string)($lk['url'] ?? ''));
  6821. if ($url === '') {
  6822. continue;
  6823. }
  6824. $label = trim((string)($lk['cgymc'] ?? ''));
  6825. if ($label === '') {
  6826. $label = '工序' . $i;
  6827. }
  6828. $lines[] = $label . ':' . $url;
  6829. $i++;
  6830. }
  6831. return implode("\n", $lines);
  6832. }
  6833. /**
  6834. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6835. *
  6836. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6837. */
  6838. protected function buildPlatformLinksHtml(array $detailLinks): string
  6839. {
  6840. $parts = [];
  6841. $i = 1;
  6842. foreach ($detailLinks as $lk) {
  6843. if (!is_array($lk)) {
  6844. continue;
  6845. }
  6846. $url = trim((string)($lk['url'] ?? ''));
  6847. if ($url === '') {
  6848. continue;
  6849. }
  6850. $label = trim((string)($lk['cgymc'] ?? ''));
  6851. if ($label === '') {
  6852. $label = '工序' . $i;
  6853. }
  6854. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6855. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6856. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6857. $i++;
  6858. }
  6859. return implode("<br>\n", $parts);
  6860. }
  6861. /**
  6862. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6863. *
  6864. * @return array<string, mixed>
  6865. */
  6866. protected function loadMailerConfig(): array
  6867. {
  6868. try {
  6869. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6870. } catch (\Throwable $e) {
  6871. $cfg = [];
  6872. }
  6873. return is_array($cfg) ? $cfg : [];
  6874. }
  6875. protected function loadNotifyTemplateRow(string $scene): ?array
  6876. {
  6877. try {
  6878. $row = Db::table('purchase_sms_template')
  6879. ->where('scene', $scene)
  6880. ->where(function ($q) {
  6881. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6882. })
  6883. ->order('id', 'asc')
  6884. ->find();
  6885. } catch (\Throwable $e) {
  6886. return null;
  6887. }
  6888. if (!is_array($row) || $row === []) {
  6889. return null;
  6890. }
  6891. return [
  6892. 'title' => trim((string)($row['title'] ?? '')),
  6893. 'content' => trim((string)($row['content'] ?? '')),
  6894. ];
  6895. }
  6896. /**
  6897. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6898. */
  6899. protected function buildProcessLinesHtml(array $mergeRows): string
  6900. {
  6901. if (count($mergeRows) <= 1) {
  6902. $r = $mergeRows[0] ?? [];
  6903. if (!is_array($r)) {
  6904. return '';
  6905. }
  6906. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6907. $dw = trim((string)($r['CDW'] ?? ''));
  6908. $gzl = trim((string)($r['NGZL'] ?? ''));
  6909. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6910. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6911. if ($dw !== '') {
  6912. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6913. }
  6914. if ($gzl !== '') {
  6915. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6916. }
  6917. if ($qty !== '') {
  6918. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6919. }
  6920. return $html;
  6921. }
  6922. $rows = '';
  6923. $i = 1;
  6924. foreach ($mergeRows as $r) {
  6925. if (!is_array($r)) {
  6926. continue;
  6927. }
  6928. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6929. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6930. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6931. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6932. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6933. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6934. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6935. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6936. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6937. $i++;
  6938. }
  6939. if ($rows === '') {
  6940. return '';
  6941. }
  6942. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  6943. . '<thead><tr style="background:#f5f5f5;">'
  6944. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  6945. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  6946. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  6947. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  6948. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  6949. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  6950. }
  6951. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  6952. {
  6953. $sysRq = trim($sysRq);
  6954. if ($sysRq === '') {
  6955. if ($required) {
  6956. $this->error('请选择招标截止日期');
  6957. }
  6958. return '';
  6959. }
  6960. $ts = strtotime($sysRq);
  6961. if ($ts === false || $ts <= 0) {
  6962. $this->error('招标截止日期格式无效');
  6963. }
  6964. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  6965. if (!$allowPast) {
  6966. $ymd = date('Y-m-d', $ts);
  6967. if ($ymd < date('Y-m-d')) {
  6968. $this->error('招标截止日期不能早于今天');
  6969. }
  6970. if ($ts <= time()) {
  6971. $this->error('招标截止时间不能早于当前时间');
  6972. }
  6973. }
  6974. return date('Y-m-d H:i:s', $ts);
  6975. }
  6976. /**
  6977. * 确保 purchase_order.czlyq(类型)存在
  6978. */
  6979. protected function ensurePurchaseOrderCzlyqColumn(): void
  6980. {
  6981. static $done = false;
  6982. if ($done) {
  6983. return;
  6984. }
  6985. $done = true;
  6986. try {
  6987. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  6988. if (empty($cols)) {
  6989. Db::execute(
  6990. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  6991. );
  6992. }
  6993. } catch (\Throwable $e) {
  6994. // ignore
  6995. }
  6996. }
  6997. /**
  6998. * 确保 purchase_order.delivery_deadline 存在
  6999. */
  7000. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7001. {
  7002. static $done = false;
  7003. if ($done) {
  7004. return;
  7005. }
  7006. $done = true;
  7007. try {
  7008. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7009. if (empty($cols)) {
  7010. Db::execute(
  7011. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7012. );
  7013. }
  7014. } catch (\Throwable $e) {
  7015. // ignore
  7016. }
  7017. }
  7018. /**
  7019. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7020. */
  7021. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7022. {
  7023. static $done = false;
  7024. if ($done) {
  7025. return;
  7026. }
  7027. $done = true;
  7028. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7029. $adds = [
  7030. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7031. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7032. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7033. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7034. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7035. ];
  7036. $changed = false;
  7037. foreach ($adds as $col => $ddl) {
  7038. try {
  7039. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7040. if (!is_array($cols) || $cols === []) {
  7041. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7042. $changed = true;
  7043. }
  7044. } catch (\Throwable $e) {
  7045. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7046. }
  7047. }
  7048. if ($changed) {
  7049. $this->clearPurchaseOrderTableFieldsCache();
  7050. }
  7051. }
  7052. /**
  7053. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7054. */
  7055. protected function clearPurchaseOrderTableFieldsCache(): void
  7056. {
  7057. try {
  7058. $db = (string)Config::get('database.database');
  7059. $key = $db . '.purchase_order';
  7060. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7061. $ref->setAccessible(true);
  7062. $info = $ref->getValue();
  7063. if (is_array($info) && isset($info[$key])) {
  7064. unset($info[$key]);
  7065. $ref->setValue(null, $info);
  7066. }
  7067. } catch (\Throwable $e) {
  7068. }
  7069. try {
  7070. $db = (string)Config::get('database.database');
  7071. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7072. if (is_file($schemaFile)) {
  7073. @unlink($schemaFile);
  7074. }
  7075. } catch (\Throwable $e) {
  7076. }
  7077. }
  7078. /**
  7079. * @return array<string, bool>
  7080. */
  7081. protected function loadPurchaseOrderColumnSet(): array
  7082. {
  7083. static $set = null;
  7084. if (is_array($set)) {
  7085. return $set;
  7086. }
  7087. $set = [];
  7088. try {
  7089. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7090. } catch (\Throwable $e) {
  7091. return $set;
  7092. }
  7093. if (!is_array($cols)) {
  7094. return $set;
  7095. }
  7096. foreach ($cols as $c) {
  7097. if (!is_array($c)) {
  7098. continue;
  7099. }
  7100. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7101. if ($f !== '') {
  7102. $set[$f] = true;
  7103. }
  7104. }
  7105. return $set;
  7106. }
  7107. /**
  7108. * 解析交货截止日期(仅年月日)
  7109. */
  7110. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7111. {
  7112. $raw = trim($raw);
  7113. if ($raw === '') {
  7114. if ($required) {
  7115. $this->error('请选择交货截止日期');
  7116. }
  7117. return '';
  7118. }
  7119. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7120. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7121. } else {
  7122. $ts = strtotime(str_replace('/', '-', $raw));
  7123. if ($ts === false || $ts <= 0) {
  7124. $this->error('交货截止日期格式无效');
  7125. }
  7126. $ymd = date('Y-m-d', $ts);
  7127. }
  7128. if ($ymd < date('Y-m-d')) {
  7129. $this->error('交货截止日期不能早于今天');
  7130. }
  7131. return $ymd;
  7132. }
  7133. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7134. {
  7135. $s = trim((string)$value);
  7136. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7137. return '';
  7138. }
  7139. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7140. return $m[1];
  7141. }
  7142. $ts = strtotime(str_replace('/', '-', $s));
  7143. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7144. }
  7145. /**
  7146. * @param array{pos?:array} $bundle
  7147. */
  7148. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7149. {
  7150. foreach ($bundle['pos'] ?? [] as $po) {
  7151. if (!is_array($po)) {
  7152. continue;
  7153. }
  7154. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7155. if ($d !== '') {
  7156. return $d;
  7157. }
  7158. }
  7159. return '';
  7160. }
  7161. protected function formatProcuremenSysRqForInput($sysRq): string
  7162. {
  7163. $sr = trim((string)$sysRq);
  7164. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7165. return '';
  7166. }
  7167. $ts = strtotime($sr);
  7168. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7169. }
  7170. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7171. {
  7172. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7173. if ($sr === '') {
  7174. return '—';
  7175. }
  7176. $ts = strtotime($sr);
  7177. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7178. }
  7179. /**
  7180. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7181. *
  7182. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7183. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7184. */
  7185. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7186. {
  7187. return $bundle;
  7188. }
  7189. /**
  7190. * 写入/更新 purchase_order(单道工序行)
  7191. *
  7192. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7193. */
  7194. protected function upsertPurchaseOrderFromRow(
  7195. array $row,
  7196. string $sysRqDb,
  7197. $wflowStatus = null,
  7198. ?string $pickTime = null,
  7199. ?array $exists = null,
  7200. ?string $deliveryDeadline = null,
  7201. $scoreRuleId = null
  7202. ): void {
  7203. $ids = $this->extractScydgyRowId($row);
  7204. if (!$this->isValidScydgyRowId($ids)) {
  7205. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7206. }
  7207. if ($exists === null) {
  7208. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7209. }
  7210. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7211. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7212. $this->ensurePurchaseOrderCzlyqColumn();
  7213. $data = [
  7214. 'scydgy_id' => $ids,
  7215. 'CCYDH' => $row['CCYDH'] ?? null,
  7216. 'CYJMC' => $row['CYJMC'] ?? null,
  7217. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7218. 'CDXMC' => $row['CDXMC'] ?? null,
  7219. 'CGYBH' => $row['CGYBH'] ?? null,
  7220. 'CGYMC' => $row['CGYMC'] ?? null,
  7221. 'CDW' => $row['CDW'] ?? null,
  7222. 'czlyq' => $row['czlyq'] ?? null,
  7223. 'NGZL' => $row['NGZL'] ?? null,
  7224. 'CDF' => $row['CDF'] ?? null,
  7225. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7226. 'MBZ' => $row['MBZ'] ?? null,
  7227. 'bwjg' => $row['bwjg'] ?? null,
  7228. 'iStatus' => $row['iStatus'] ?? null,
  7229. 'dStamp' => $row['dStamp'] ?? null,
  7230. 'dputrecord' => $row['dputrecord'] ?? null,
  7231. 'cywyxm' => $row['cywyxm'] ?? null,
  7232. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7233. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7234. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7235. 'sys_rq' => $sysRqDb,
  7236. ];
  7237. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7238. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7239. if ($qtyUp === '') {
  7240. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7241. 'This_quantity' => '',
  7242. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7243. ]);
  7244. if ($qtyFallback !== '') {
  7245. $data['This_quantity'] = $qtyFallback;
  7246. }
  7247. }
  7248. if ($deliveryDeadline !== null) {
  7249. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7250. }
  7251. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7252. $scoreRule = null;
  7253. if (is_array($scoreRuleId)) {
  7254. $scoreRule = $scoreRuleId;
  7255. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7256. } else {
  7257. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7258. }
  7259. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7260. $poCols = $this->loadPurchaseOrderColumnSet();
  7261. if (!empty($poCols['score_rule_id'])) {
  7262. $data['score_rule_id'] = $scoreRuleId;
  7263. if (is_array($scoreRule)) {
  7264. if (!empty($poCols['score_rule_name'])) {
  7265. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7266. }
  7267. if (!empty($poCols['score_quality_weight'])) {
  7268. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7269. }
  7270. if (!empty($poCols['score_price_weight'])) {
  7271. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7272. }
  7273. if (!empty($poCols['score_lead_weight'])) {
  7274. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7275. }
  7276. }
  7277. }
  7278. }
  7279. if ($wflowStatus !== null && $wflowStatus !== '') {
  7280. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7281. }
  7282. if ($pickTime !== null && $pickTime !== '') {
  7283. $data['pick_time'] = $pickTime;
  7284. $data['pick_company_name'] = '';
  7285. }
  7286. if ($exists) {
  7287. $upd = $data;
  7288. unset($upd['scydgy_id']);
  7289. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7290. } else {
  7291. $data['createtime'] = date('Y-m-d H:i:s');
  7292. Db::table('purchase_order')->insert($data);
  7293. }
  7294. }
  7295. /**
  7296. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7297. *
  7298. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7299. */
  7300. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7301. {
  7302. $toDb = function ($value) {
  7303. if ($value === null) {
  7304. return null;
  7305. }
  7306. if (is_scalar($value)) {
  7307. return $value;
  7308. }
  7309. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7310. };
  7311. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7312. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7313. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7314. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7315. if ($username === '') {
  7316. $username = $this->resolveCustomerContactName($phone, $companyName);
  7317. }
  7318. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7319. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7320. }
  7321. if ($requirePhone && $phone === '') {
  7322. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7323. }
  7324. $detailLinks = [];
  7325. foreach ($mergeRows as $row) {
  7326. if (!is_array($row)) {
  7327. continue;
  7328. }
  7329. $sid = $this->extractScydgyRowId($row);
  7330. $detailId = 0;
  7331. if ($skipExisting) {
  7332. try {
  7333. $existsQuery = Db::table('purchase_order_detail')
  7334. ->where('scydgy_id', $sid)
  7335. ->where('company_name', $companyName);
  7336. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7337. $exists = $existsQuery->find();
  7338. } catch (\Throwable $e) {
  7339. $exists = null;
  7340. }
  7341. if (is_array($exists)) {
  7342. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7343. }
  7344. }
  7345. if ($detailId <= 0) {
  7346. $one = [
  7347. 'scydgy_id' => $toDb($sid),
  7348. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7349. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7350. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7351. 'username' => $username !== '' ? $username : null,
  7352. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7353. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7354. 'createtime' => date('Y-m-d H:i:s'),
  7355. 'status' => ProcuremenStatus::POD_UNPICKED,
  7356. 'status_name' => '未提交',
  7357. ];
  7358. Db::table('purchase_order_detail')->insert($one);
  7359. $detailId = (int)Db::getLastInsID();
  7360. }
  7361. $mprocUrl = '';
  7362. if ($buildMobileLinks && $detailId > 0) {
  7363. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7364. }
  7365. $detailLinks[] = [
  7366. 'detail_id' => $detailId,
  7367. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7368. 'url' => $mprocUrl,
  7369. ];
  7370. }
  7371. $this->invalidatePickHiddenScydgyCache();
  7372. return $detailLinks;
  7373. }
  7374. /**
  7375. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7376. * @return array<string, mixed>
  7377. */
  7378. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  7379. {
  7380. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7381. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7382. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7383. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7384. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7385. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7386. $isMerge = !empty($ctx['is_merge']);
  7387. $contactName = trim((string)($c['username'] ?? ''));
  7388. if ($contactName === '') {
  7389. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7390. }
  7391. $notifyVars = [
  7392. 'company_name' => $companyName,
  7393. 'contact_name' => $contactName,
  7394. 'phone' => $phone,
  7395. 'email' => $toEmail,
  7396. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7397. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7398. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7399. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7400. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7401. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7402. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7403. 'platform_url' => $platformUrl,
  7404. 'platform_links' => $platformLinksPlain,
  7405. 'platform_links_html' => $platformLinksHtml,
  7406. ];
  7407. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7408. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  7409. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7410. return [
  7411. 'company_name' => $companyName,
  7412. 'phone' => $phone,
  7413. 'email' => $toEmail,
  7414. 'sms_content' => $smsContent,
  7415. 'mail_plain' => $mailPlain,
  7416. 'mail_body' => $mailBody,
  7417. 'notify_vars' => $notifyVars,
  7418. 'detail_links' => $detailLinks,
  7419. ];
  7420. }
  7421. /**
  7422. * @param array<string, mixed> $chosen
  7423. * @param array<int, array<string, mixed>> $mergeRows
  7424. * @param array{ccydh:string, pos:array} $bundle
  7425. */
  7426. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  7427. {
  7428. if (!$sendSms && !$sendEmail) {
  7429. return;
  7430. }
  7431. $companyName = trim((string)($chosen['name'] ?? ''));
  7432. $phone = trim((string)($chosen['phone'] ?? ''));
  7433. $toEmail = trim((string)($chosen['email'] ?? ''));
  7434. if ($companyName === '') {
  7435. throw new \Exception('供应商名称无效');
  7436. }
  7437. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7438. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7439. }
  7440. if ($sendSms && $phone === '') {
  7441. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7442. }
  7443. $sids = [];
  7444. foreach ($mergeRows as $mr) {
  7445. if (!is_array($mr)) {
  7446. continue;
  7447. }
  7448. $sid = $this->extractScydgyRowId($mr);
  7449. if ($this->isValidScydgyRowId($sid)) {
  7450. $sids[$sid] = true;
  7451. }
  7452. }
  7453. if ($sids === []) {
  7454. throw new \Exception('未找到工序行,无法发送通知');
  7455. }
  7456. $sysRqNotify = '';
  7457. $pos = $bundle['pos'] ?? [];
  7458. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7459. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7460. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7461. $ts = strtotime($sr);
  7462. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7463. }
  7464. }
  7465. try {
  7466. $detailsQuery = Db::table('purchase_order_detail')
  7467. ->where('scydgy_id', 'in', array_keys($sids))
  7468. ->where('company_name', $companyName);
  7469. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7470. $details = $detailsQuery->order('id', 'asc')->select();
  7471. } catch (\Throwable $e) {
  7472. $details = [];
  7473. }
  7474. if (!is_array($details) || $details === []) {
  7475. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7476. try {
  7477. $detailsQuery = Db::table('purchase_order_detail')
  7478. ->where('scydgy_id', 'in', array_keys($sids))
  7479. ->where('company_name', $companyName);
  7480. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7481. $details = $detailsQuery->order('id', 'asc')->select();
  7482. } catch (\Throwable $e) {
  7483. $details = [];
  7484. }
  7485. }
  7486. if (!is_array($details) || $details === []) {
  7487. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7488. }
  7489. $detailLinks = [];
  7490. foreach ($details as $d) {
  7491. if (!is_array($d)) {
  7492. continue;
  7493. }
  7494. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7495. if ($detailId <= 0) {
  7496. continue;
  7497. }
  7498. $sid = (int)($d['scydgy_id'] ?? 0);
  7499. $gymc = '';
  7500. foreach ($mergeRows as $mr) {
  7501. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7502. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7503. break;
  7504. }
  7505. }
  7506. $detailLinks[] = [
  7507. 'detail_id' => $detailId,
  7508. 'cgymc' => $gymc,
  7509. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7510. ];
  7511. }
  7512. if ($detailLinks === []) {
  7513. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7514. }
  7515. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7516. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  7517. $notifyBundle['email_log_scene'] = $emailLogScene;
  7518. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7519. $poIdLog = 0;
  7520. $pos = $bundle['pos'] ?? [];
  7521. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7522. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7523. }
  7524. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7525. if ($sendEmail) {
  7526. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  7527. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7528. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  7529. }
  7530. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  7531. $mailConfig = $this->loadMailerConfig();
  7532. if (!$this->isProcuremenNotifyDryRun()) {
  7533. if (empty($mailConfig['host'])) {
  7534. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7535. }
  7536. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7537. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7538. }
  7539. }
  7540. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7541. }
  7542. if ($sendSms) {
  7543. $this->issueSendSupplierSms($notifyBundle);
  7544. }
  7545. }
  7546. /**
  7547. * @param array<int, array<string, mixed>> $quoteGroups
  7548. * @return array<int, array<string, mixed>>
  7549. */
  7550. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7551. {
  7552. $names = [];
  7553. if (is_string($companiesJson) && $companiesJson !== '') {
  7554. $decoded = json_decode($companiesJson, true);
  7555. if (is_array($decoded)) {
  7556. foreach ($decoded as $nm) {
  7557. $nm = trim((string)$nm);
  7558. if ($nm !== '') {
  7559. $names[] = $nm;
  7560. }
  7561. }
  7562. }
  7563. }
  7564. $names = array_values(array_unique($names));
  7565. if ($names === [] && $selectedCompany !== '') {
  7566. $names = [$selectedCompany];
  7567. }
  7568. if ($names === []) {
  7569. return $quoteGroups;
  7570. }
  7571. $targets = [];
  7572. foreach ($quoteGroups as $g) {
  7573. if (!is_array($g)) {
  7574. continue;
  7575. }
  7576. $cn = trim((string)($g['name'] ?? ''));
  7577. if ($cn !== '' && in_array($cn, $names, true)) {
  7578. $targets[] = $g;
  7579. }
  7580. }
  7581. return $targets;
  7582. }
  7583. /**
  7584. * @return array{pos:array, merge_rows:array, bundle:array}
  7585. */
  7586. protected function loadAuditResendBundle(string $scydgyId): array
  7587. {
  7588. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7589. $pos = $bundle['pos'];
  7590. $mergeRows = $bundle['merge_rows'];
  7591. if ($pos === [] || $mergeRows === []) {
  7592. $this->error('该订单不在待确认供应商状态');
  7593. }
  7594. $sysRqDb = '';
  7595. if (isset($pos[0]) && is_array($pos[0])) {
  7596. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7597. }
  7598. foreach ($pos as $i => $poRow) {
  7599. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7600. $pos[$i]['sys_rq'] = $sysRqDb;
  7601. }
  7602. }
  7603. $bundle['pos'] = $pos;
  7604. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7605. }
  7606. /**
  7607. * @param array<int, array<string, mixed>> $targets
  7608. */
  7609. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7610. {
  7611. if ($targets === []) {
  7612. $this->error('未找到可通知的供应商');
  7613. }
  7614. $notifyErrors = [];
  7615. try {
  7616. $this->notifyDryRunPreview = [];
  7617. foreach ($targets as $g) {
  7618. if (!is_array($g)) {
  7619. continue;
  7620. }
  7621. $cname = trim((string)($g['name'] ?? ''));
  7622. if ($cname === '') {
  7623. continue;
  7624. }
  7625. $chosen = [
  7626. 'name' => $cname,
  7627. 'company_name' => $cname,
  7628. 'email' => trim((string)($g['email'] ?? '')),
  7629. 'phone' => trim((string)($g['phone'] ?? '')),
  7630. 'username' => trim((string)($g['username'] ?? '')),
  7631. ];
  7632. try {
  7633. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7634. } catch (\Throwable $e) {
  7635. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7636. }
  7637. }
  7638. } catch (\Throwable $e) {
  7639. $this->error('通知发送失败:' . $e->getMessage());
  7640. }
  7641. if ($notifyErrors !== []) {
  7642. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7643. }
  7644. if ($this->isProcuremenNotifyDryRun()) {
  7645. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7646. 'notify_dry_run' => true,
  7647. 'notify_preview' => $this->notifyDryRunPreview,
  7648. ]);
  7649. }
  7650. $nameLabels = [];
  7651. foreach ($targets as $g) {
  7652. if (!is_array($g)) {
  7653. continue;
  7654. }
  7655. $n = trim((string)($g['name'] ?? ''));
  7656. if ($n !== '') {
  7657. $nameLabels[] = $n;
  7658. }
  7659. }
  7660. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7661. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7662. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7663. $seenLogSid = [];
  7664. foreach ($bundle['pos'] ?? [] as $poRow) {
  7665. if (!is_array($poRow)) {
  7666. continue;
  7667. }
  7668. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7669. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7670. continue;
  7671. }
  7672. $seenLogSid[$sid] = true;
  7673. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7674. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7675. }
  7676. if ($seenLogSid === []) {
  7677. foreach ($mergeRows as $mr) {
  7678. if (!is_array($mr)) {
  7679. continue;
  7680. }
  7681. $sid = $this->extractScydgyRowId($mr);
  7682. if ($this->isValidScydgyRowId($sid)) {
  7683. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7684. break;
  7685. }
  7686. }
  7687. }
  7688. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7689. }
  7690. /**
  7691. * 协助下发 — 发送短信(一家供应商)
  7692. *
  7693. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7694. */
  7695. protected function issueSendSupplierSms(array $bundle): void
  7696. {
  7697. $companyName = (string)($bundle['company_name'] ?? '');
  7698. $phone = (string)($bundle['phone'] ?? '');
  7699. $smsContent = (string)($bundle['sms_content'] ?? '');
  7700. $this->logIssueNotifyDebug('短信', [
  7701. 'company' => $companyName,
  7702. 'phone' => $phone,
  7703. 'sms_content' => $smsContent,
  7704. ]);
  7705. if ($this->isProcuremenNotifyDryRun()) {
  7706. $this->recordNotifyDryRunPreview([
  7707. 'scene' => 'issue_sms',
  7708. 'company_name' => $companyName,
  7709. 'phone' => $phone,
  7710. 'sms_content' => $smsContent,
  7711. ]);
  7712. return;
  7713. }
  7714. $this->smsbao($phone, $smsContent);
  7715. }
  7716. /**
  7717. * 协助下发 — 发送邮件(一家供应商)
  7718. *
  7719. * @param array<string, mixed> $bundle
  7720. * @param array<string, mixed> $mailConfig
  7721. */
  7722. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7723. {
  7724. $companyName = (string)($bundle['company_name'] ?? '');
  7725. $toEmail = (string)($bundle['email'] ?? '');
  7726. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7727. $mailBody = (string)($bundle['mail_body'] ?? '');
  7728. $this->logIssueNotifyDebug('邮件', [
  7729. 'company' => $companyName,
  7730. 'email' => $toEmail,
  7731. 'mail_subject' => $mailSubject,
  7732. 'mail_body' => $mailPlain,
  7733. ]);
  7734. if ($this->isProcuremenNotifyDryRun()) {
  7735. $this->recordNotifyDryRunPreview([
  7736. 'scene' => 'issue_email',
  7737. 'company_name' => $companyName,
  7738. 'email' => $toEmail,
  7739. 'mail_subject' => $mailSubject,
  7740. 'mail_body' => $mailPlain,
  7741. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7742. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7743. 'detail_links' => $bundle['detail_links'] ?? [],
  7744. ]);
  7745. return;
  7746. }
  7747. $mail = new PHPMailer(true);
  7748. $mail->isSMTP();
  7749. $mail->Host = $mailConfig['host'];
  7750. $mail->SMTPAuth = true;
  7751. $mail->Username = $mailConfig['addr'];
  7752. $mail->Password = $mailConfig['pass'];
  7753. $mail->SMTPSecure = $mailConfig['security'];
  7754. $mail->Port = $mailConfig['port'];
  7755. $mail->CharSet = $mailConfig['charset'];
  7756. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7757. $mail->addAddress($toEmail, $companyName);
  7758. $mail->isHTML(true);
  7759. $mail->Subject = $mailSubject;
  7760. $mail->Body = $mailBody;
  7761. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7762. $sendOk = true;
  7763. $failReason = '';
  7764. try {
  7765. $mail->send();
  7766. } catch (\Throwable $e) {
  7767. $sendOk = false;
  7768. $failReason = $e->getMessage();
  7769. $this->persistEmailSendLog([
  7770. 'from_email' => $fromEmail,
  7771. 'to_email' => $toEmail,
  7772. 'send_time' => date('Y-m-d H:i:s'),
  7773. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7774. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7775. 'company_name' => $companyName,
  7776. 'mail_subject' => $mailSubject,
  7777. 'status' => 0,
  7778. 'fail_reason' => $failReason,
  7779. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7780. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7781. ]);
  7782. throw $e;
  7783. }
  7784. $this->persistEmailSendLog([
  7785. 'from_email' => $fromEmail,
  7786. 'to_email' => $toEmail,
  7787. 'send_time' => date('Y-m-d H:i:s'),
  7788. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7789. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7790. 'company_name' => $companyName,
  7791. 'mail_subject' => $mailSubject,
  7792. 'status' => 1,
  7793. 'fail_reason' => '',
  7794. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7795. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7796. ]);
  7797. }
  7798. /**
  7799. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7800. *
  7801. * @param array<int, array<string, mixed>> $mergeRows
  7802. * @return array<string, mixed>
  7803. */
  7804. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7805. {
  7806. $head = $mergeRows[0] ?? [];
  7807. $isMerge = count($mergeRows) > 1;
  7808. return [
  7809. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7810. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7811. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7812. 'is_merge' => $isMerge,
  7813. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7814. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7815. 'deadline' => $sysRqNotify,
  7816. ];
  7817. }
  7818. /**
  7819. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7820. *
  7821. * @param array<string, mixed> $data
  7822. */
  7823. protected function logIssueNotifyDebug(string $type, array $data): void
  7824. {
  7825. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7826. return;
  7827. }
  7828. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7829. }
  7830. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7831. {
  7832. try {
  7833. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7834. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7835. return;
  7836. } catch (\Throwable $e) {
  7837. }
  7838. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7839. if (is_file($sqlFile)) {
  7840. $sql = file_get_contents($sqlFile);
  7841. if (is_string($sql) && $sql !== '') {
  7842. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7843. $stmt = trim($stmt);
  7844. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7845. continue;
  7846. }
  7847. try {
  7848. Db::execute($stmt);
  7849. } catch (\Throwable $ignore) {
  7850. }
  7851. }
  7852. }
  7853. }
  7854. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7855. }
  7856. /**
  7857. * @param array<string, mixed> $row
  7858. */
  7859. protected function persistEmailSendLog(array $row): void
  7860. {
  7861. try {
  7862. $this->ensurePurchaseEmailSendLogTableOnce();
  7863. } catch (\Throwable $e) {
  7864. return;
  7865. }
  7866. list($adminId, $adminName) = $this->GetUseName();
  7867. $cut = function ($s, $max) {
  7868. $s = (string)$s;
  7869. if (function_exists('mb_substr')) {
  7870. return mb_substr($s, 0, $max, 'UTF-8');
  7871. }
  7872. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7873. };
  7874. $data = [
  7875. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7876. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7877. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7878. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7879. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7880. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7881. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7882. 'status' => !empty($row['status']) ? 1 : 0,
  7883. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7884. 'admin_id' => (int)$adminId,
  7885. 'admin_name' => $cut($adminName, 64),
  7886. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7887. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7888. 'createtime' => date('Y-m-d H:i:s'),
  7889. ];
  7890. try {
  7891. Db::table('purchase_email_send_log')->insert($data);
  7892. } catch (\Throwable $e) {
  7893. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7894. }
  7895. }
  7896. protected function formatEmailLogSceneText(string $scene): string
  7897. {
  7898. $map = [
  7899. 'pick_issue' => '初选下发',
  7900. 'audit_resend' => '确认页重发',
  7901. 'rfq_salesman' => '询价通知业务员',
  7902. ];
  7903. return $map[$scene] ?? $scene;
  7904. }
  7905. /**
  7906. * 邮件发送日志列表
  7907. */
  7908. public function emailLog()
  7909. {
  7910. $this->relationSearch = false;
  7911. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7912. $this->request->filter(['strip_tags', 'trim']);
  7913. $bakModel = $this->model;
  7914. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7915. if ($this->request->isAjax()) {
  7916. $this->ensurePurchaseEmailSendLogTableOnce();
  7917. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7918. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7919. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7920. $list = $this->model
  7921. ->where($where)
  7922. ->order($sortField, $orderDir)
  7923. ->paginate($limit);
  7924. $rows = [];
  7925. foreach ($list->items() as $item) {
  7926. $row = is_array($item) ? $item : $item->toArray();
  7927. $scene = trim((string)($row['scene'] ?? ''));
  7928. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7929. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7930. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7931. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7932. $rows[] = $row;
  7933. }
  7934. $this->model = $bakModel;
  7935. return json(['total' => $list->total(), 'rows' => $rows]);
  7936. }
  7937. $this->model = $bakModel;
  7938. return $this->view->fetch('procuremen/emaillog');
  7939. }
  7940. /**
  7941. * 协助下发弹窗(选多家供应商并通知)
  7942. */
  7943. public function pickReview()
  7944. {
  7945. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  7946. $this->error(__('You have no permission'));
  7947. }
  7948. if ($this->request->isPost()) {
  7949. $this->error('请使用弹窗内「确认下发」提交');
  7950. }
  7951. $this->view->assign('pickMode', 1);
  7952. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  7953. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  7954. }
  7955. /**
  7956. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  7957. */
  7958. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  7959. {
  7960. static $done = false;
  7961. if ($done) {
  7962. return;
  7963. }
  7964. $done = true;
  7965. try {
  7966. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  7967. if (empty($cols)) {
  7968. Db::execute(
  7969. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  7970. );
  7971. } else {
  7972. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  7973. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  7974. Db::execute(
  7975. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  7976. );
  7977. }
  7978. }
  7979. } catch (\Throwable $e) {
  7980. // ignore
  7981. }
  7982. }
  7983. /**
  7984. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  7985. */
  7986. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  7987. {
  7988. static $done = false;
  7989. if ($done) {
  7990. return;
  7991. }
  7992. $done = true;
  7993. try {
  7994. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  7995. if (empty($cols)) {
  7996. Db::execute(
  7997. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  7998. );
  7999. }
  8000. } catch (\Throwable $e) {
  8001. // ignore
  8002. }
  8003. try {
  8004. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8005. if (empty($cols2)) {
  8006. Db::execute(
  8007. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8008. );
  8009. }
  8010. } catch (\Throwable $e) {
  8011. // ignore
  8012. }
  8013. }
  8014. /**
  8015. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8016. */
  8017. protected function ensureRfqSalesmanEmailTemplate(): void
  8018. {
  8019. static $done = false;
  8020. if ($done) {
  8021. return;
  8022. }
  8023. $done = true;
  8024. $content = "您好,{contact_name}:\n\n"
  8025. . "有新的协助采购询价需求,请知悉。\n"
  8026. . "印件名称:{cyjmc}\n"
  8027. . "工序名称:{cgymc}\n"
  8028. . "本次数量:{this_quantity}\n"
  8029. . "供应商:{supplier_name}\n"
  8030. . "需求发起人:{cywyxm}\n";
  8031. try {
  8032. $row = Db::table('purchase_sms_template')
  8033. ->where('scene', 'rfq_salesman_email')
  8034. ->find();
  8035. } catch (\Throwable $e) {
  8036. return;
  8037. }
  8038. $now = date('Y-m-d H:i:s');
  8039. if (is_array($row) && $row !== []) {
  8040. $old = (string)($row['content'] ?? '');
  8041. $needMigrate = (strpos($old, '需求编号:{ccydh}') !== false)
  8042. || (strpos($old, '{supplier_name}') === false && strpos($old, '供应商:') === false);
  8043. if ($needMigrate) {
  8044. $data = ['content' => $content];
  8045. try {
  8046. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8047. if (!empty($cols)) {
  8048. $data['updatetime'] = $now;
  8049. }
  8050. } catch (\Throwable $e) {
  8051. }
  8052. try {
  8053. Db::table('purchase_sms_template')
  8054. ->where('id', (int)($row['id'] ?? 0))
  8055. ->update($data);
  8056. } catch (\Throwable $e) {
  8057. }
  8058. }
  8059. return;
  8060. }
  8061. try {
  8062. $data = [
  8063. 'scene' => 'rfq_salesman_email',
  8064. 'title' => '询价邮箱通知',
  8065. 'content' => $content,
  8066. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8067. 'status' => 1,
  8068. ];
  8069. try {
  8070. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8071. } catch (\Throwable $e) {
  8072. $cols = [];
  8073. }
  8074. $colNames = [];
  8075. foreach ($cols as $c) {
  8076. if (!is_array($c)) {
  8077. continue;
  8078. }
  8079. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8080. if ($n !== '') {
  8081. $colNames[$n] = true;
  8082. }
  8083. }
  8084. if (isset($colNames['updatetime'])) {
  8085. $data['updatetime'] = $now;
  8086. }
  8087. if (isset($colNames['createtime'])) {
  8088. $data['createtime'] = $now;
  8089. }
  8090. Db::table('purchase_sms_template')->insert($data);
  8091. } catch (\Throwable $e) {
  8092. // ignore
  8093. }
  8094. }
  8095. /**
  8096. * 询价多选字段:数组或字符串统一为顿号拼接
  8097. *
  8098. * @param mixed $raw
  8099. */
  8100. protected function joinRfqMultiSelectValues($raw): string
  8101. {
  8102. $parts = [];
  8103. if (is_array($raw)) {
  8104. foreach ($raw as $item) {
  8105. if (is_array($item)) {
  8106. continue;
  8107. }
  8108. $v = trim((string)$item);
  8109. if ($v !== '') {
  8110. $parts[] = $v;
  8111. }
  8112. }
  8113. } else {
  8114. $s = trim((string)$raw);
  8115. if ($s !== '') {
  8116. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8117. $v = trim((string)$piece);
  8118. if ($v !== '') {
  8119. $parts[] = $v;
  8120. }
  8121. }
  8122. }
  8123. }
  8124. $parts = array_values(array_unique($parts));
  8125. return implode('、', $parts);
  8126. }
  8127. /**
  8128. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8129. *
  8130. * @return string[]
  8131. */
  8132. protected function loadRfqSupplierNameOptions(): array
  8133. {
  8134. $out = [];
  8135. try {
  8136. $rows = Db::table('customer')
  8137. ->where(function ($q) {
  8138. $q->where('status', 1)
  8139. ->whereOr('status', '1')
  8140. ->whereOr('status', '')
  8141. ->whereNull('status');
  8142. })
  8143. ->order('id', 'desc')
  8144. ->column('company_name');
  8145. } catch (\Throwable $e) {
  8146. return [];
  8147. }
  8148. if (!is_array($rows)) {
  8149. return [];
  8150. }
  8151. foreach ($rows as $name) {
  8152. $name = trim((string)$name);
  8153. if ($name === '' || isset($out[$name])) {
  8154. continue;
  8155. }
  8156. $out[$name] = $name;
  8157. }
  8158. return array_values($out);
  8159. }
  8160. /**
  8161. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8162. */
  8163. protected function rfqNotifySalesmanAuthGroupId(): int
  8164. {
  8165. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8166. if ($id > 0) {
  8167. return $id;
  8168. }
  8169. try {
  8170. $found = Db::name('auth_group')
  8171. ->where('name', '业务员')
  8172. ->where('status', 'normal')
  8173. ->order('id', 'asc')
  8174. ->value('id');
  8175. $id = (int)$found;
  8176. } catch (\Throwable $e) {
  8177. $id = 0;
  8178. }
  8179. return $id > 0 ? $id : 12;
  8180. }
  8181. /**
  8182. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8183. *
  8184. * @return string[]
  8185. */
  8186. protected function loadRfqSalesmanNameOptions(): array
  8187. {
  8188. $out = [];
  8189. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8190. if ($groupId <= 0) {
  8191. return [];
  8192. }
  8193. try {
  8194. $adminIds = Db::name('auth_group_access')
  8195. ->where('group_id', $groupId)
  8196. ->column('uid');
  8197. } catch (\Throwable $e) {
  8198. return [];
  8199. }
  8200. $adminIds = is_array($adminIds)
  8201. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8202. : [];
  8203. if ($adminIds === []) {
  8204. return [];
  8205. }
  8206. try {
  8207. $rows = Db::name('admin')
  8208. ->where('status', 'normal')
  8209. ->where('id', 'in', $adminIds)
  8210. ->order('id', 'asc')
  8211. ->field('id,nickname,username')
  8212. ->select();
  8213. } catch (\Throwable $e) {
  8214. return [];
  8215. }
  8216. if (!is_array($rows)) {
  8217. return [];
  8218. }
  8219. foreach ($rows as $row) {
  8220. if (!is_array($row)) {
  8221. continue;
  8222. }
  8223. $name = trim((string)($row['nickname'] ?? ''));
  8224. if ($name === '') {
  8225. $name = trim((string)($row['username'] ?? ''));
  8226. }
  8227. if ($name === '' || isset($out[$name])) {
  8228. continue;
  8229. }
  8230. $out[$name] = $name;
  8231. }
  8232. return array_values($out);
  8233. }
  8234. /**
  8235. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8236. *
  8237. * @return string[]
  8238. */
  8239. protected function loadRfqDeptNameOptions(): array
  8240. {
  8241. $out = [];
  8242. // ERP 承揽部门(主来源)
  8243. try {
  8244. $vals = Db::table('mcyd')
  8245. ->where('CCLBMMC', '<>', '')
  8246. ->whereNotNull('CCLBMMC')
  8247. ->distinct(true)
  8248. ->limit(300)
  8249. ->column('CCLBMMC');
  8250. } catch (\Throwable $e) {
  8251. $vals = [];
  8252. }
  8253. if (is_array($vals)) {
  8254. foreach ($vals as $v) {
  8255. $v = trim((string)$v);
  8256. if ($v === '' || isset($out[$v])) {
  8257. continue;
  8258. }
  8259. $out[$v] = $v;
  8260. }
  8261. }
  8262. // 手工询价历史部门补全
  8263. try {
  8264. $poVals = Db::table('purchase_order')
  8265. ->where('CCLBMMC', '<>', '')
  8266. ->whereNotNull('CCLBMMC')
  8267. ->distinct(true)
  8268. ->limit(200)
  8269. ->column('CCLBMMC');
  8270. } catch (\Throwable $e) {
  8271. $poVals = [];
  8272. }
  8273. if (is_array($poVals)) {
  8274. foreach ($poVals as $v) {
  8275. $v = trim((string)$v);
  8276. if ($v === '' || isset($out[$v])) {
  8277. continue;
  8278. }
  8279. $out[$v] = $v;
  8280. }
  8281. }
  8282. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8283. if (!isset($out[$preset])) {
  8284. $out[$preset] = $preset;
  8285. }
  8286. }
  8287. $list = array_values($out);
  8288. // 常用部门靠前
  8289. usort($list, static function ($a, $b) {
  8290. $weight = [
  8291. '营销中心' => 1,
  8292. '业务部' => 2,
  8293. '市场部' => 3,
  8294. '外贸部' => 4,
  8295. '新华技术业务部' => 5,
  8296. ];
  8297. $wa = $weight[$a] ?? 100;
  8298. $wb = $weight[$b] ?? 100;
  8299. if ($wa !== $wb) {
  8300. return $wa <=> $wb;
  8301. }
  8302. return strcmp((string)$a, (string)$b);
  8303. });
  8304. return $list;
  8305. }
  8306. /**
  8307. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8308. */
  8309. public function add()
  8310. {
  8311. if ($this->request->isPost()) {
  8312. $params = $this->request->post('row/a');
  8313. if (!is_array($params)) {
  8314. $this->error(__('Parameter %s can not be empty', ''));
  8315. }
  8316. [, $adminName] = $this->GetUseName();
  8317. $params['cywyxm'] = $adminName;
  8318. try {
  8319. $sid = $this->saveManualPickOrder($params);
  8320. } catch (\InvalidArgumentException $e) {
  8321. $this->error($e->getMessage());
  8322. } catch (\Throwable $e) {
  8323. $this->error($e->getMessage());
  8324. }
  8325. $this->success('新增成功', '', [
  8326. 'scydgy_id' => $sid,
  8327. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8328. ]);
  8329. }
  8330. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8331. [, $adminName] = $this->GetUseName();
  8332. $this->view->assign('adminNickname', $adminName);
  8333. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8334. $this->view->assign('defaultCclbmmc', '营销中心');
  8335. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8336. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8337. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8338. return $this->view->fetch();
  8339. }
  8340. /**
  8341. * 业务员新增进度查询(手工询价;发起人 / 通知业务员可见,超管看全部)
  8342. */
  8343. public function rfqlist()
  8344. {
  8345. $this->relationSearch = false;
  8346. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8347. $this->request->filter(['strip_tags', 'trim']);
  8348. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8349. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8350. $this->ensureRfqSalesmanEmailTemplate();
  8351. if ($this->request->isAjax()) {
  8352. try {
  8353. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8354. $limit = max(10, min(500, (int)$limit));
  8355. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8356. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8357. $filterYm = date('Y-m');
  8358. }
  8359. $applyFilters = function ($query) use ($where, $filterYm) {
  8360. $query->where('scydgy_id', '<', 0);
  8361. $this->applyPurchaseOrderNotDeletedWhere($query);
  8362. $this->applyManualRfqViewerWhere($query);
  8363. $this->applyRfqListMonthFilter($query, $filterYm);
  8364. if (!empty($where)) {
  8365. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8366. $safeWhere = [];
  8367. $skipFields = [
  8368. 'supplier_name' => true,
  8369. 'progress_text' => true,
  8370. 'createtime_text' => true,
  8371. 'notify_time_text' => true,
  8372. 'can_notify_salesman' => true,
  8373. 'has_issued' => true,
  8374. 'has_quoted' => true,
  8375. ];
  8376. foreach ((array)$where as $cond) {
  8377. if (!is_array($cond) || !isset($cond[0])) {
  8378. continue;
  8379. }
  8380. $field = (string)$cond[0];
  8381. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8382. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8383. if (isset($skipFields[$fieldBase])) {
  8384. continue;
  8385. }
  8386. if ($fieldBase === 'supplier_name') {
  8387. continue;
  8388. }
  8389. $safeWhere[] = $cond;
  8390. }
  8391. if ($safeWhere !== []) {
  8392. $query->where($safeWhere);
  8393. }
  8394. }
  8395. };
  8396. $countQuery = Db::table('purchase_order');
  8397. $applyFilters($countQuery);
  8398. $total = (int)$countQuery->count();
  8399. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8400. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8401. $listQuery = Db::table('purchase_order');
  8402. $applyFilters($listQuery);
  8403. $rows = $listQuery
  8404. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cGzzxMc,pick_company_name,cywyxm,notify_salesman,rfq_salesman_notified,rfq_salesman_notify_time,MBZ,createtime,dStamp,status,wflow_status')
  8405. ->order($sortField, $orderDir)
  8406. ->limit($offset, $limit)
  8407. ->select();
  8408. if (!is_array($rows)) {
  8409. $rows = [];
  8410. }
  8411. $sidList = [];
  8412. foreach ($rows as $r) {
  8413. if (!is_array($r)) {
  8414. continue;
  8415. }
  8416. $sid = (int)($r['scydgy_id'] ?? 0);
  8417. if ($sid < 0) {
  8418. $sidList[$sid] = true;
  8419. }
  8420. }
  8421. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8422. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8423. $out = [];
  8424. foreach ($rows as $r) {
  8425. if (!is_array($r)) {
  8426. continue;
  8427. }
  8428. $sid = (int)($r['scydgy_id'] ?? 0);
  8429. if ($sid >= 0) {
  8430. continue;
  8431. }
  8432. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8433. if ($createdText === '') {
  8434. $createdText = trim((string)($r['dStamp'] ?? ''));
  8435. }
  8436. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8437. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8438. if ($supplier === '') {
  8439. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8440. }
  8441. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8442. || isset($issuedSidSet[$sid]);
  8443. $hasQuoted = isset($quotedSidSet[$sid]);
  8444. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8445. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8446. $out[] = [
  8447. 'id' => (int)($r['id'] ?? 0),
  8448. 'scydgy_id' => $sid,
  8449. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8450. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8451. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8452. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8453. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8454. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8455. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8456. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8457. 'supplier_name' => $supplier,
  8458. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8459. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8460. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8461. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8462. 'notify_time_text' => $notifyTimeText,
  8463. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8464. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8465. 'has_issued' => $hasIssued ? 1 : 0,
  8466. 'has_quoted' => $hasQuoted ? 1 : 0,
  8467. 'can_notify_salesman' => $canNotifySalesman,
  8468. 'createtime' => $r['createtime'] ?? null,
  8469. 'createtime_text' => $createdText,
  8470. ];
  8471. }
  8472. return json(['total' => $total, 'rows' => $out]);
  8473. } catch (\Throwable $e) {
  8474. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8475. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8476. }
  8477. }
  8478. $sidebar = $this->loadRfqSidebarYearMonths();
  8479. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8480. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8481. [, $adminName] = $this->GetUseName();
  8482. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8483. $this->view->assign('adminNickname', $adminName);
  8484. $this->view->assign('defaultYm', $defaultYm);
  8485. $this->view->assign('sidebarYearMonths', $sidebar);
  8486. return $this->view->fetch('procuremen/rfqlist');
  8487. }
  8488. /**
  8489. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8490. *
  8491. * @param array<int, array{year:string, months:array}> $sidebar
  8492. */
  8493. protected function resolveRfqListDefaultYm(array $sidebar): string
  8494. {
  8495. $current = date('Y-m');
  8496. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8497. if (in_array($current, $yms, true)) {
  8498. return $current;
  8499. }
  8500. if ($yms !== []) {
  8501. rsort($yms, SORT_STRING);
  8502. return (string)$yms[0];
  8503. }
  8504. return $current;
  8505. }
  8506. /**
  8507. * 手工询价列表左侧月份(按 createtime / dStamp)
  8508. *
  8509. * @return array<int, array{year:string, months:array}>
  8510. */
  8511. protected function loadRfqSidebarYearMonths(): array
  8512. {
  8513. $ymSet = [];
  8514. try {
  8515. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8516. $this->applyPurchaseOrderNotDeletedWhere($q);
  8517. $this->applyManualRfqViewerWhere($q);
  8518. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8519. } catch (\Throwable $e) {
  8520. $rows = [];
  8521. }
  8522. if (!is_array($rows)) {
  8523. $rows = [];
  8524. }
  8525. foreach ($rows as $r) {
  8526. if (!is_array($r)) {
  8527. continue;
  8528. }
  8529. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8530. if ($t === '') {
  8531. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8532. }
  8533. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8534. $ymSet[$m[1] . '-' . $m[2]] = true;
  8535. }
  8536. }
  8537. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8538. }
  8539. /**
  8540. * 手工询价可见范围:仅「需求发起人」或「通知业务员」与当前登录账号一致(超管看全部)
  8541. */
  8542. protected function applyManualRfqViewerWhere($query): void
  8543. {
  8544. if ($this->auth->isSuperAdmin()) {
  8545. return;
  8546. }
  8547. [, $adminName] = $this->GetUseName();
  8548. $adminName = trim((string)$adminName);
  8549. if ($adminName === '') {
  8550. $query->whereRaw('1 = 0');
  8551. return;
  8552. }
  8553. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8554. $query->where(function ($q) use ($adminName) {
  8555. $q->where('cywyxm', $adminName)
  8556. ->whereOr('notify_salesman', $adminName)
  8557. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8558. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8559. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8560. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8561. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8562. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8563. });
  8564. }
  8565. /**
  8566. * 当前用户是否可查看/操作该手工询价单(需求发起人或通知业务员;超管全部)
  8567. */
  8568. protected function canViewManualRfqOrder(array $po): bool
  8569. {
  8570. if ($this->auth->isSuperAdmin()) {
  8571. return true;
  8572. }
  8573. [, $adminName] = $this->GetUseName();
  8574. $adminName = trim((string)$adminName);
  8575. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8576. return true;
  8577. }
  8578. if ($adminName !== '') {
  8579. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8580. if ($n === $adminName) {
  8581. return true;
  8582. }
  8583. }
  8584. }
  8585. return false;
  8586. }
  8587. /**
  8588. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8589. */
  8590. protected function applyRfqListMonthFilter($query, string $ym): void
  8591. {
  8592. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8593. $ym = date('Y-m');
  8594. }
  8595. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8596. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8597. $query->whereRaw(
  8598. "("
  8599. . "CASE "
  8600. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8601. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8602. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8603. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8604. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8605. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8606. . "END"
  8607. . ") LIKE '{$ymEsc}-%'"
  8608. );
  8609. }
  8610. /**
  8611. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8612. */
  8613. public function rfqlistDetails()
  8614. {
  8615. return $this->details();
  8616. }
  8617. /**
  8618. * 查询询价 — 弹窗:列出本单「通知业务员」姓名与邮箱
  8619. */
  8620. public function rfqnotifysalesmen()
  8621. {
  8622. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen'])) {
  8623. $this->error(__('You have no permission'));
  8624. }
  8625. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8626. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8627. $sid = (int)$this->request->param('scydgy_id', 0);
  8628. if ($sid >= 0) {
  8629. $this->error('仅支持手工新增询价单');
  8630. }
  8631. $po = $this->loadManualRfqOrderForNotify($sid);
  8632. $names = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8633. $list = $this->resolveRfqSalesmanContactRows($names);
  8634. $canNotify = $this->canRfqNotifySalesman($po);
  8635. $this->success('', null, [
  8636. 'scydgy_id' => $sid,
  8637. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8638. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8639. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8640. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8641. 'list' => $list,
  8642. ]);
  8643. }
  8644. /**
  8645. * 查询询价 — 邮箱通知业务员(支持单人 / 全部 notify_all=1)
  8646. */
  8647. public function rfqnotifysalesman()
  8648. {
  8649. if (!$this->request->isPost()) {
  8650. $this->error(__('Invalid parameters'));
  8651. }
  8652. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman'])) {
  8653. $this->error(__('You have no permission'));
  8654. }
  8655. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8656. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8657. $sid = (int)$this->request->post('scydgy_id', 0);
  8658. $notifyAll = (int)$this->request->post('notify_all', 0) === 1;
  8659. $adminId = (int)$this->request->post('admin_id', 0);
  8660. $name = trim((string)$this->request->post('name', ''));
  8661. if ($sid >= 0) {
  8662. $this->error('仅支持手工新增询价单');
  8663. }
  8664. $po = $this->loadManualRfqOrderForNotify($sid);
  8665. $this->assertRfqCanNotifySalesman($po);
  8666. $allowed = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8667. if ($allowed === []) {
  8668. $this->error('该订单未指定通知业务员');
  8669. }
  8670. $allContacts = $this->resolveRfqSalesmanContactRows($allowed);
  8671. $targets = [];
  8672. if ($notifyAll) {
  8673. foreach ($allContacts as $row) {
  8674. $em = trim((string)($row['email'] ?? ''));
  8675. if ($em !== '' && filter_var($em, FILTER_VALIDATE_EMAIL)) {
  8676. $targets[] = $row;
  8677. }
  8678. }
  8679. if ($targets === []) {
  8680. $this->error('名单中业务员均未填写有效邮箱');
  8681. }
  8682. } else {
  8683. $contact = null;
  8684. if ($adminId > 0) {
  8685. foreach ($allContacts as $row) {
  8686. if ((int)($row['admin_id'] ?? 0) === $adminId) {
  8687. $contact = $row;
  8688. break;
  8689. }
  8690. }
  8691. }
  8692. if ($contact === null && $name !== '') {
  8693. foreach ($allContacts as $row) {
  8694. if (trim((string)($row['name'] ?? '')) === $name) {
  8695. $contact = $row;
  8696. break;
  8697. }
  8698. }
  8699. }
  8700. if ($contact === null) {
  8701. $this->error('业务员不在本单通知名单中');
  8702. }
  8703. $toEmail = trim((string)($contact['email'] ?? ''));
  8704. $toName = trim((string)($contact['name'] ?? ''));
  8705. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  8706. $this->error(($toName !== '' ? $toName : '该业务员') . ' 未填写有效邮箱');
  8707. }
  8708. $targets[] = $contact;
  8709. }
  8710. $mailConfig = $this->loadMailerConfig();
  8711. if (empty($mailConfig['host'])) {
  8712. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8713. }
  8714. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8715. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8716. }
  8717. $this->ensureRfqSalesmanEmailTemplate();
  8718. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  8719. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  8720. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  8721. $qty = trim((string)($po['This_quantity'] ?? ''));
  8722. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  8723. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  8724. if ($supplier === '') {
  8725. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  8726. }
  8727. try {
  8728. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  8729. } catch (\Throwable $e) {
  8730. $this->error($e->getMessage());
  8731. }
  8732. $okNames = [];
  8733. $failMsgs = [];
  8734. foreach ($targets as $contact) {
  8735. $toEmail = trim((string)($contact['email'] ?? ''));
  8736. $toName = trim((string)($contact['name'] ?? ''));
  8737. $notifyVars = [
  8738. 'contact_name' => $toName,
  8739. 'salesman_name' => $toName,
  8740. 'company_name' => $toName,
  8741. 'email' => $toEmail,
  8742. 'ccydh' => $ccydh,
  8743. 'cyjmc' => $cyjmc,
  8744. 'cgymc' => $cgymc,
  8745. 'this_quantity' => $qty,
  8746. 'supplier_name' => $supplier,
  8747. 'cywyxm' => $cywyxm,
  8748. ];
  8749. try {
  8750. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  8751. $mailSubject = $mailSubjectTpl;
  8752. foreach ($notifyVars as $k => $v) {
  8753. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  8754. }
  8755. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  8756. $mailSubject = trim((string)$mailSubject);
  8757. if ($mailSubject === '') {
  8758. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  8759. }
  8760. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8761. $bundle = [
  8762. 'company_name' => $toName,
  8763. 'email' => $toEmail,
  8764. 'mail_plain' => $mailPlain,
  8765. 'mail_body' => $mailBody,
  8766. 'ccydh' => $ccydh,
  8767. 'email_log_scene' => 'rfq_salesman',
  8768. 'email_log_scydgy_id' => $sid,
  8769. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  8770. 'notify_vars' => $notifyVars,
  8771. ];
  8772. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  8773. $okNames[] = $toName . '(' . $toEmail . ')';
  8774. } catch (\Throwable $e) {
  8775. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  8776. }
  8777. }
  8778. if ($okNames === []) {
  8779. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  8780. }
  8781. $now = date('Y-m-d H:i:s');
  8782. try {
  8783. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8784. 'rfq_salesman_notified' => 1,
  8785. 'rfq_salesman_notify_time' => $now,
  8786. ]);
  8787. } catch (\Throwable $e) {
  8788. // ignore
  8789. }
  8790. $this->addOrderLog(
  8791. $sid,
  8792. 'rfq_notify_salesman',
  8793. '邮箱通知业务员:' . implode('、', $okNames),
  8794. (int)($po['id'] ?? 0)
  8795. );
  8796. $msg = '已通知 ' . count($okNames) . ' 人';
  8797. if ($failMsgs !== []) {
  8798. $msg .= ';部分失败:' . implode(';', $failMsgs);
  8799. }
  8800. $this->success($msg, null, [
  8801. 'scydgy_id' => $sid,
  8802. 'rfq_salesman_notified' => 1,
  8803. 'rfq_salesman_notify_time' => $now,
  8804. 'notify_time_text' => $now,
  8805. 'ok_count' => count($okNames),
  8806. 'fail_count' => count($failMsgs),
  8807. ]);
  8808. }
  8809. /**
  8810. * 查询询价 — 下发前:返回将通知的供应商表格数据
  8811. */
  8812. public function rfqissuesuppliers()
  8813. {
  8814. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers'])) {
  8815. $this->error(__('You have no permission'));
  8816. }
  8817. $sid = (int)$this->request->param('scydgy_id', 0);
  8818. if ($sid >= 0) {
  8819. $this->error('仅支持手工新增询价单');
  8820. }
  8821. $po = $this->loadManualRfqOrderForNotify($sid);
  8822. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  8823. if ($supplierRaw === '') {
  8824. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  8825. }
  8826. $names = $this->splitRfqSalesmanNames($supplierRaw);
  8827. $list = [];
  8828. foreach ($names as $name) {
  8829. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  8830. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  8831. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  8832. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  8833. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  8834. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  8835. $list[] = [
  8836. 'name' => $name,
  8837. 'username' => $username,
  8838. 'email' => $email,
  8839. 'phone' => $phone,
  8840. 'can_notify' => $okEmail ? 1 : 0,
  8841. 'found' => is_array($contact) ? 1 : 0,
  8842. ];
  8843. }
  8844. $this->success('', null, [
  8845. 'scydgy_id' => $sid,
  8846. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8847. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  8848. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  8849. 'CDW' => trim((string)($po['CDW'] ?? '')),
  8850. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  8851. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  8852. 'CDF' => trim((string)($po['CDF'] ?? '')),
  8853. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  8854. 'list' => $list,
  8855. ]);
  8856. }
  8857. /**
  8858. * 查询询价 — 补加供应商可选名单
  8859. */
  8860. public function rfqsupplieroptions()
  8861. {
  8862. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  8863. $this->error(__('You have no permission'));
  8864. }
  8865. $names = array_values($this->loadRfqSupplierNameOptions());
  8866. $out = [];
  8867. foreach ($names as $name) {
  8868. $out[] = ['name' => $name];
  8869. }
  8870. $this->success('', null, ['list' => $out]);
  8871. }
  8872. /**
  8873. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  8874. */
  8875. public function rfqappendsuppliers()
  8876. {
  8877. if (!$this->request->isPost()) {
  8878. $this->error(__('Invalid parameters'));
  8879. }
  8880. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers'])) {
  8881. $this->error(__('You have no permission'));
  8882. }
  8883. $sid = (int)$this->request->post('scydgy_id', 0);
  8884. if ($sid >= 0) {
  8885. $this->error('仅支持手工新增询价单');
  8886. }
  8887. $po = $this->loadManualRfqOrderForNotify($sid);
  8888. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8889. $this->error('订单已完结,无法补加供应商');
  8890. }
  8891. $raw = $this->request->post('suppliers/a', []);
  8892. if (!is_array($raw) || $raw === []) {
  8893. $suppliersJson = $this->request->post('suppliers_json', '');
  8894. if (is_string($suppliersJson) && $suppliersJson !== '') {
  8895. $decoded = json_decode($suppliersJson, true);
  8896. $raw = is_array($decoded) ? $decoded : [];
  8897. }
  8898. }
  8899. $addNames = [];
  8900. foreach ((array)$raw as $item) {
  8901. if (is_array($item)) {
  8902. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  8903. } else {
  8904. $n = trim((string)$item);
  8905. }
  8906. if ($n !== '') {
  8907. $addNames[] = $n;
  8908. }
  8909. }
  8910. $addNames = array_values(array_unique($addNames));
  8911. if ($addNames === []) {
  8912. $this->error('请选择要补加的供应商');
  8913. }
  8914. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  8915. if ($existingRaw === '') {
  8916. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  8917. }
  8918. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8919. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8920. try {
  8921. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  8922. } catch (\Throwable $e) {
  8923. $this->error('保存失败:' . $e->getMessage());
  8924. }
  8925. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8926. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8927. $this->success('已补加供应商', null, [
  8928. 'scydgy_id' => $sid,
  8929. 'cGzzxMc' => $mergedStr,
  8930. 'added_count' => count($addNames),
  8931. ]);
  8932. }
  8933. /**
  8934. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  8935. */
  8936. public function rfqissue()
  8937. {
  8938. if (!$this->request->isPost()) {
  8939. $this->error(__('Invalid parameters'));
  8940. }
  8941. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue'])) {
  8942. $this->error(__('You have no permission'));
  8943. }
  8944. $sid = (int)$this->request->post('scydgy_id', 0);
  8945. if ($sid >= 0) {
  8946. $this->error('仅支持手工新增询价单');
  8947. }
  8948. $po = $this->loadManualRfqOrderForNotify($sid);
  8949. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8950. $this->error('订单已完结,无法下发');
  8951. }
  8952. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  8953. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  8954. $this->error('订单已进入后续流程,无法再下发');
  8955. }
  8956. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  8957. if ($supplierRaw === '') {
  8958. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  8959. }
  8960. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  8961. if ($supplierNames === []) {
  8962. $this->error('请先在新增询价时选择供应商');
  8963. }
  8964. $companies = [];
  8965. $missing = [];
  8966. $noEmail = [];
  8967. foreach ($supplierNames as $name) {
  8968. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  8969. if ($contact === null) {
  8970. $missing[] = $name;
  8971. continue;
  8972. }
  8973. $em = trim((string)($contact['email'] ?? ''));
  8974. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  8975. $noEmail[] = $name;
  8976. continue;
  8977. }
  8978. $companies[] = $contact;
  8979. }
  8980. if ($missing !== []) {
  8981. $this->error('未找到供应商档案:' . implode('、', $missing));
  8982. }
  8983. if ($noEmail !== []) {
  8984. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  8985. }
  8986. if ($companies === []) {
  8987. $this->error('没有可通知的供应商');
  8988. }
  8989. $mailConfig = $this->loadMailerConfig();
  8990. if (empty($mailConfig['host'])) {
  8991. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8992. }
  8993. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8994. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8995. }
  8996. $mergeRow = $po;
  8997. $mergeRow['ID'] = $sid;
  8998. $mergeRow['id'] = $sid;
  8999. $mergeRows = [$mergeRow];
  9000. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9001. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9002. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9003. }
  9004. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9005. $issueTime = date('Y-m-d H:i:s');
  9006. $nameLabels = [];
  9007. foreach ($companies as $c) {
  9008. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9009. }
  9010. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9011. Db::startTrans();
  9012. try {
  9013. $this->upsertPurchaseOrderFromRow(
  9014. $mergeRow,
  9015. $sysRqDb,
  9016. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9017. $issueTime,
  9018. $po,
  9019. null,
  9020. $scoreRule
  9021. );
  9022. foreach ($companies as $c) {
  9023. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9024. }
  9025. Db::commit();
  9026. } catch (\Throwable $e) {
  9027. Db::rollback();
  9028. $this->error($e->getMessage());
  9029. }
  9030. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9031. if ($poId <= 0) {
  9032. try {
  9033. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9034. } catch (\Throwable $e) {
  9035. $poId = 0;
  9036. }
  9037. }
  9038. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9039. $posNotify = [];
  9040. try {
  9041. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9042. if (is_array($fresh)) {
  9043. $fresh['sys_rq'] = $sysRqDb;
  9044. $posNotify = [$fresh];
  9045. }
  9046. } catch (\Throwable $e) {
  9047. $posNotify = [$po];
  9048. $posNotify[0]['sys_rq'] = $sysRqDb;
  9049. }
  9050. $notifyBundle = [
  9051. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9052. 'pos' => $posNotify,
  9053. 'merge_rows' => $mergeRows,
  9054. ];
  9055. $notifyErrors = [];
  9056. foreach ($companies as $c) {
  9057. $cname = trim((string)($c['name'] ?? ''));
  9058. try {
  9059. // 询价下发:仅邮箱通知供应商
  9060. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9061. } catch (\Throwable $e) {
  9062. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9063. }
  9064. }
  9065. if ($notifyErrors !== []) {
  9066. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9067. }
  9068. $this->success('已询价并邮件通知供应商', null, [
  9069. 'scydgy_id' => $sid,
  9070. 'progress_text' => '待报价',
  9071. 'supplier_count' => count($companies),
  9072. ]);
  9073. }
  9074. /**
  9075. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9076. */
  9077. public function rfqissuesendmail()
  9078. {
  9079. if (!$this->request->isPost()) {
  9080. $this->error(__('Invalid parameters'));
  9081. }
  9082. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail'])) {
  9083. $this->error(__('You have no permission'));
  9084. }
  9085. $sid = (int)$this->request->post('scydgy_id', 0);
  9086. $companyName = trim((string)$this->request->post('company_name', ''));
  9087. if ($sid >= 0) {
  9088. $this->error('仅支持手工新增询价单');
  9089. }
  9090. if ($companyName === '') {
  9091. $this->error('请选择供应商');
  9092. }
  9093. $po = $this->loadManualRfqOrderForNotify($sid);
  9094. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9095. $this->error('订单已完结,无法发送');
  9096. }
  9097. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9098. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9099. $this->error('订单已进入后续流程,无法再发送');
  9100. }
  9101. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9102. if ($contact === null) {
  9103. $this->error('未找到供应商档案:' . $companyName);
  9104. }
  9105. $email = trim((string)($contact['email'] ?? ''));
  9106. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9107. $this->error('该供应商未填写有效邮箱');
  9108. }
  9109. $mailConfig = $this->loadMailerConfig();
  9110. if (empty($mailConfig['host'])) {
  9111. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9112. }
  9113. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9114. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9115. }
  9116. $mergeRow = $po;
  9117. $mergeRow['ID'] = $sid;
  9118. $mergeRow['id'] = $sid;
  9119. $mergeRows = [$mergeRow];
  9120. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9121. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9122. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9123. }
  9124. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9125. $issueTime = date('Y-m-d H:i:s');
  9126. Db::startTrans();
  9127. try {
  9128. $this->upsertPurchaseOrderFromRow(
  9129. $mergeRow,
  9130. $sysRqDb,
  9131. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9132. $issueTime,
  9133. $po,
  9134. null,
  9135. $scoreRule
  9136. );
  9137. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9138. Db::commit();
  9139. } catch (\Throwable $e) {
  9140. Db::rollback();
  9141. $this->error($e->getMessage());
  9142. }
  9143. $posNotify = [];
  9144. try {
  9145. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9146. if (is_array($fresh)) {
  9147. $fresh['sys_rq'] = $sysRqDb;
  9148. $posNotify = [$fresh];
  9149. }
  9150. } catch (\Throwable $e) {
  9151. $posNotify = [$po];
  9152. $posNotify[0]['sys_rq'] = $sysRqDb;
  9153. }
  9154. $notifyBundle = [
  9155. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9156. 'pos' => $posNotify,
  9157. 'merge_rows' => $mergeRows,
  9158. ];
  9159. try {
  9160. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9161. } catch (\Throwable $e) {
  9162. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9163. }
  9164. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9165. if ($poId <= 0) {
  9166. try {
  9167. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9168. } catch (\Throwable $e) {
  9169. $poId = 0;
  9170. }
  9171. }
  9172. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9173. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9174. 'scydgy_id' => $sid,
  9175. 'company_name' => $companyName,
  9176. ]);
  9177. }
  9178. /**
  9179. * 查询询价 — 查看各供应商报价(单价)
  9180. */
  9181. public function rfqquotes()
  9182. {
  9183. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue'])) {
  9184. $this->error(__('You have no permission'));
  9185. }
  9186. $sid = (int)$this->request->param('scydgy_id', 0);
  9187. if ($sid >= 0) {
  9188. $this->error('仅支持手工新增询价单');
  9189. }
  9190. $po = $this->loadManualRfqOrderForNotify($sid);
  9191. $rows = [];
  9192. try {
  9193. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9194. $q = Db::table('purchase_order_detail')
  9195. ->where('scydgy_id', $sid)
  9196. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9197. ->order('id', 'asc');
  9198. $this->applyActivePurchaseOrderDetailWhere($q);
  9199. $rows = $q->select();
  9200. } catch (\Throwable $e) {
  9201. try {
  9202. $q = Db::table('purchase_order_detail')
  9203. ->where('scydgy_id', $sid)
  9204. ->order('id', 'asc');
  9205. $this->applyActivePurchaseOrderDetailWhere($q);
  9206. $rows = $q->select();
  9207. } catch (\Throwable $e2) {
  9208. $rows = [];
  9209. }
  9210. }
  9211. if (!is_array($rows)) {
  9212. $rows = [];
  9213. }
  9214. $list = [];
  9215. foreach ($rows as $row) {
  9216. if (!is_array($row)) {
  9217. continue;
  9218. }
  9219. $amount = trim((string)($row['amount'] ?? ''));
  9220. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9221. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9222. $oper = '';
  9223. if ($isQuoted) {
  9224. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9225. if ($oper === '') {
  9226. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9227. }
  9228. }
  9229. $list[] = [
  9230. 'id' => (int)($row['id'] ?? 0),
  9231. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9232. 'amount' => $amount,
  9233. 'amount_text' => $isQuoted ? $amount : '',
  9234. 'is_quoted' => $isQuoted,
  9235. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9236. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9237. 'oper_time' => $oper,
  9238. ];
  9239. }
  9240. $this->success('', null, [
  9241. 'scydgy_id' => $sid,
  9242. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9243. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9244. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9245. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9246. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9247. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9248. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9249. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9250. 'list' => $list,
  9251. ]);
  9252. }
  9253. /**
  9254. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9255. */
  9256. protected function isRfqOrderIssued(array $po): bool
  9257. {
  9258. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9259. return true;
  9260. }
  9261. $sid = (int)($po['scydgy_id'] ?? 0);
  9262. if ($sid >= 0) {
  9263. return false;
  9264. }
  9265. try {
  9266. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9267. $this->applyActivePurchaseOrderDetailWhere($q);
  9268. return (int)$q->count() > 0;
  9269. } catch (\Throwable $e) {
  9270. return false;
  9271. }
  9272. }
  9273. /**
  9274. * 批量:已有下发明细的手工询价 scydgy_id
  9275. *
  9276. * @param int[] $scydgyIds
  9277. * @return array<int, bool>
  9278. */
  9279. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9280. {
  9281. $set = [];
  9282. $ids = [];
  9283. foreach ($scydgyIds as $sid) {
  9284. $sid = (int)$sid;
  9285. if ($sid < 0) {
  9286. $ids[$sid] = true;
  9287. }
  9288. }
  9289. if ($ids === []) {
  9290. return $set;
  9291. }
  9292. try {
  9293. $q = Db::table('purchase_order_detail')
  9294. ->where('scydgy_id', 'in', array_keys($ids))
  9295. ->field('scydgy_id');
  9296. $this->applyActivePurchaseOrderDetailWhere($q);
  9297. $rows = $q->select();
  9298. } catch (\Throwable $e) {
  9299. return $set;
  9300. }
  9301. if (!is_array($rows)) {
  9302. return $set;
  9303. }
  9304. foreach ($rows as $row) {
  9305. if (!is_array($row)) {
  9306. continue;
  9307. }
  9308. $sid = (int)($row['scydgy_id'] ?? 0);
  9309. if ($sid < 0) {
  9310. $set[$sid] = true;
  9311. }
  9312. }
  9313. return $set;
  9314. }
  9315. /**
  9316. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9317. *
  9318. * @param int[] $scydgyIds
  9319. * @return array<int, bool>
  9320. */
  9321. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9322. {
  9323. $set = [];
  9324. $ids = [];
  9325. foreach ($scydgyIds as $sid) {
  9326. $sid = (int)$sid;
  9327. if ($sid < 0) {
  9328. $ids[$sid] = true;
  9329. }
  9330. }
  9331. if ($ids === []) {
  9332. return $set;
  9333. }
  9334. try {
  9335. $q = Db::table('purchase_order_detail')
  9336. ->where('scydgy_id', 'in', array_keys($ids))
  9337. ->field('scydgy_id,amount');
  9338. $this->applyActivePurchaseOrderDetailWhere($q);
  9339. $rows = $q->select();
  9340. } catch (\Throwable $e) {
  9341. return $set;
  9342. }
  9343. if (!is_array($rows)) {
  9344. return $set;
  9345. }
  9346. foreach ($rows as $row) {
  9347. if (!is_array($row)) {
  9348. continue;
  9349. }
  9350. $amount = trim((string)($row['amount'] ?? ''));
  9351. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9352. continue;
  9353. }
  9354. $sid = (int)($row['scydgy_id'] ?? 0);
  9355. if ($sid < 0) {
  9356. $set[$sid] = true;
  9357. }
  9358. }
  9359. return $set;
  9360. }
  9361. /**
  9362. * 已下发且至少一家供应商已报价,才允许通知业务员
  9363. */
  9364. protected function canRfqNotifySalesman(array $po): bool
  9365. {
  9366. if (!$this->isRfqOrderIssued($po)) {
  9367. return false;
  9368. }
  9369. $sid = (int)($po['scydgy_id'] ?? 0);
  9370. if ($sid >= 0) {
  9371. return false;
  9372. }
  9373. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9374. return isset($quoted[$sid]);
  9375. }
  9376. protected function assertRfqCanNotifySalesman(array $po): void
  9377. {
  9378. if (!$this->isRfqOrderIssued($po)) {
  9379. $this->error('请先询价并等待供应商报价后再通知业务员');
  9380. }
  9381. if (!$this->canRfqNotifySalesman($po)) {
  9382. $this->error('供应商尚未报价,暂不能通知业务员');
  9383. }
  9384. }
  9385. /**
  9386. * 加载手工询价单(含可见性校验)
  9387. *
  9388. * @return array<string, mixed>
  9389. */
  9390. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9391. {
  9392. try {
  9393. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9394. } catch (\Throwable $e) {
  9395. $po = null;
  9396. }
  9397. if (!is_array($po)) {
  9398. $this->error('订单不存在');
  9399. }
  9400. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9401. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9402. $this->error('订单不存在');
  9403. }
  9404. if ($this->auth->isSuperAdmin()) {
  9405. return $po;
  9406. }
  9407. if ($this->canViewManualRfqOrder($po)) {
  9408. return $po;
  9409. }
  9410. $this->error('无权操作该订单');
  9411. }
  9412. /**
  9413. * @return string[]
  9414. */
  9415. protected function splitRfqSalesmanNames(string $raw): array
  9416. {
  9417. $parts = [];
  9418. $raw = trim($raw);
  9419. if ($raw === '') {
  9420. return [];
  9421. }
  9422. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9423. $v = trim((string)$piece);
  9424. if ($v !== '' && !in_array($v, $parts, true)) {
  9425. $parts[] = $v;
  9426. }
  9427. }
  9428. return $parts;
  9429. }
  9430. /**
  9431. * 按姓名匹配 fa_admin 邮箱
  9432. *
  9433. * @param string[] $names
  9434. * @return array<int, array{admin_id:int,name:string,email:string}>
  9435. */
  9436. protected function resolveRfqSalesmanContactRows(array $names): array
  9437. {
  9438. $out = [];
  9439. foreach ($names as $name) {
  9440. $name = trim((string)$name);
  9441. if ($name === '') {
  9442. continue;
  9443. }
  9444. $adminId = 0;
  9445. $email = '';
  9446. try {
  9447. $row = Db::name('admin')
  9448. ->where(function ($q) use ($name) {
  9449. $q->where('nickname', $name)->whereOr('username', $name);
  9450. })
  9451. ->where('status', 'normal')
  9452. ->order('id', 'asc')
  9453. ->field('id,nickname,username,email')
  9454. ->find();
  9455. } catch (\Throwable $e) {
  9456. $row = null;
  9457. }
  9458. if (is_array($row)) {
  9459. $adminId = (int)($row['id'] ?? 0);
  9460. $email = trim((string)($row['email'] ?? ''));
  9461. $disp = trim((string)($row['nickname'] ?? ''));
  9462. if ($disp === '') {
  9463. $disp = trim((string)($row['username'] ?? ''));
  9464. }
  9465. if ($disp !== '') {
  9466. $name = $disp;
  9467. }
  9468. }
  9469. $out[] = [
  9470. 'admin_id' => $adminId,
  9471. 'name' => $name,
  9472. 'email' => $email,
  9473. ];
  9474. }
  9475. return $out;
  9476. }
  9477. /**
  9478. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9479. */
  9480. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9481. {
  9482. if ($scydgyId >= 0) {
  9483. return;
  9484. }
  9485. try {
  9486. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9487. } catch (\Throwable $e) {
  9488. $po = null;
  9489. }
  9490. if (!is_array($po)) {
  9491. $this->error('订单不存在');
  9492. }
  9493. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9494. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9495. $this->error('订单不存在');
  9496. }
  9497. if ($this->auth->isSuperAdmin()) {
  9498. return;
  9499. }
  9500. [, $adminName] = $this->GetUseName();
  9501. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9502. if ($cywy !== '' && $cywy === $adminName) {
  9503. return;
  9504. }
  9505. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9506. try {
  9507. if ($this->auth->check($rule)) {
  9508. return;
  9509. }
  9510. } catch (\Throwable $e) {
  9511. }
  9512. }
  9513. $this->error('无权查看该订单');
  9514. }
  9515. /**
  9516. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9517. */
  9518. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9519. {
  9520. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9521. return ProcuremenStatus::PO_COMPLETED;
  9522. }
  9523. $sid = (int)($row['scydgy_id'] ?? 0);
  9524. if ($sid < 0) {
  9525. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9526. return '已通知业务员';
  9527. }
  9528. if ($hasQuoted) {
  9529. return '供应商已报价';
  9530. }
  9531. if ($hasIssued
  9532. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9533. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9534. return '待报价';
  9535. }
  9536. try {
  9537. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9538. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9539. if ((int)$detCntQuery->count() > 0) {
  9540. return '待报价';
  9541. }
  9542. } catch (\Throwable $e) {
  9543. }
  9544. return '待询价';
  9545. }
  9546. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9547. return '待入库评分';
  9548. }
  9549. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9550. return '待采购确认';
  9551. }
  9552. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9553. return '待确认供应商';
  9554. }
  9555. return '待协助下发';
  9556. }
  9557. /**
  9558. * 协助初选列表 — 批量软删除
  9559. */
  9560. public function pickDelete()
  9561. {
  9562. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9563. $this->error(__('Invalid parameters'));
  9564. }
  9565. if (!$this->procuremenCanPickDelete()) {
  9566. $this->error(__('You have no permission'));
  9567. }
  9568. $rowsRaw = $this->request->post('rows_json', '[]');
  9569. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9570. if (!is_array($rows) || $rows === []) {
  9571. $this->error('请至少勾选一条工序');
  9572. }
  9573. $done = 0;
  9574. Db::startTrans();
  9575. try {
  9576. foreach ($rows as $row) {
  9577. if (!is_array($row)) {
  9578. continue;
  9579. }
  9580. $this->softDeleteProcuremenPickRow($row);
  9581. $done++;
  9582. }
  9583. if ($done < 1) {
  9584. throw new \Exception('没有可删除的工序');
  9585. }
  9586. Db::commit();
  9587. } catch (\InvalidArgumentException $e) {
  9588. Db::rollback();
  9589. $this->error($e->getMessage());
  9590. } catch (\Throwable $e) {
  9591. Db::rollback();
  9592. $this->error($e->getMessage());
  9593. }
  9594. $this->pickHiddenScydgySetCache = null;
  9595. $this->success('已删除 ' . $done . ' 条工序');
  9596. }
  9597. /**
  9598. * 下发 — 手工新增工序(弹窗)
  9599. */
  9600. public function pickAdd()
  9601. {
  9602. if ($this->request->isPost()) {
  9603. $params = $this->request->post('row/a');
  9604. if (!is_array($params)) {
  9605. $this->error(__('Parameter %s can not be empty', ''));
  9606. }
  9607. try {
  9608. $sid = $this->saveManualPickOrder($params);
  9609. } catch (\InvalidArgumentException $e) {
  9610. $this->error($e->getMessage());
  9611. } catch (\Throwable $e) {
  9612. $this->error($e->getMessage());
  9613. }
  9614. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  9615. }
  9616. return $this->view->fetch('procuremen/pick_add');
  9617. }
  9618. /**
  9619. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  9620. */
  9621. public function pickSubmit()
  9622. {
  9623. if (!$this->request->isPost()) {
  9624. $this->error(__('Invalid parameters'));
  9625. }
  9626. // ---------- 接口订单数据 ----------
  9627. $rowJson = $this->request->post('row_json', '');
  9628. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  9629. $companiesJson = $this->request->post('companies_json', '[]');
  9630. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  9631. $companies = json_decode($companiesJson, true);
  9632. if (!is_array($companies)) {
  9633. $this->error('供应商数据无效');
  9634. }
  9635. $issueCompanies = $this->normalizePickCompanies($companies);
  9636. if ($issueCompanies === []) {
  9637. $this->error('请至少选择一家合作供应商');
  9638. }
  9639. $issueNameLabels = [];
  9640. foreach ($issueCompanies as $pc) {
  9641. $issueNameLabels[] = $pc['name'];
  9642. }
  9643. $issueNamesSummary = implode('、', $issueNameLabels);
  9644. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  9645. if ($sysRq === '') {
  9646. $this->error('请选择招标截止日期');
  9647. }
  9648. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  9649. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  9650. (string)$this->request->post('delivery_deadline', ''),
  9651. true
  9652. );
  9653. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  9654. if ($scoreRuleId <= 0) {
  9655. $this->error('请选择订单类型');
  9656. }
  9657. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  9658. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  9659. $this->error('订单类型无效,请刷新后重选');
  9660. }
  9661. $scoreRuleId = (int)$scoreRule['id'];
  9662. $this->ensurePurchaseOrderScoreRuleIdColumn();
  9663. $isMerge = count($mergeRows) > 1;
  9664. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  9665. $logMsg = '下发' . $procPart
  9666. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  9667. $issueTime = date('Y-m-d H:i:s');
  9668. $logSidList = [];
  9669. foreach ($mergeRows as $row) {
  9670. if (!is_array($row)) {
  9671. continue;
  9672. }
  9673. $sid = $this->extractScydgyRowId($row);
  9674. if ($this->isValidScydgyRowId($sid)) {
  9675. $logSidList[$sid] = true;
  9676. }
  9677. }
  9678. $existingBySid = [];
  9679. if ($logSidList !== []) {
  9680. try {
  9681. $existingRows = Db::table('purchase_order')
  9682. ->where('scydgy_id', 'in', array_keys($logSidList))
  9683. ->select();
  9684. if (is_array($existingRows)) {
  9685. foreach ($existingRows as $poRow) {
  9686. if (!is_array($poRow)) {
  9687. continue;
  9688. }
  9689. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9690. if ($this->isValidScydgyRowId($sid)) {
  9691. $existingBySid[$sid] = $poRow;
  9692. }
  9693. }
  9694. }
  9695. } catch (\Throwable $e) {
  9696. $existingBySid = [];
  9697. }
  9698. }
  9699. Db::startTrans();
  9700. try {
  9701. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  9702. foreach ($mergeRows as $row) {
  9703. if (!is_array($row)) {
  9704. continue;
  9705. }
  9706. $sid = $this->extractScydgyRowId($row);
  9707. $this->upsertPurchaseOrderFromRow(
  9708. $row,
  9709. $sysRqDb,
  9710. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9711. $issueTime,
  9712. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  9713. $deliveryDeadlineDb,
  9714. $scoreRule
  9715. );
  9716. }
  9717. foreach ($issueCompanies as $c) {
  9718. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  9719. }
  9720. Db::commit();
  9721. } catch (\Throwable $e) {
  9722. Db::rollback();
  9723. $this->error($e->getMessage());
  9724. }
  9725. $poIdBySid = [];
  9726. if ($logSidList !== []) {
  9727. try {
  9728. $poIdBySid = Db::table('purchase_order')
  9729. ->where('scydgy_id', 'in', array_keys($logSidList))
  9730. ->column('id', 'scydgy_id');
  9731. } catch (\Throwable $e) {
  9732. $poIdBySid = [];
  9733. }
  9734. }
  9735. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  9736. if ($logSidList !== []) {
  9737. list($adminId, $adminName) = $this->GetUseName();
  9738. $logRows = [];
  9739. $seenLogSid = [];
  9740. foreach ($mergeRows as $row) {
  9741. if (!is_array($row)) {
  9742. continue;
  9743. }
  9744. $ids = $this->extractScydgyRowId($row);
  9745. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  9746. continue;
  9747. }
  9748. $seenLogSid[$ids] = true;
  9749. $poIdLog = null;
  9750. if (isset($poIdBySid[$ids])) {
  9751. $tid = (int)$poIdBySid[$ids];
  9752. $poIdLog = $tid > 0 ? $tid : null;
  9753. }
  9754. $logRows[] = ProcuremenOperLog::buildInsertRow(
  9755. $ids,
  9756. 'issue_submit',
  9757. $logMsg,
  9758. $poIdLog,
  9759. (int)$adminId,
  9760. (string)$adminName
  9761. );
  9762. }
  9763. if ($logRows !== []) {
  9764. try {
  9765. Db::table('purchase_order_oper_log')->insertAll($logRows);
  9766. } catch (\Throwable $e) {
  9767. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  9768. }
  9769. }
  9770. }
  9771. $notifyErrors = [];
  9772. $posNotify = [];
  9773. if ($logSidList !== []) {
  9774. try {
  9775. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  9776. } catch (\Throwable $e) {
  9777. $posNotify = [];
  9778. }
  9779. }
  9780. if (!is_array($posNotify)) {
  9781. $posNotify = [];
  9782. }
  9783. foreach ($posNotify as $i => $prow) {
  9784. if (is_array($posNotify[$i])) {
  9785. $posNotify[$i]['sys_rq'] = $sysRqDb;
  9786. }
  9787. }
  9788. $ccydhPick = '';
  9789. foreach ($mergeRows as $row) {
  9790. if (!is_array($row)) {
  9791. continue;
  9792. }
  9793. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  9794. if ($ccydhPick !== '') {
  9795. break;
  9796. }
  9797. }
  9798. $notifyBundleBase = [
  9799. 'ccydh' => $ccydhPick,
  9800. 'pos' => $posNotify,
  9801. 'merge_rows' => $mergeRows,
  9802. ];
  9803. try {
  9804. $this->notifyDryRunPreview = [];
  9805. foreach ($issueCompanies as $c) {
  9806. if (!is_array($c)) {
  9807. continue;
  9808. }
  9809. $cname = trim((string)($c['name'] ?? ''));
  9810. if ($cname === '') {
  9811. continue;
  9812. }
  9813. try {
  9814. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  9815. } catch (\Throwable $e) {
  9816. $notifyErrors[] = $cname . ':' . $e->getMessage();
  9817. }
  9818. }
  9819. } catch (\Throwable $e) {
  9820. $this->error('通知发送失败:' . $e->getMessage());
  9821. }
  9822. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  9823. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  9824. }
  9825. if ($this->isProcuremenNotifyDryRun()) {
  9826. $this->success('【演练模式】已保存并生成通知预览', '', [
  9827. 'notify_dry_run' => true,
  9828. 'notify_preview' => $this->notifyDryRunPreview,
  9829. ]);
  9830. }
  9831. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  9832. }
  9833. /**
  9834. * 确认供应商弹窗
  9835. */
  9836. public function auditIssue()
  9837. {
  9838. $ids = $this->request->param('ids', $this->request->param('id', ''));
  9839. if (is_array($ids)) {
  9840. $ids = isset($ids[0]) ? $ids[0] : '';
  9841. }
  9842. $ids = trim((string)$ids);
  9843. if ($ids === '') {
  9844. $this->error(__('Invalid parameters'));
  9845. }
  9846. if ($this->request->isPost()) {
  9847. $this->error('请使用弹窗内「确认」提交');
  9848. }
  9849. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  9850. $pos = $bundle['pos'];
  9851. if ($pos === []) {
  9852. $this->error('该订单不在待确认供应商状态');
  9853. }
  9854. $po = $pos[0];
  9855. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  9856. if ($quoteGroups === []) {
  9857. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  9858. }
  9859. $pickedName = '';
  9860. foreach ($pos as $poRow) {
  9861. if (!is_array($poRow)) {
  9862. continue;
  9863. }
  9864. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  9865. if ($pn !== '') {
  9866. $pickedName = $pn;
  9867. break;
  9868. }
  9869. }
  9870. $this->view->assign('po', $po);
  9871. $this->view->assign('scydgyId', $ids);
  9872. $this->view->assign('orderCcydh', $bundle['ccydh']);
  9873. $mergeRows = $bundle['merge_rows'];
  9874. $this->view->assign('processRows', $mergeRows);
  9875. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  9876. $this->view->assign('processCount', count($mergeRows));
  9877. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  9878. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  9879. $this->view->assign('pickedCompanyName', $pickedName);
  9880. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  9881. if ($sysRqForView === '') {
  9882. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  9883. }
  9884. $this->view->assign('sysRq', $sysRqForView);
  9885. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  9886. if ($deliveryDeadlineForView === '') {
  9887. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  9888. }
  9889. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  9890. $this->ensurePurchaseOrderManualPickColumns();
  9891. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  9892. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  9893. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  9894. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  9895. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  9896. $pickedName = $manualPickInfo['company'];
  9897. $this->view->assign('pickedCompanyName', $pickedName);
  9898. }
  9899. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  9900. $this->view->assign('manualPicked', $manualPicked);
  9901. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  9902. $this->view->assign('quoteVisible', $quoteVisible);
  9903. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  9904. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  9905. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  9906. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  9907. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  9908. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  9909. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  9910. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  9911. return $this->view->fetch('procuremen/audit_issue');
  9912. }
  9913. /**
  9914. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  9915. *
  9916. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  9917. */
  9918. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  9919. {
  9920. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  9921. return false;
  9922. }
  9923. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  9924. return false;
  9925. }
  9926. return true;
  9927. }
  9928. /**
  9929. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  9930. *
  9931. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  9932. */
  9933. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  9934. {
  9935. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  9936. return false;
  9937. }
  9938. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  9939. return false;
  9940. }
  9941. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  9942. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  9943. return true;
  9944. }
  9945. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  9946. }
  9947. /**
  9948. * 确认页 — 补加供应商弹窗
  9949. */
  9950. public function auditAppend()
  9951. {
  9952. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  9953. $this->error(__('You have no permission'));
  9954. }
  9955. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  9956. if (is_array($ids)) {
  9957. $ids = isset($ids[0]) ? $ids[0] : '';
  9958. }
  9959. $ids = trim((string)$ids);
  9960. if ($ids === '') {
  9961. $this->error(__('Invalid parameters'));
  9962. }
  9963. if ($this->request->isPost()) {
  9964. $this->error('请使用弹窗内「确认」提交');
  9965. }
  9966. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  9967. if (($bundle['pos'] ?? []) === []) {
  9968. $this->error('该订单不在待确认供应商状态');
  9969. }
  9970. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  9971. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  9972. $this->error('已开标验证,不能再补加供应商');
  9973. }
  9974. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  9975. $this->error('已指定供应商,不能再补加供应商');
  9976. }
  9977. $this->error('已经超过了招标截止日期,不可操作');
  9978. }
  9979. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  9980. $existingNames = [];
  9981. foreach ($quoteGroups as $g) {
  9982. if (!is_array($g)) {
  9983. continue;
  9984. }
  9985. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  9986. if ($n !== '') {
  9987. $existingNames[$n] = true;
  9988. }
  9989. }
  9990. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  9991. $mergeRows = $bundle['merge_rows'] ?? [];
  9992. $this->view->assign('scydgyId', $ids);
  9993. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  9994. $this->view->assign('po', $po);
  9995. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  9996. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  9997. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  9998. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  9999. if ($sysRqForView === '') {
  10000. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10001. }
  10002. $this->view->assign('sysRq', $sysRqForView);
  10003. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10004. if ($deliveryDeadlineForView === '') {
  10005. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10006. }
  10007. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10008. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10009. }
  10010. /**
  10011. * 确认页 — 补加供应商提交
  10012. */
  10013. public function auditAppendSubmit()
  10014. {
  10015. if (!$this->request->isPost()) {
  10016. $this->error(__('Invalid parameters'));
  10017. }
  10018. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10019. $this->error(__('You have no permission'));
  10020. }
  10021. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10022. if ($ids === '') {
  10023. $this->error(__('Invalid parameters'));
  10024. }
  10025. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10026. if (($bundle['pos'] ?? []) === []) {
  10027. $this->error('该订单不在待确认供应商状态');
  10028. }
  10029. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10030. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10031. $this->error('已开标验证,不能再补加供应商');
  10032. }
  10033. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10034. $this->error('已指定供应商,不能再补加供应商');
  10035. }
  10036. $this->error('已经超过了招标截止日期,不可操作');
  10037. }
  10038. $companiesJson = $this->request->post('companies_json', '[]');
  10039. $companies = json_decode((string)$companiesJson, true);
  10040. if (!is_array($companies)) {
  10041. $this->error('供应商数据无效');
  10042. }
  10043. $issueCompanies = $this->normalizePickCompanies($companies);
  10044. if ($issueCompanies === []) {
  10045. $this->error('请至少选择一家合作供应商');
  10046. }
  10047. $mergeRows = $bundle['merge_rows'] ?? [];
  10048. if (!is_array($mergeRows) || $mergeRows === []) {
  10049. $this->error('未找到工序行,无法补加');
  10050. }
  10051. $existingNames = [];
  10052. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10053. if (!is_array($g)) {
  10054. continue;
  10055. }
  10056. $n = trim((string)($g['company_name'] ?? ''));
  10057. if ($n !== '') {
  10058. $existingNames[$n] = true;
  10059. }
  10060. }
  10061. $toAdd = [];
  10062. foreach ($issueCompanies as $c) {
  10063. if (!is_array($c)) {
  10064. continue;
  10065. }
  10066. $n = trim((string)($c['name'] ?? ''));
  10067. if ($n === '' || isset($existingNames[$n])) {
  10068. continue;
  10069. }
  10070. $toAdd[] = $c;
  10071. }
  10072. if ($toAdd === []) {
  10073. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10074. }
  10075. $addedNames = [];
  10076. Db::startTrans();
  10077. try {
  10078. foreach ($toAdd as $c) {
  10079. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10080. $addedNames[] = trim((string)($c['name'] ?? ''));
  10081. }
  10082. Db::commit();
  10083. } catch (\Throwable $e) {
  10084. Db::rollback();
  10085. $this->error($e->getMessage());
  10086. }
  10087. $notifyErrors = [];
  10088. $notifyBundleBase = [
  10089. 'ccydh' => $bundle['ccydh'] ?? '',
  10090. 'pos' => $bundle['pos'] ?? [],
  10091. 'merge_rows' => $mergeRows,
  10092. ];
  10093. foreach ($toAdd as $c) {
  10094. if (!is_array($c)) {
  10095. continue;
  10096. }
  10097. $cname = trim((string)($c['name'] ?? ''));
  10098. if ($cname === '') {
  10099. continue;
  10100. }
  10101. try {
  10102. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10103. } catch (\Throwable $e) {
  10104. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10105. }
  10106. }
  10107. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10108. $seenLogSid = [];
  10109. foreach ($bundle['pos'] ?? [] as $poRow) {
  10110. if (!is_array($poRow)) {
  10111. continue;
  10112. }
  10113. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10114. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10115. continue;
  10116. }
  10117. $seenLogSid[$sid] = true;
  10118. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10119. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10120. }
  10121. if ($seenLogSid === []) {
  10122. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10123. if ($this->isValidScydgyRowId($logSid)) {
  10124. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10125. }
  10126. }
  10127. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10128. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10129. }
  10130. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10131. }
  10132. /**
  10133. * 开标双重验证 — 可选验证人列表
  10134. */
  10135. public function bidOpenUsers()
  10136. {
  10137. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10138. $this->error('无权限');
  10139. }
  10140. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10141. if ($scydgyId !== '') {
  10142. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10143. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10144. $this->success('已完成开标验证', null, [
  10145. 'verified' => 1,
  10146. 'users' => [],
  10147. ]);
  10148. }
  10149. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10150. $this->error('本单已指定供应商,无需再开标');
  10151. }
  10152. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10153. }
  10154. $this->success('', null, [
  10155. 'verified' => 0,
  10156. 'users' => $this->listBidOpenVerifierCandidates(),
  10157. ]);
  10158. }
  10159. /**
  10160. * 开标双重验证 — 向指定管理员发送短信验证码
  10161. */
  10162. public function bidOpenSendCode()
  10163. {
  10164. if (!$this->request->isPost()) {
  10165. $this->error(__('Invalid parameters'));
  10166. }
  10167. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10168. $this->error('无权限');
  10169. }
  10170. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10171. $adminId = (int)$this->request->post('admin_id', 0);
  10172. if ($scydgyId === '' || $adminId <= 0) {
  10173. $this->error('参数无效');
  10174. }
  10175. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10176. if ($bundle['pos'] === []) {
  10177. $this->error('该订单不在待确认供应商状态');
  10178. }
  10179. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10180. $this->success('已完成开标验证,无需重复发送');
  10181. }
  10182. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10183. $this->error('本单已指定供应商,无需再开标');
  10184. }
  10185. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10186. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10187. if ($ccydh === '') {
  10188. $this->error('订单号无效');
  10189. }
  10190. $admin = $this->loadBidOpenAdminUser($adminId);
  10191. if ($admin === null) {
  10192. $this->error('验证人无效或未绑定手机号');
  10193. }
  10194. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10195. $cd = max(30, min(120, $cd));
  10196. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10197. $this->error('发送过于频繁,请稍后再试');
  10198. }
  10199. $code = (string)random_int(100000, 999999);
  10200. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10201. $ttl = max(60, min(600, $ttl));
  10202. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10203. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10204. try {
  10205. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10206. } catch (\Throwable $e) {
  10207. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10208. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10209. $this->error($e->getMessage());
  10210. }
  10211. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10212. }
  10213. /**
  10214. * 开标双重验证 — 两人验证码校验并记录
  10215. */
  10216. public function bidOpenVerify()
  10217. {
  10218. if (!$this->request->isPost()) {
  10219. $this->error(__('Invalid parameters'));
  10220. }
  10221. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10222. $this->error('无权限');
  10223. }
  10224. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10225. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10226. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10227. $code1 = trim((string)$this->request->post('code1', ''));
  10228. $code2 = trim((string)$this->request->post('code2', ''));
  10229. if ($scydgyId === '') {
  10230. $this->error('参数无效');
  10231. }
  10232. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10233. $this->error('请选择两位验证人');
  10234. }
  10235. if ($verifier1Id === $verifier2Id) {
  10236. $this->error('两位验证人不能相同');
  10237. }
  10238. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10239. $this->error('请输入6位短信验证码');
  10240. }
  10241. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10242. if ($bundle['pos'] === []) {
  10243. $this->error('该订单不在待确认供应商状态');
  10244. }
  10245. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10246. if ($ccydh === '') {
  10247. $this->error('订单号无效');
  10248. }
  10249. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10250. $this->success('已完成开标验证');
  10251. }
  10252. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10253. $this->error('本单已指定供应商,无需再开标');
  10254. }
  10255. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10256. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10257. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10258. if ($verifier1 === null || $verifier2 === null) {
  10259. $this->error('验证人无效或未绑定手机号');
  10260. }
  10261. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10262. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10263. }
  10264. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10265. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10266. }
  10267. try {
  10268. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10269. } catch (\Throwable $e) {
  10270. $this->error($e->getMessage());
  10271. }
  10272. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10273. }
  10274. /**
  10275. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10276. */
  10277. public function auditManualPick()
  10278. {
  10279. if (!$this->request->isPost()) {
  10280. $this->error(__('Invalid parameters'));
  10281. }
  10282. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10283. $this->error('无权限');
  10284. }
  10285. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10286. if ($scydgyId === '') {
  10287. $this->error('参数无效');
  10288. }
  10289. $companyName = trim((string)$this->request->post('selected_company', ''));
  10290. $reason = trim((string)$this->request->post('pick_reason', ''));
  10291. if ($companyName === '') {
  10292. $this->error('请选择一家供应商');
  10293. }
  10294. if ($reason === '') {
  10295. $this->error('请填写选择说明');
  10296. }
  10297. if (mb_strlen($reason) > 500) {
  10298. $this->error('选择说明不能超过500字');
  10299. }
  10300. $this->ensurePurchaseOrderManualPickColumns();
  10301. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10302. $pos = $bundle['pos'];
  10303. if ($pos === []) {
  10304. $this->error('该订单不在待确认供应商状态');
  10305. }
  10306. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10307. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10308. }
  10309. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10310. if ($quoteGroups === []) {
  10311. $this->error('暂无供应商,请确认已完成协助初选通知');
  10312. }
  10313. $matched = null;
  10314. foreach ($quoteGroups as $g) {
  10315. if (!is_array($g)) {
  10316. continue;
  10317. }
  10318. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10319. $matched = $g;
  10320. break;
  10321. }
  10322. }
  10323. if ($matched === null) {
  10324. $this->error('所选供应商不在本单报价列表中');
  10325. }
  10326. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10327. Db::startTrans();
  10328. try {
  10329. foreach ($pos as $poRow) {
  10330. if (!is_array($poRow)) {
  10331. continue;
  10332. }
  10333. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10334. if (!$this->isValidScydgyRowId($sid)) {
  10335. continue;
  10336. }
  10337. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10338. 'pick_company_name' => $companyName,
  10339. 'manual_pick' => 1,
  10340. 'manual_pick_reason' => $reason,
  10341. ]);
  10342. }
  10343. Db::commit();
  10344. } catch (\Throwable $e) {
  10345. Db::rollback();
  10346. $this->error($e->getMessage());
  10347. }
  10348. foreach ($pos as $poRow) {
  10349. if (!is_array($poRow)) {
  10350. continue;
  10351. }
  10352. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10353. if (!$this->isValidScydgyRowId($sid)) {
  10354. continue;
  10355. }
  10356. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10357. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10358. }
  10359. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10360. try {
  10361. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10362. if ($ccydh !== '') {
  10363. // 重新加载以拿到未掩码报价参与计分
  10364. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10365. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10366. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10367. }
  10368. } catch (\Throwable $e) {
  10369. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10370. }
  10371. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10372. }
  10373. /**
  10374. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10375. */
  10376. public function auditSubmit()
  10377. {
  10378. if (!$this->request->isPost()) {
  10379. $this->error(__('Invalid parameters'));
  10380. }
  10381. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10382. if ($scydgyId === '') {
  10383. $this->error('参数无效');
  10384. }
  10385. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10386. $pos = $bundle['pos'];
  10387. $mergeRows = $bundle['merge_rows'];
  10388. if ($pos === [] || $mergeRows === []) {
  10389. $this->error('该订单不在待确认供应商状态');
  10390. }
  10391. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10392. if ($quoteGroups === []) {
  10393. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10394. }
  10395. $companyName = trim((string)$this->request->post('selected_company', ''));
  10396. if ($companyName === '') {
  10397. $this->error('请选择一家供应商');
  10398. }
  10399. $matched = null;
  10400. foreach ($quoteGroups as $g) {
  10401. if (!is_array($g)) {
  10402. continue;
  10403. }
  10404. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10405. $matched = $g;
  10406. break;
  10407. }
  10408. }
  10409. if ($matched === null) {
  10410. $this->error('所选供应商不在本单报价列表中');
  10411. }
  10412. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10413. if ($sysRqDb === '') {
  10414. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10415. } else {
  10416. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10417. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10418. }
  10419. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10420. $this->error('未到招标截止日期,暂不可确认');
  10421. }
  10422. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10423. && !$this->isProcuremenManualPickedForBundle($bundle)
  10424. ) {
  10425. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10426. }
  10427. $procCnt = count($mergeRows);
  10428. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10429. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10430. Db::startTrans();
  10431. try {
  10432. foreach ($pos as $poRow) {
  10433. if (!is_array($poRow)) {
  10434. continue;
  10435. }
  10436. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10437. if (!$this->isValidScydgyRowId($sid)) {
  10438. continue;
  10439. }
  10440. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10441. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10442. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10443. 'pick_company_name' => $companyName,
  10444. 'sys_rq' => $sysRqDb,
  10445. ]);
  10446. }
  10447. Db::commit();
  10448. } catch (\Throwable $e) {
  10449. Db::rollback();
  10450. $this->error($e->getMessage());
  10451. }
  10452. foreach ($pos as $poRow) {
  10453. if (!is_array($poRow)) {
  10454. continue;
  10455. }
  10456. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10457. if (!$this->isValidScydgyRowId($sid)) {
  10458. continue;
  10459. }
  10460. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10461. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10462. }
  10463. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10464. }
  10465. /**
  10466. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10467. */
  10468. public function auditResendSms()
  10469. {
  10470. if (!$this->request->isPost()) {
  10471. $this->error(__('Invalid parameters'));
  10472. }
  10473. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10474. if ($scydgyId === '') {
  10475. $this->error('参数无效');
  10476. }
  10477. $loaded = $this->loadAuditResendBundle($scydgyId);
  10478. $mergeRows = $loaded['merge_rows'];
  10479. $bundle = $loaded['bundle'];
  10480. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10481. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10482. if ($quoteGroups === []) {
  10483. $this->error('暂无可通知的供应商');
  10484. }
  10485. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10486. $companiesJson = (string)$this->request->post('companies_json', '');
  10487. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10488. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10489. }
  10490. /**
  10491. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10492. */
  10493. public function auditResendEmail()
  10494. {
  10495. if (!$this->request->isPost()) {
  10496. $this->error(__('Invalid parameters'));
  10497. }
  10498. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10499. if ($scydgyId === '') {
  10500. $this->error('参数无效');
  10501. }
  10502. $loaded = $this->loadAuditResendBundle($scydgyId);
  10503. $mergeRows = $loaded['merge_rows'];
  10504. $bundle = $loaded['bundle'];
  10505. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10506. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10507. if ($quoteGroups === []) {
  10508. $this->error('暂无可通知的供应商');
  10509. }
  10510. $companiesJson = (string)$this->request->post('companies_json', '');
  10511. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10512. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10513. if ($companiesJson === '' && $selectedCompany === '') {
  10514. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10515. }
  10516. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10517. }
  10518. /**
  10519. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10520. *
  10521. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10522. * @return array<int, true> 已处理的 scydgy_id 集合
  10523. */
  10524. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10525. {
  10526. $pos = $bundle['pos'] ?? [];
  10527. if (!is_array($pos) || $pos === []) {
  10528. return [];
  10529. }
  10530. $sids = [];
  10531. $poIdBySid = [];
  10532. foreach ($pos as $poRow) {
  10533. if (!is_array($poRow)) {
  10534. continue;
  10535. }
  10536. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10537. if ($this->isValidScydgyRowId($sid)) {
  10538. $sids[$sid] = true;
  10539. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10540. if ($poId > 0) {
  10541. $poIdBySid[$sid] = $poId;
  10542. }
  10543. }
  10544. }
  10545. if ($sids === []) {
  10546. return [];
  10547. }
  10548. $logMsg = '重新下发';
  10549. $suffix = trim((string)$logSuffix, ',, ');
  10550. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10551. $logMsg .= ':从历史存证退回协助初选';
  10552. } else {
  10553. $logMsg .= ':退回协助初选';
  10554. }
  10555. Db::table('purchase_order')
  10556. ->where('scydgy_id', 'in', array_keys($sids))
  10557. ->update([
  10558. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10559. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10560. 'pick_company_name' => '',
  10561. 'pick_time' => null,
  10562. 'sys_rq' => null,
  10563. 'mod_rq' => null,
  10564. ]);
  10565. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10566. foreach (array_keys($sids) as $sid) {
  10567. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10568. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10569. }
  10570. return $sids;
  10571. }
  10572. /**
  10573. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  10574. *
  10575. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10576. */
  10577. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  10578. {
  10579. $scydgyId = trim($scydgyId);
  10580. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10581. if ($scydgyId === '') {
  10582. return $empty;
  10583. }
  10584. try {
  10585. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10586. } catch (\Throwable $e) {
  10587. $anchor = null;
  10588. }
  10589. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  10590. return $empty;
  10591. }
  10592. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10593. if ($ccydh === '') {
  10594. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10595. }
  10596. try {
  10597. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  10598. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  10599. $pos = $query->order('scydgy_id', 'asc')->select();
  10600. } catch (\Throwable $e) {
  10601. $pos = [$anchor];
  10602. }
  10603. if (!is_array($pos) || $pos === []) {
  10604. $pos = [$anchor];
  10605. }
  10606. return [
  10607. 'ccydh' => $ccydh,
  10608. 'pos' => $pos,
  10609. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10610. ];
  10611. }
  10612. protected function purchaseOrderRowIsCompleted(array $po): bool
  10613. {
  10614. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10615. }
  10616. /**
  10617. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  10618. *
  10619. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10620. */
  10621. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  10622. {
  10623. $scydgyId = trim($scydgyId);
  10624. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10625. if ($scydgyId === '') {
  10626. return $empty;
  10627. }
  10628. try {
  10629. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10630. } catch (\Throwable $e) {
  10631. $anchor = null;
  10632. }
  10633. if (!is_array($anchor)) {
  10634. return $empty;
  10635. }
  10636. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10637. if ($ccydh === '') {
  10638. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10639. }
  10640. try {
  10641. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  10642. } catch (\Throwable $e) {
  10643. $pos = [$anchor];
  10644. }
  10645. if (!is_array($pos) || $pos === []) {
  10646. $pos = [$anchor];
  10647. }
  10648. return [
  10649. 'ccydh' => $ccydh,
  10650. 'pos' => $pos,
  10651. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10652. ];
  10653. }
  10654. /**
  10655. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  10656. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  10657. */
  10658. public function auditAbandon()
  10659. {
  10660. if (!$this->request->isPost()) {
  10661. $this->error(__('Invalid parameters'));
  10662. }
  10663. $anchorIds = [];
  10664. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  10665. if ($batchRaw !== '') {
  10666. $decoded = json_decode($batchRaw, true);
  10667. if (is_array($decoded)) {
  10668. foreach ($decoded as $id) {
  10669. $s = trim((string)$id);
  10670. if ($s !== '') {
  10671. $anchorIds[] = $s;
  10672. }
  10673. }
  10674. }
  10675. }
  10676. if ($anchorIds === []) {
  10677. $single = trim((string)$this->request->post('scydgy_id', ''));
  10678. if ($single !== '') {
  10679. $anchorIds[] = $single;
  10680. }
  10681. }
  10682. if ($anchorIds === []) {
  10683. $this->error('请至少选择一条订单');
  10684. }
  10685. $processedCcydh = [];
  10686. $doneOrders = 0;
  10687. $allSids = [];
  10688. Db::startTrans();
  10689. try {
  10690. foreach ($anchorIds as $anchorId) {
  10691. $fromArchive = false;
  10692. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  10693. if (($bundle['pos'] ?? []) === []) {
  10694. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  10695. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10696. }
  10697. if (($bundle['pos'] ?? []) === []) {
  10698. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  10699. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10700. }
  10701. if (($bundle['pos'] ?? []) === []) {
  10702. continue;
  10703. }
  10704. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10705. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  10706. if (isset($processedCcydh[$dedupeKey])) {
  10707. continue;
  10708. }
  10709. $processedCcydh[$dedupeKey] = true;
  10710. $sids = $fromArchive
  10711. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  10712. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  10713. if ($sids === []) {
  10714. continue;
  10715. }
  10716. $doneOrders++;
  10717. foreach (array_keys($sids) as $sid) {
  10718. $allSids[(int)$sid] = true;
  10719. }
  10720. }
  10721. if ($doneOrders < 1) {
  10722. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  10723. }
  10724. Db::commit();
  10725. } catch (\Throwable $e) {
  10726. Db::rollback();
  10727. $this->error($e->getMessage());
  10728. }
  10729. $this->pickHiddenScydgySetCache = null;
  10730. $msg = $doneOrders > 1
  10731. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  10732. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  10733. $this->success($msg);
  10734. }
  10735. /**
  10736. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  10737. */
  10738. public function archiveAbandon()
  10739. {
  10740. return $this->auditAbandon();
  10741. }
  10742. /**
  10743. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  10744. */
  10745. public function purchaseApprovalReject()
  10746. {
  10747. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10748. $this->error(__('Invalid parameters'));
  10749. }
  10750. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  10751. $this->error(__('You have no permission'));
  10752. }
  10753. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  10754. $decoded = json_decode($batchRaw, true);
  10755. if (!is_array($decoded) || $decoded === []) {
  10756. $this->error('提交数据无效');
  10757. }
  10758. $done = 0;
  10759. Db::startTrans();
  10760. try {
  10761. foreach ($decoded as $item) {
  10762. if (!is_array($item)) {
  10763. continue;
  10764. }
  10765. $sid = (int)($item['scydgy_id'] ?? 0);
  10766. if (!$this->isValidScydgyRowId($sid)) {
  10767. continue;
  10768. }
  10769. $this->runPurchaseApprovalRejectForSid($sid);
  10770. $done++;
  10771. }
  10772. if ($done < 1) {
  10773. throw new \Exception('所选订单均不在待审批状态');
  10774. }
  10775. Db::commit();
  10776. } catch (\Throwable $e) {
  10777. Db::rollback();
  10778. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  10779. }
  10780. $this->pickHiddenScydgySetCache = null;
  10781. $this->success('已驳回并退回「协助审批下发」');
  10782. }
  10783. /**
  10784. * @throws \Exception
  10785. */
  10786. protected function runPurchaseApprovalRejectForSid(int $sid): void
  10787. {
  10788. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  10789. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  10790. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  10791. $allIds = $this->purchaseOrderDetail($sid);
  10792. if ($allIds === []) {
  10793. throw new \Exception('未找到下发明细');
  10794. }
  10795. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10796. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10797. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10798. 'pick_company_name' => '',
  10799. ]);
  10800. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  10801. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  10802. $poId = 0;
  10803. try {
  10804. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  10805. if (is_array($po)) {
  10806. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10807. }
  10808. } catch (\Throwable $e) {
  10809. }
  10810. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  10811. }
  10812. /**
  10813. * 审核弹窗(旧入口,POST 已关闭)
  10814. */
  10815. public function review()
  10816. {
  10817. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  10818. $this->error(__('You have no permission'));
  10819. }
  10820. if ($this->request->isPost()) {
  10821. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  10822. }
  10823. $this->view->assign('pickMode', 0);
  10824. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  10825. }
  10826. /**
  10827. * 审核弹窗获取公司列表
  10828. */
  10829. public function reviewCompanies()
  10830. {
  10831. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  10832. $this->error(__('You have no permission'));
  10833. }
  10834. if (!$this->request->isAjax()) {
  10835. $this->error(__('Invalid parameters'));
  10836. }
  10837. $list = [];
  10838. try {
  10839. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  10840. $rows = Db::table('customer')
  10841. ->where(function ($q) {
  10842. $q->where('status', 1)
  10843. ->whereOr('status', '1')
  10844. ->whereOr('status', '')
  10845. ->whereNull('status');
  10846. })
  10847. ->order('id', 'desc')
  10848. ->select();
  10849. } catch (\Throwable $e) {
  10850. $this->success('', '', []);
  10851. return;
  10852. }
  10853. if (!is_array($rows)) {
  10854. $this->success('', '', []);
  10855. return;
  10856. }
  10857. $detailColCandidates = [
  10858. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  10859. 'company_detail', 'company_desc', 'address',
  10860. ];
  10861. foreach ($rows as $row) {
  10862. if (!is_array($row)) {
  10863. continue;
  10864. }
  10865. $norm = [];
  10866. foreach ($row as $k => $v) {
  10867. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  10868. }
  10869. $row = $norm;
  10870. $st = $row['status'] ?? '';
  10871. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  10872. continue;
  10873. }
  10874. $payload = $this->buildCustomerContactPayloadFromRow($row);
  10875. if ($payload === null) {
  10876. continue;
  10877. }
  10878. $detail = '';
  10879. foreach ($detailColCandidates as $dk) {
  10880. if (!isset($row[$dk])) {
  10881. continue;
  10882. }
  10883. $dv = trim((string)$row[$dk]);
  10884. if ($dv !== '') {
  10885. $detail = $dv;
  10886. break;
  10887. }
  10888. }
  10889. $payload['detail'] = $detail;
  10890. $list[] = $this->maskSupplierContactFields($payload);
  10891. }
  10892. $this->success('', '', $list);
  10893. }
  10894. /**
  10895. * 采购确认-下发明细弹窗:
  10896. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  10897. */
  10898. public function outward_detail()
  10899. {
  10900. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10901. if (is_array($ids)) {
  10902. $ids = isset($ids[0]) ? $ids[0] : '';
  10903. }
  10904. $ids = trim((string)$ids);
  10905. if ($ids === '') {
  10906. $this->error(__('Invalid parameters'));
  10907. }
  10908. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  10909. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  10910. $wffTab = 'all';
  10911. }
  10912. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  10913. $purchaseOrderId = 0;
  10914. $po = null;
  10915. try {
  10916. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  10917. if (is_array($po)) {
  10918. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10919. }
  10920. } catch (\Throwable $e) {
  10921. $purchaseOrderId = 0;
  10922. $po = null;
  10923. }
  10924. if (!$isPurchaseConfirm && is_array($po)) {
  10925. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10926. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  10927. $isPurchaseConfirm = true;
  10928. }
  10929. }
  10930. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  10931. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10932. $confirmProcessCount = 1;
  10933. $confirmPickGroups = [];
  10934. $processDisplayRows = [];
  10935. $allDetailsBySid = [];
  10936. $requiredSidList = [];
  10937. $sidList = [$ids];
  10938. if ($isPurchaseConfirm) {
  10939. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  10940. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  10941. if ($mergeRows !== []) {
  10942. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  10943. }
  10944. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  10945. if ($confirmBundle['pos'] !== []) {
  10946. $sidList = [];
  10947. foreach ($confirmBundle['pos'] as $poRow) {
  10948. if (!is_array($poRow)) {
  10949. continue;
  10950. }
  10951. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10952. if (!$this->isValidScydgyRowId($sid)) {
  10953. continue;
  10954. }
  10955. $sidList[] = (string)$sid;
  10956. $requiredSidList[] = $sid;
  10957. }
  10958. }
  10959. if ($sidList === []) {
  10960. $sidList = [$ids];
  10961. $requiredSidList = [(int)$ids];
  10962. }
  10963. $confirmProcessCount = max(1, count($requiredSidList));
  10964. if (is_array($po) && $purchaseOrderId <= 0) {
  10965. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10966. }
  10967. }
  10968. $rows = [];
  10969. try {
  10970. if (count($sidList) === 1) {
  10971. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  10972. } else {
  10973. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  10974. }
  10975. } catch (\Throwable $e) {
  10976. $rows = [];
  10977. }
  10978. if ($isPurchaseConfirm) {
  10979. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  10980. }
  10981. foreach ($rows as &$r) {
  10982. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  10983. $r['id'] = $r['ID'];
  10984. }
  10985. if (isset($r['createtime'])) {
  10986. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  10987. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  10988. } else {
  10989. $r['createtime_text'] = (string)$r['createtime'];
  10990. }
  10991. } else {
  10992. $r['createtime_text'] = '';
  10993. }
  10994. if (is_array($r)) {
  10995. $r = $this->maskSupplierContactFields($r);
  10996. }
  10997. }
  10998. unset($r);
  10999. $pickedCompanyName = '';
  11000. if ($isPurchaseConfirm) {
  11001. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11002. if (!is_array($poRow)) {
  11003. continue;
  11004. }
  11005. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11006. if ($pn !== '') {
  11007. $pickedCompanyName = $pn;
  11008. break;
  11009. }
  11010. }
  11011. }
  11012. $this->view->assign('rows', $rows ?: []);
  11013. $this->view->assign('rowCount', count($rows ?: []));
  11014. $this->view->assign('scydgyId', $ids);
  11015. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11016. $this->view->assign('headTitle', $headTitle);
  11017. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11018. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11019. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11020. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11021. $this->view->assign('processDisplayRows', $processDisplayRows);
  11022. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11023. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11024. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11025. $this->view->assign('bidOpenVerified', ($isPurchaseConfirm && $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle)) ? 1 : 0);
  11026. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11027. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11028. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11029. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11030. $sysRqDisplay = '—';
  11031. if ($isPurchaseConfirm) {
  11032. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11033. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11034. );
  11035. }
  11036. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11037. $this->view->assign('sysRq', $isPurchaseConfirm
  11038. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11039. : '');
  11040. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11041. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11042. : '');
  11043. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11044. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11045. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11046. if ($isPurchaseConfirm) {
  11047. return $this->view->fetch();
  11048. }
  11049. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11050. $this->view->engine->layout(false);
  11051. try {
  11052. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11053. $this->view->assign('dialogBody', $bodyHtml);
  11054. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11055. } finally {
  11056. if ($restoreLayout) {
  11057. $this->view->engine->layout($restoreLayout);
  11058. }
  11059. }
  11060. }
  11061. /**
  11062. * 月度导出记录表(不存在时自动创建)
  11063. */
  11064. protected function ensurePurchaseMonthExportLogTable(): void
  11065. {
  11066. try {
  11067. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11068. } catch (\Throwable $e) {
  11069. Db::execute(
  11070. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11071. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11072. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11073. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11074. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11075. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11076. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11077. `createtime` int(10) unsigned DEFAULT NULL,
  11078. PRIMARY KEY (`id`),
  11079. KEY `idx_ym` (`ym`),
  11080. KEY `idx_ct` (`createtime`)
  11081. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11082. );
  11083. }
  11084. }
  11085. /**
  11086. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11087. *
  11088. * @param array<int, mixed> $dbRows
  11089. * @return array<int, array<string, mixed>>
  11090. */
  11091. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11092. {
  11093. $keyword = trim((string)$this->request->get('search', ''));
  11094. if ($keyword === '') {
  11095. $keyword = trim((string)$this->request->request('search', ''));
  11096. }
  11097. $filter = $this->request->get('filter', '');
  11098. $op = $this->request->get('op', '');
  11099. if (is_string($filter) && $filter !== '') {
  11100. $filterArr = (array)json_decode($filter, true);
  11101. } else {
  11102. $filterArr = is_array($filter) ? $filter : [];
  11103. }
  11104. if (is_string($op) && $op !== '') {
  11105. $opArr = (array)json_decode($op, true);
  11106. } else {
  11107. $opArr = is_array($op) ? $op : [];
  11108. }
  11109. if ($keyword === '' && $filterArr === []) {
  11110. return array_values(array_filter($dbRows, 'is_array'));
  11111. }
  11112. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11113. $out = [];
  11114. foreach ($dbRows as $row) {
  11115. if (!is_array($row)) {
  11116. continue;
  11117. }
  11118. if ($keyword !== '') {
  11119. $hit = false;
  11120. foreach ($searchFields as $f) {
  11121. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11122. $hit = true;
  11123. break;
  11124. }
  11125. }
  11126. if (!$hit) {
  11127. continue;
  11128. }
  11129. }
  11130. $passFilter = true;
  11131. foreach ($filterArr as $field => $val) {
  11132. $field = (string)$field;
  11133. $val = trim((string)$val);
  11134. if ($field === '' || $val === '') {
  11135. continue;
  11136. }
  11137. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11138. continue;
  11139. }
  11140. $cell = (string)($row[$field] ?? '');
  11141. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11142. if ($mode === '=' || $mode === 'EQUAL') {
  11143. if (strcasecmp($cell, $val) !== 0) {
  11144. $passFilter = false;
  11145. break;
  11146. }
  11147. } elseif (mb_stripos($cell, $val) === false) {
  11148. $passFilter = false;
  11149. break;
  11150. }
  11151. }
  11152. if (!$passFilter) {
  11153. continue;
  11154. }
  11155. $out[] = $row;
  11156. }
  11157. return $out;
  11158. }
  11159. /**
  11160. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11161. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11162. */
  11163. public function export_month_outward()
  11164. {
  11165. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11166. $this->error(__('You have no permission'));
  11167. }
  11168. $bundle = $this->prepareMonthOutwardExportBundle();
  11169. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11170. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11171. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11172. $spreadsheet = new Spreadsheet();
  11173. $sheet = $spreadsheet->getActiveSheet();
  11174. $sheet->setTitle('外协加工明细');
  11175. $mon = (int)substr($ym, 5, 2);
  11176. $sheet->mergeCells('A1:H1');
  11177. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11178. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11179. $sheet->getStyle('A1')->getAlignment()
  11180. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11181. ->setVertical(Alignment::VERTICAL_CENTER);
  11182. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11183. $col = 'A';
  11184. foreach ($headers as $h) {
  11185. $sheet->setCellValue($col . '2', $h);
  11186. $col++;
  11187. }
  11188. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11189. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11190. $rowNum = 3;
  11191. $sumSubtotalCounts = 0;
  11192. $grandAmount = 0.0;
  11193. $globalSeq = 0;
  11194. if ($groups === []) {
  11195. $sheet->mergeCells('A3:H3');
  11196. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11197. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11198. $rowNum = 4;
  11199. } else {
  11200. foreach ($groups as $items) {
  11201. if ($items === []) {
  11202. continue;
  11203. }
  11204. $groupLineCount = count($items);
  11205. $subAmount = 0.0;
  11206. foreach ($items as $line) {
  11207. $globalSeq++;
  11208. $dr = $line['detail'];
  11209. $amt = $this->procuremenExportAmount($dr);
  11210. $subAmount += $amt;
  11211. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11212. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11213. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11214. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11215. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11216. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11217. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11218. $sheet->setCellValue('H' . $rowNum, $amt);
  11219. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11220. $rowNum++;
  11221. }
  11222. $sumSubtotalCounts += $groupLineCount;
  11223. $grandAmount += $subAmount;
  11224. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11225. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11226. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11227. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11228. ->setVertical(Alignment::VERTICAL_CENTER);
  11229. $rowNum++;
  11230. }
  11231. }
  11232. $sheet->setCellValue('A' . $rowNum, '总计');
  11233. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11234. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11235. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11236. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11237. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11238. $lastRow = $rowNum;
  11239. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11240. 'borders' => [
  11241. 'allBorders' => [
  11242. 'borderStyle' => Border::BORDER_THIN,
  11243. 'color' => ['rgb' => '000000'],
  11244. ],
  11245. ],
  11246. ]);
  11247. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11248. if ($lastRow >= 3) {
  11249. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11250. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11251. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11252. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11253. }
  11254. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11255. $sheet->getColumnDimension('A')->setWidth(7);
  11256. $sheet->getColumnDimension('B')->setWidth(16);
  11257. $sheet->getColumnDimension('C')->setWidth(52);
  11258. $sheet->getColumnDimension('D')->setWidth(32);
  11259. $sheet->getColumnDimension('E')->setWidth(12);
  11260. $sheet->getColumnDimension('F')->setWidth(44);
  11261. $sheet->getColumnDimension('G')->setWidth(26);
  11262. $sheet->getColumnDimension('H')->setWidth(13);
  11263. $sheet->getRowDimension(1)->setRowHeight(28);
  11264. $ymCompact = str_replace('-', '', $ym);
  11265. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11266. $filename = $fileBase . '.xlsx';
  11267. try {
  11268. $this->ensurePurchaseMonthExportLogTable();
  11269. list($adminId, $adminName) = $this->GetUseName();
  11270. Db::table('purchase_month_export_log')->insert([
  11271. 'ym' => $ym,
  11272. 'admin_id' => (int)$adminId,
  11273. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11274. 'row_count' => count($exportLines),
  11275. 'total_amount' => round($grandAmount, 2),
  11276. 'createtime' => time(),
  11277. ]);
  11278. } catch (\Throwable $e) {
  11279. Log::write('month export log: ' . $e->getMessage(), 'error');
  11280. }
  11281. if (ob_get_length()) {
  11282. ob_end_clean();
  11283. }
  11284. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11285. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11286. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11287. header('Cache-Control: max-age=0');
  11288. $writer = new Xlsx($spreadsheet);
  11289. $writer->save('php://output');
  11290. $spreadsheet->disconnectWorksheets();
  11291. unset($spreadsheet);
  11292. exit;
  11293. }
  11294. /**
  11295. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11296. */
  11297. public function export_month_quote()
  11298. {
  11299. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11300. $this->error(__('You have no permission'));
  11301. }
  11302. $bundle = $this->prepareMonthOutwardExportBundle();
  11303. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11304. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11305. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11306. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11307. $spreadsheet = new Spreadsheet();
  11308. $sheet = $spreadsheet->getActiveSheet();
  11309. $sheet->setTitle('供应商报价明细');
  11310. $mon = (int)substr($ym, 5, 2);
  11311. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11312. $sheet->getColumnDimension('A')->setWidth(7);
  11313. $sheet->getColumnDimension('B')->setWidth(16);
  11314. $sheet->getColumnDimension('C')->setWidth(52);
  11315. $sheet->getColumnDimension('D')->setWidth(26);
  11316. $sheet->getColumnDimension('E')->setWidth(32);
  11317. $sheet->getColumnDimension('F')->setWidth(12);
  11318. $sheet->getColumnDimension('G')->setWidth(14);
  11319. $sheet->getColumnDimension('H')->setWidth(12);
  11320. if ($quoteLastRow < 1) {
  11321. $quoteLastRow = 3;
  11322. }
  11323. $ymCompact = str_replace('-', '', $ym);
  11324. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11325. if (ob_get_length()) {
  11326. ob_end_clean();
  11327. }
  11328. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11329. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11330. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11331. header('Cache-Control: max-age=0');
  11332. $writer = new Xlsx($spreadsheet);
  11333. $writer->save('php://output');
  11334. $spreadsheet->disconnectWorksheets();
  11335. unset($spreadsheet);
  11336. exit;
  11337. }
  11338. /**
  11339. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11340. *
  11341. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11342. */
  11343. protected function prepareMonthOutwardExportBundle(): array
  11344. {
  11345. $this->request->filter(['strip_tags', 'trim']);
  11346. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11347. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11348. $ym = date('Y-m');
  11349. }
  11350. $dbRows = [];
  11351. try {
  11352. $query = Db::table('purchase_order');
  11353. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11354. $dbRows = $query->select();
  11355. } catch (\Throwable $e) {
  11356. $dbRows = [];
  11357. }
  11358. if (!is_array($dbRows)) {
  11359. $dbRows = [];
  11360. }
  11361. $completeTsMap = [];
  11362. $sidList = [];
  11363. foreach ($dbRows as $dbRow) {
  11364. if (!is_array($dbRow)) {
  11365. continue;
  11366. }
  11367. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11368. if ($sid > 0) {
  11369. $sidList[$sid] = true;
  11370. }
  11371. }
  11372. if ($sidList !== []) {
  11373. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11374. }
  11375. $searchKw = trim((string)$this->request->get('search', ''));
  11376. if ($searchKw === '') {
  11377. $searchKw = trim((string)$this->request->request('search', ''));
  11378. }
  11379. $filterRaw = $this->request->get('filter', '');
  11380. $filterArrTmp = [];
  11381. if (is_string($filterRaw) && $filterRaw !== '') {
  11382. $filterArrTmp = (array)json_decode($filterRaw, true);
  11383. } elseif (is_array($filterRaw)) {
  11384. $filterArrTmp = $filterRaw;
  11385. }
  11386. $hasSearch = ($searchKw !== '');
  11387. if (!$hasSearch) {
  11388. foreach ($filterArrTmp as $fv) {
  11389. if (trim((string)$fv) !== '') {
  11390. $hasSearch = true;
  11391. break;
  11392. }
  11393. }
  11394. }
  11395. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11396. if (!is_array($dbRow)) {
  11397. return false;
  11398. }
  11399. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11400. if ($done['ts'] <= 0) {
  11401. return false;
  11402. }
  11403. if ($hasSearch) {
  11404. return true;
  11405. }
  11406. return date('Y-m', $done['ts']) === $ym;
  11407. }));
  11408. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11409. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11410. $mainBySid = [];
  11411. foreach ($pool as $rw) {
  11412. if (!is_array($rw)) {
  11413. continue;
  11414. }
  11415. $rid = (int)($rw['ID'] ?? 0);
  11416. if ($rid > 0) {
  11417. $mainBySid[$rid] = $rw;
  11418. }
  11419. }
  11420. if ($mainBySid === []) {
  11421. $detailRows = [];
  11422. } else {
  11423. try {
  11424. $detailRows = Db::table('purchase_order_detail')
  11425. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11426. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11427. ->order('status', 'desc')
  11428. ->order('CCYDH', 'asc')
  11429. ->order('company_name', 'asc')
  11430. ->order('id', 'asc')
  11431. ->select();
  11432. } catch (\Throwable $e) {
  11433. try {
  11434. $detailRows = Db::table('purchase_order_detail')
  11435. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11436. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11437. ->order('status', 'desc')
  11438. ->order('CCYDH', 'asc')
  11439. ->order('company_name', 'asc')
  11440. ->order('ID', 'asc')
  11441. ->select();
  11442. } catch (\Throwable $e2) {
  11443. $detailRows = [];
  11444. }
  11445. }
  11446. }
  11447. if (!is_array($detailRows)) {
  11448. $detailRows = [];
  11449. }
  11450. $exportLines = [];
  11451. $detailSidSeen = [];
  11452. foreach ($detailRows as $dr) {
  11453. if (!is_array($dr)) {
  11454. continue;
  11455. }
  11456. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11457. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11458. continue;
  11459. }
  11460. if (isset($detailSidSeen[$sid])) {
  11461. continue;
  11462. }
  11463. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11464. continue;
  11465. }
  11466. $detailSidSeen[$sid] = true;
  11467. $m = $mainBySid[$sid];
  11468. $exportLines[] = [
  11469. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11470. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11471. 'company_name' => (string)($dr['company_name'] ?? ''),
  11472. 'CDF' => (string)($m['CDF'] ?? ''),
  11473. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11474. 'gx' => $this->procuremenExportGxText($m),
  11475. 'detail' => $dr,
  11476. ];
  11477. }
  11478. foreach ($detailRows as $dr) {
  11479. if (!is_array($dr)) {
  11480. continue;
  11481. }
  11482. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11483. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11484. continue;
  11485. }
  11486. $detailSidSeen[$sid] = true;
  11487. $m = $mainBySid[$sid];
  11488. $exportLines[] = [
  11489. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11490. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11491. 'company_name' => (string)($dr['company_name'] ?? ''),
  11492. 'CDF' => (string)($m['CDF'] ?? ''),
  11493. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11494. 'gx' => $this->procuremenExportGxText($m),
  11495. 'detail' => $dr,
  11496. ];
  11497. }
  11498. foreach ($mainBySid as $sid => $m) {
  11499. if (isset($detailSidSeen[$sid])) {
  11500. continue;
  11501. }
  11502. $company = trim((string)($m['pick_company_name'] ?? ''));
  11503. $exportLines[] = [
  11504. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11505. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11506. 'company_name' => $company,
  11507. 'CDF' => (string)($m['CDF'] ?? ''),
  11508. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11509. 'gx' => $this->procuremenExportGxText($m),
  11510. 'detail' => [],
  11511. ];
  11512. }
  11513. $groups = [];
  11514. foreach ($exportLines as $line) {
  11515. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11516. if (!isset($groups[$k])) {
  11517. $groups[$k] = [];
  11518. }
  11519. $groups[$k][] = $line;
  11520. }
  11521. ksort($groups, SORT_STRING);
  11522. return [
  11523. 'ym' => $ym,
  11524. 'mainBySid' => $mainBySid,
  11525. 'detailRows' => $detailRows,
  11526. 'exportLines' => $exportLines,
  11527. 'groups' => $groups,
  11528. ];
  11529. }
  11530. /**
  11531. * 导出用:工序列文案
  11532. */
  11533. protected function procuremenExportGxText(array $r)
  11534. {
  11535. $a = trim((string)($r['CDXMC'] ?? ''));
  11536. $b = trim((string)($r['CGYMC'] ?? ''));
  11537. if ($a !== '' && $b !== '') {
  11538. return $a . ':' . $b;
  11539. }
  11540. return $a !== '' ? $a : $b;
  11541. }
  11542. /**
  11543. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  11544. */
  11545. protected function procuremenExportAmount(array $r)
  11546. {
  11547. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  11548. if (!array_key_exists($k, $r)) {
  11549. continue;
  11550. }
  11551. $v = $r[$k];
  11552. if ($v === null || $v === '') {
  11553. continue;
  11554. }
  11555. if (is_numeric($v)) {
  11556. return (float)$v;
  11557. }
  11558. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  11559. if ($v !== '' && is_numeric($v)) {
  11560. return (float)$v;
  11561. }
  11562. }
  11563. return 0.0;
  11564. }
  11565. /**
  11566. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  11567. *
  11568. * @param array<int, array<string, mixed>> $detailRows
  11569. * @param array<int, array<string, mixed>> $mainBySid
  11570. * @return array<int, array<string, mixed>>
  11571. */
  11572. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  11573. {
  11574. $lines = [];
  11575. foreach ($detailRows as $dr) {
  11576. if (!is_array($dr)) {
  11577. continue;
  11578. }
  11579. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11580. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11581. continue;
  11582. }
  11583. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  11584. continue;
  11585. }
  11586. $cn = trim((string)($dr['company_name'] ?? ''));
  11587. if ($cn === '') {
  11588. continue;
  11589. }
  11590. $m = $mainBySid[$sid];
  11591. $am = trim((string)($dr['amount'] ?? ''));
  11592. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  11593. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  11594. $amountText = $amountFilled
  11595. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  11596. : '未填写';
  11597. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  11598. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  11599. if ($deliveryShow === '' && $deliveryRaw !== '') {
  11600. $deliveryShow = $deliveryRaw;
  11601. }
  11602. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  11603. ? $deliveryShow
  11604. : '未填写';
  11605. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  11606. $lines[] = [
  11607. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11608. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11609. 'gx' => $this->procuremenExportGxText($m),
  11610. 'company_name' => $cn,
  11611. 'amount_text' => $amountText,
  11612. 'amount_num' => $amountFilled ? $amountNum : null,
  11613. 'delivery_text' => $deliveryText,
  11614. 'picked_text' => $picked ? '中标' : '未中标',
  11615. 'picked' => $picked,
  11616. ];
  11617. }
  11618. $winnerSupplierByOrder = [];
  11619. foreach ($lines as $line) {
  11620. $dh = trim((string)($line['CCYDH'] ?? ''));
  11621. $cn = trim((string)($line['company_name'] ?? ''));
  11622. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  11623. $winnerSupplierByOrder[$dh][$cn] = true;
  11624. }
  11625. }
  11626. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  11627. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  11628. if ($c !== 0) {
  11629. return $c;
  11630. }
  11631. $dh = trim((string)($a['CCYDH'] ?? ''));
  11632. $aCn = trim((string)($a['company_name'] ?? ''));
  11633. $bCn = trim((string)($b['company_name'] ?? ''));
  11634. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  11635. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  11636. if ($aSupplierWin !== $bSupplierWin) {
  11637. return $aSupplierWin ? -1 : 1;
  11638. }
  11639. $c = strcmp($aCn, $bCn);
  11640. if ($c !== 0) {
  11641. return $c;
  11642. }
  11643. if (!empty($a['picked']) !== !empty($b['picked'])) {
  11644. return !empty($a['picked']) ? -1 : 1;
  11645. }
  11646. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  11647. if ($c !== 0) {
  11648. return $c;
  11649. }
  11650. return 0;
  11651. });
  11652. return $lines;
  11653. }
  11654. /**
  11655. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  11656. *
  11657. * @param array<int, array<string, mixed>> $quoteLines
  11658. */
  11659. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  11660. {
  11661. $mon = (int)substr($ym, 5, 2);
  11662. $titleRow = $startRow;
  11663. $headerRow = $startRow + 1;
  11664. $dataStartRow = $startRow + 2;
  11665. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  11666. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  11667. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  11668. $sheet->getStyle('A' . $titleRow)->getAlignment()
  11669. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11670. ->setVertical(Alignment::VERTICAL_CENTER);
  11671. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  11672. $col = 'A';
  11673. foreach ($headers as $h) {
  11674. $sheet->setCellValue($col . $headerRow, $h);
  11675. $col++;
  11676. }
  11677. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  11678. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11679. $rowNum = $dataStartRow;
  11680. if ($quoteLines === []) {
  11681. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  11682. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  11683. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11684. $rowNum = $dataStartRow + 1;
  11685. } else {
  11686. $i = 0;
  11687. foreach ($quoteLines as $line) {
  11688. $i++;
  11689. $sheet->setCellValue('A' . $rowNum, $i);
  11690. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  11691. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  11692. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  11693. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  11694. if ($line['amount_num'] !== null) {
  11695. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  11696. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  11697. } else {
  11698. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  11699. }
  11700. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  11701. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  11702. if (!empty($line['picked'])) {
  11703. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11704. }
  11705. $rowNum++;
  11706. }
  11707. }
  11708. $lastRow = $rowNum - 1;
  11709. if ($lastRow >= $headerRow) {
  11710. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  11711. 'borders' => [
  11712. 'allBorders' => [
  11713. 'borderStyle' => Border::BORDER_THIN,
  11714. 'color' => ['rgb' => '000000'],
  11715. ],
  11716. ],
  11717. ]);
  11718. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11719. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11720. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11721. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11722. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  11723. if ($lastRow >= $dataStartRow) {
  11724. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  11725. }
  11726. }
  11727. return $lastRow;
  11728. }
  11729. /**
  11730. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  11731. */
  11732. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  11733. {
  11734. if ($lastRow < $dataStartRow || $headerRow < 1) {
  11735. return;
  11736. }
  11737. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  11738. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11739. ->setVertical(Alignment::VERTICAL_CENTER);
  11740. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  11741. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11742. ->setVertical(Alignment::VERTICAL_CENTER);
  11743. if ($lastCol > 'B') {
  11744. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  11745. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11746. ->setVertical(Alignment::VERTICAL_CENTER);
  11747. }
  11748. }
  11749. /**
  11750. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  11751. */
  11752. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  11753. {
  11754. $s = trim($ccydh);
  11755. if ($s === '') {
  11756. return 'ORDER';
  11757. }
  11758. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  11759. $s = trim($s, '._-');
  11760. if ($s === '') {
  11761. return 'ORDER';
  11762. }
  11763. if (function_exists('mb_substr')) {
  11764. return mb_substr($s, 0, 80, 'UTF-8');
  11765. }
  11766. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  11767. }
  11768. /**
  11769. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  11770. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  11771. *
  11772. * @return array{objectKey: string, webPath: string}
  11773. */
  11774. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  11775. {
  11776. $sid = (int)$scydgyId;
  11777. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  11778. $y = date('Y');
  11779. $m = date('m');
  11780. $d = date('d');
  11781. $basename = $safeOrder . '_' . $sid . '.pdf';
  11782. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  11783. return [
  11784. 'objectKey' => $objectKey,
  11785. 'webPath' => '/' . $objectKey,
  11786. ];
  11787. }
  11788. /**
  11789. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  11790. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  11791. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  11792. *
  11793. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  11794. */
  11795. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  11796. {
  11797. if (!$this->isValidScydgyRowId($scydgyId)) {
  11798. return '';
  11799. }
  11800. $ids = trim((string)$scydgyId);
  11801. $prep = $this->prepareProcuremenDetailsView($ids);
  11802. if (!$prep['ok']) {
  11803. return '';
  11804. }
  11805. $ccydh = $prep['ccydh'];
  11806. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  11807. $objectKey = $paths['objectKey'];
  11808. $webPath = $paths['webPath'];
  11809. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  11810. $this->view->assign([
  11811. 'pdf_export' => 1,
  11812. 'pdfMetaLine' => $meta,
  11813. ]);
  11814. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  11815. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11816. $this->view->engine->layout(false);
  11817. try {
  11818. $html = $this->view->fetch('procuremen/details_pdf_shell');
  11819. } catch (\Throwable $e) {
  11820. if ($restoreLayout) {
  11821. $this->view->engine->layout($restoreLayout);
  11822. }
  11823. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  11824. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  11825. return '';
  11826. }
  11827. if ($restoreLayout) {
  11828. $this->view->engine->layout($restoreLayout);
  11829. }
  11830. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  11831. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  11832. if (!is_dir($tempDir)) {
  11833. @mkdir($tempDir, 0755, true);
  11834. }
  11835. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  11836. try {
  11837. $mpdf = new \Mpdf\Mpdf([
  11838. 'mode' => 'utf-8',
  11839. 'format' => 'A4',
  11840. 'margin_left' => 12,
  11841. 'margin_right' => 12,
  11842. 'margin_top' => 14,
  11843. 'margin_bottom' => 14,
  11844. 'tempDir' => $tempDir,
  11845. 'autoScriptToLang' => true,
  11846. 'autoLangToFont' => true,
  11847. ]);
  11848. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  11849. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  11850. $mpdf->SetBasePath('http://127.0.0.1/');
  11851. $mpdf->WriteHTML($html);
  11852. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  11853. } catch (\Throwable $e) {
  11854. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  11855. if (is_file($tempPdf)) {
  11856. @unlink($tempPdf);
  11857. }
  11858. return '';
  11859. }
  11860. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  11861. if ($ossUrl !== '') {
  11862. @unlink($tempPdf);
  11863. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  11864. return $ossUrl;
  11865. }
  11866. $pi = pathinfo($objectKey);
  11867. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  11868. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  11869. if ($baseFile === '') {
  11870. @unlink($tempPdf);
  11871. return '';
  11872. }
  11873. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  11874. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  11875. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  11876. @unlink($tempPdf);
  11877. return '';
  11878. }
  11879. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  11880. if (!@copy($tempPdf, $fullPath)) {
  11881. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  11882. @unlink($tempPdf);
  11883. return '';
  11884. }
  11885. @unlink($tempPdf);
  11886. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  11887. return $webPath;
  11888. }
  11889. /**
  11890. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  11891. */
  11892. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  11893. {
  11894. if ($scydgyId <= 0 || $webPath === '') {
  11895. return;
  11896. }
  11897. try {
  11898. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  11899. } catch (\Throwable $e) {
  11900. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  11901. }
  11902. }
  11903. /**
  11904. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  11905. *
  11906. * @param array<string, string> $vars
  11907. * @return array<string, string>
  11908. */
  11909. protected function normalizeSmsTemplateVars(array $vars): array
  11910. {
  11911. $out = [];
  11912. foreach ($vars as $k => $v) {
  11913. $out[(string)$k] = trim((string)$v);
  11914. }
  11915. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  11916. $out['contact_name'] = $out['company_name'];
  11917. }
  11918. return $out;
  11919. }
  11920. /**
  11921. * 按手机号或公司名称查 customer 表联系人姓名
  11922. */
  11923. protected function resolveCustomerContactName(string $phone, string $companyName): string
  11924. {
  11925. $phone = trim($phone);
  11926. $companyName = trim($companyName);
  11927. try {
  11928. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  11929. $row = Db::table('customer')
  11930. ->where(function ($q) use ($phone) {
  11931. $q->where('phone', $phone)->whereOr('account', $phone);
  11932. })
  11933. ->order('id', 'asc')
  11934. ->find();
  11935. if (is_array($row)) {
  11936. $nm = trim((string)($row['username'] ?? ''));
  11937. if ($nm !== '') {
  11938. return $nm;
  11939. }
  11940. }
  11941. }
  11942. if ($companyName !== '') {
  11943. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  11944. if (is_array($row)) {
  11945. return trim((string)($row['username'] ?? ''));
  11946. }
  11947. }
  11948. } catch (\Throwable $e) {
  11949. }
  11950. return '';
  11951. }
  11952. /**
  11953. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  11954. */
  11955. protected function plainTextToHtmlEmailBody(string $text): string
  11956. {
  11957. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  11958. $parts = explode("\n", $text);
  11959. $out = [];
  11960. foreach ($parts as $line) {
  11961. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  11962. $out[] = $line;
  11963. } else {
  11964. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  11965. }
  11966. }
  11967. return implode("<br>\n", $out);
  11968. }
  11969. /**
  11970. * 短信场景:去掉链接类变量,避免误填 URL
  11971. *
  11972. * @param array<string, string> $vars
  11973. * @return array<string, string>
  11974. */
  11975. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  11976. {
  11977. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  11978. return $vars;
  11979. }
  11980. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  11981. $vars[$k] = '';
  11982. }
  11983. return $vars;
  11984. }
  11985. /**
  11986. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  11987. *
  11988. * @param array<string, string> $vars
  11989. */
  11990. protected function renderNotifyTemplate(string $scene, array $vars): string
  11991. {
  11992. $vars = $this->normalizeSmsTemplateVars($vars);
  11993. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  11994. $row = $this->loadNotifyTemplateRow($scene);
  11995. if ($row === null) {
  11996. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  11997. }
  11998. $tpl = trim((string)($row['content'] ?? ''));
  11999. if ($tpl === '') {
  12000. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12001. }
  12002. foreach ($vars as $k => $v) {
  12003. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12004. }
  12005. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12006. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12007. return $tpl;
  12008. }
  12009. protected function resolveProcuremenEmailSubject(string $scene): string
  12010. {
  12011. // 询价通知业务员:模版名称即邮件主题(可含 {ccydh})
  12012. if ($scene === 'rfq_salesman_email') {
  12013. $row = $this->loadNotifyTemplateRow($scene);
  12014. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12015. if ($title !== '') {
  12016. return $title;
  12017. }
  12018. return '协助采购询价通知';
  12019. }
  12020. $map = [
  12021. 'review_email' => '您有新的协助加工订单',
  12022. ];
  12023. $subject = trim((string)($map[$scene] ?? ''));
  12024. if ($subject === '') {
  12025. $this->error('未配置邮件主题:' . $scene);
  12026. }
  12027. return $subject;
  12028. }
  12029. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12030. {
  12031. $map = [
  12032. 'review_email' => '协助下发-邮箱',
  12033. 'review_sms' => '协助下发-短信',
  12034. 'confirm_ok' => '采购确认-通过',
  12035. 'confirm_fail' => '采购确认-未通过',
  12036. 'bid_open' => '开标双重验证',
  12037. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12038. ];
  12039. $label = $map[$scene] ?? $scene;
  12040. if ($titleRequired) {
  12041. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12042. }
  12043. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12044. }
  12045. /**
  12046. * 是否开启协助通知演练(不发真实短信/邮件)
  12047. */
  12048. protected function isProcuremenNotifyDryRun(): bool
  12049. {
  12050. return (bool)Config::get('procuremen_notify_dry_run');
  12051. }
  12052. /**
  12053. * @param array<string, mixed> $payload
  12054. */
  12055. protected function recordNotifyDryRunPreview(array $payload): void
  12056. {
  12057. $this->notifyDryRunPreview[] = $payload;
  12058. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12059. }
  12060. /**
  12061. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12062. * @throws \Exception
  12063. */
  12064. protected function smsbao($phone, $content)
  12065. {
  12066. if ($this->isProcuremenNotifyDryRun()) {
  12067. $this->recordNotifyDryRunPreview([
  12068. 'scene' => 'sms_only',
  12069. 'phone' => $phone,
  12070. 'sms_content' => $content,
  12071. ]);
  12072. return;
  12073. }
  12074. $statusStr = [
  12075. '0' => '短信发送成功',
  12076. '-1' => '参数不全',
  12077. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12078. '30' => '密码错误',
  12079. '40' => '账号不存在',
  12080. '41' => '余额不足',
  12081. '42' => '帐户已过期',
  12082. '43' => 'IP地址限制',
  12083. '50' => '内容含有敏感词',
  12084. ];
  12085. $smsapi = 'http://api.smsbao.com/';
  12086. $user = 'zhuwei123';
  12087. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12088. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12089. $result = @file_get_contents($sendurl);
  12090. if ($result === false) {
  12091. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12092. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12093. }
  12094. $result = trim((string)$result);
  12095. if ($result !== '0') {
  12096. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12097. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12098. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12099. }
  12100. }
  12101. }