Procuremen.php 496 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188
  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', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  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. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  241. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen']),
  242. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers']),
  243. 'rfqissue' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue']),
  244. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue']),
  246. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers']),
  247. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  248. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  249. ];
  250. $this->assignconfig('procuremenAuth', $authMap);
  251. }
  252. /**
  253. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  254. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  255. *
  256. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  257. */
  258. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  259. {
  260. static $mprocCfgLoaded = false;
  261. if (!$mprocCfgLoaded) {
  262. $mprocCfgLoaded = true;
  263. if (is_file(APP_PATH . 'extra/mproc.php')) {
  264. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  265. }
  266. }
  267. $eid = (int)$purchaseOrderDetailId;
  268. $base = $this->resolveMprocMobilePublicBaseUrl();
  269. if ($base === '') {
  270. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  271. }
  272. $path = trim((string)Config::get('mproc.mobile_index_path'));
  273. if ($path === '') {
  274. $path = '/index.php/index/index/index';
  275. } else {
  276. $path = '/' . ltrim($path, '/');
  277. }
  278. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  279. if ($eid > 0) {
  280. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  281. }
  282. return $base . $path . '?main_tab=orders';
  283. }
  284. /**
  285. * 邮件/短信外链:须为带点的公网域名
  286. */
  287. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  288. {
  289. $u = trim((string)$baseUrl);
  290. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  291. return false;
  292. }
  293. $host = parse_url($u, PHP_URL_HOST);
  294. if (!is_string($host) || $host === '') {
  295. return false;
  296. }
  297. if (strcasecmp($host, 'localhost') === 0) {
  298. return false;
  299. }
  300. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  301. return false;
  302. }
  303. if (strpos($host, '.') === false) {
  304. return false;
  305. }
  306. return true;
  307. }
  308. /**
  309. * 解析用于协助邮件/短信的手机端站点根
  310. */
  311. protected function resolveMprocMobilePublicBaseUrl()
  312. {
  313. $candidates = [];
  314. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  315. $candidates[] = trim((string)Config::get('site.indexurl'));
  316. $cdn = trim((string)Config::get('site.cdnurl'));
  317. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  318. $candidates[] = rtrim($cdn, '/');
  319. }
  320. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  321. $candidates[] = $reqBase;
  322. foreach ($candidates as $c) {
  323. if ($c === '') {
  324. continue;
  325. }
  326. $c = rtrim($c, '/');
  327. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  328. return $c;
  329. }
  330. }
  331. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  332. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  333. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  334. return $reqBase;
  335. }
  336. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  337. return '';
  338. }
  339. /**
  340. * 获取 Redis 中 procuremen_redis
  341. */
  342. protected function ProcuremenRedis(): array
  343. {
  344. if ($this->procuremenRedisCache !== null) {
  345. return $this->procuremenRedisCache;
  346. }
  347. try {
  348. $redis = redis();
  349. $raw = $redis->get('procuremen_redis');
  350. if ($raw === false || $raw === '') {
  351. $this->procuremenRedisCache = [];
  352. return $this->procuremenRedisCache;
  353. }
  354. $decoded = json_decode($raw, true);
  355. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  356. $this->procuremenRedisCache = [];
  357. return $this->procuremenRedisCache;
  358. }
  359. $this->procuremenRedisCache = $decoded['data'];
  360. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  361. if ($this->loadProcuremenSidebarYmList() === []) {
  362. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  363. }
  364. return $this->procuremenRedisCache;
  365. } catch (\Throwable $e) {
  366. $this->procuremenRedisCache = [];
  367. return $this->procuremenRedisCache;
  368. }
  369. }
  370. /**
  371. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  372. *
  373. * @return array<int, array<string, mixed>>
  374. */
  375. protected function procuremenFetchErpPoolFromDb(): array
  376. {
  377. try {
  378. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  379. $endTime = date('Y-m-d 23:59:59');
  380. $list = Db::table('scydgy')
  381. ->alias('a')
  382. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  383. ->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')
  384. ->where([
  385. 'a.bwjg' => 1,
  386. 'a.iEndBz' => 0,
  387. 'a.iType' => 0,
  388. 'a.iStatus' => 10,
  389. ])
  390. ->where('a.dStamp', '>=', $startTime)
  391. ->where('a.dStamp', '<=', $endTime)
  392. ->order('a.dStamp', 'desc')
  393. ->select();
  394. if (!is_array($list)) {
  395. return [];
  396. }
  397. try {
  398. $redis = redis();
  399. $payload = [
  400. 'code' => 200,
  401. 'msg' => 'success',
  402. 'data' => $list,
  403. ];
  404. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  405. $this->procuremenRedisCache = $list;
  406. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  407. $this->clearPickMonthPoolCaches();
  408. $this->warmPickMonthPoolCachesFromPool($list);
  409. } catch (\Throwable $e) {
  410. }
  411. return $list;
  412. } catch (\Throwable $e) {
  413. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  414. return [];
  415. }
  416. }
  417. /**
  418. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  419. *
  420. * @return array<int, array<string, mixed>>
  421. */
  422. protected function procuremenEnsureRedisPool(): array
  423. {
  424. $pool = $this->ProcuremenRedis();
  425. if (is_array($pool) && $pool !== []) {
  426. return $pool;
  427. }
  428. static $warmed = false;
  429. if ($warmed) {
  430. return is_array($pool) ? $pool : [];
  431. }
  432. $warmed = true;
  433. return $this->procuremenFetchErpPoolFromDb();
  434. }
  435. /**
  436. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  437. *
  438. * @param array<string, mixed> $row
  439. */
  440. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  441. {
  442. $t = $this->procuremenRowListSortTime($row, $primary);
  443. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  444. return null;
  445. }
  446. $mo = (int)$m[2];
  447. if ($mo < 1 || $mo > 12) {
  448. return null;
  449. }
  450. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  451. }
  452. /**
  453. * @param array<int, array{year:string, months:array}> $sidebar
  454. * @return array<int, array{year:string, months:array}>
  455. */
  456. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  457. {
  458. $ym = trim($ym);
  459. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  460. return $sidebar;
  461. }
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  468. return $sidebar;
  469. }
  470. }
  471. }
  472. $y = substr($ym, 0, 4);
  473. $mo = (int)substr($ym, 5, 2);
  474. $sidebar[] = [
  475. 'year' => $y,
  476. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  477. ];
  478. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  479. }
  480. /**
  481. * @param array<int, array{year:string, months:array}> $sidebar
  482. * @return string[]
  483. */
  484. protected function flattenProcuremenSidebarYms(array $sidebar): array
  485. {
  486. $yms = [];
  487. foreach ($sidebar as $block) {
  488. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  489. continue;
  490. }
  491. foreach ($block['months'] as $item) {
  492. if (!is_array($item)) {
  493. continue;
  494. }
  495. $ym = trim((string)($item['ym'] ?? ''));
  496. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  497. $yms[$ym] = true;
  498. }
  499. }
  500. }
  501. return array_keys($yms);
  502. }
  503. /**
  504. * 左侧菜单(协助初选)
  505. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  506. */
  507. protected function GetIndexYearMonths()
  508. {
  509. $ymList = $this->ensureProcuremenPickSidebarYmList();
  510. if ($ymList === []) {
  511. $def = date('Y-m');
  512. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  513. }
  514. return $this->buildYearMonthSidebar($ymList);
  515. }
  516. /**
  517. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  518. *
  519. * @return string[]
  520. */
  521. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  522. {
  523. static $memo = null;
  524. if (!$forceRefresh && is_array($memo)) {
  525. return $memo;
  526. }
  527. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  528. if ($fromDb !== []) {
  529. $this->saveProcuremenSidebarYmList($fromDb);
  530. $memo = $fromDb;
  531. return $memo;
  532. }
  533. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  534. $cached = $this->loadProcuremenSidebarYmList();
  535. if ($cached !== []) {
  536. $memo = $cached;
  537. return $memo;
  538. }
  539. $memo = [date('Y-m')];
  540. return $memo;
  541. }
  542. /**
  543. * @return string[] 形如 2026-07
  544. */
  545. protected function loadProcuremenSidebarYmList(): array
  546. {
  547. try {
  548. $raw = redis()->get('procuremen_redis_yms');
  549. if ($raw === false || $raw === null || $raw === '') {
  550. return [];
  551. }
  552. $decoded = json_decode((string)$raw, true);
  553. if (!is_array($decoded)) {
  554. return [];
  555. }
  556. $out = [];
  557. foreach ($decoded as $ym) {
  558. $ym = trim((string)$ym);
  559. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  560. $out[$ym] = true;
  561. }
  562. }
  563. return array_keys($out);
  564. } catch (\Throwable $e) {
  565. return [];
  566. }
  567. }
  568. /**
  569. * @param string[] $ymList
  570. */
  571. protected function saveProcuremenSidebarYmList(array $ymList): void
  572. {
  573. $out = [];
  574. foreach ($ymList as $ym) {
  575. $ym = trim((string)$ym);
  576. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  577. $out[$ym] = true;
  578. }
  579. }
  580. if ($out === []) {
  581. return;
  582. }
  583. try {
  584. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  585. } catch (\Throwable $e) {
  586. }
  587. }
  588. /**
  589. * @param array<int, array<string, mixed>> $pool
  590. * @return string[]
  591. */
  592. protected function extractYearMonthsFromPoolRows(array $pool): array
  593. {
  594. $ymSet = [];
  595. foreach ($pool as $r) {
  596. if (!is_array($r)) {
  597. continue;
  598. }
  599. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  600. continue;
  601. }
  602. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  603. if ($ym !== null) {
  604. $ymSet[$ym] = true;
  605. }
  606. }
  607. return array_keys($ymSet);
  608. }
  609. /**
  610. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  611. *
  612. * @return string[]
  613. */
  614. protected function queryProcuremenPickSidebarYmListLight(): array
  615. {
  616. try {
  617. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  618. $endTime = date('Y-m-d 23:59:59');
  619. $sql = 'SELECT DISTINCT DATE_FORMAT('
  620. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  621. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  622. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  623. . ' FROM scydgy a'
  624. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  625. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  626. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  627. $rows = Db::query($sql, [$startTime, $endTime]);
  628. if (!is_array($rows)) {
  629. return [];
  630. }
  631. $out = [];
  632. foreach ($rows as $r) {
  633. $ym = trim((string)($r['ym'] ?? ''));
  634. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  635. $out[$ym] = true;
  636. }
  637. }
  638. return array_keys($out);
  639. } catch (\Throwable $e) {
  640. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  641. return [];
  642. }
  643. }
  644. /**
  645. * @return string[] 含当月在内的近 N 个自然月
  646. */
  647. protected function buildRecentCalendarYmList(int $months = 12): array
  648. {
  649. $months = max(1, min(24, $months));
  650. $out = [];
  651. $base = strtotime(date('Y-m-01'));
  652. for ($i = 0; $i < $months; $i++) {
  653. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  654. }
  655. return $out;
  656. }
  657. /**
  658. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  659. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  660. *
  661. * @return array<int, array<string, mixed>>
  662. */
  663. protected function loadPickPoolForYm(string $ym): array
  664. {
  665. $ym = trim($ym);
  666. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  667. return [];
  668. }
  669. $hit = $this->readPickMonthPoolCache($ym);
  670. if ($hit !== null) {
  671. return $hit;
  672. }
  673. return $this->queryPickPoolForYmFromDb($ym);
  674. }
  675. /**
  676. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  677. */
  678. protected function readPickMonthPoolCache(string $ym): ?array
  679. {
  680. try {
  681. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  682. if ($raw === false || $raw === null || $raw === '') {
  683. return null;
  684. }
  685. $decoded = json_decode((string)$raw, true);
  686. if (!is_array($decoded)) {
  687. return null;
  688. }
  689. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  690. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  691. return $decoded['rows'];
  692. }
  693. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  694. if ($decoded === []) {
  695. try {
  696. redis()->del('procuremen_pick_pool:' . $ym);
  697. } catch (\Throwable $e) {
  698. }
  699. return null;
  700. }
  701. if (isset($decoded[0]) && is_array($decoded[0])) {
  702. return $decoded;
  703. }
  704. return null;
  705. } catch (\Throwable $e) {
  706. return null;
  707. }
  708. }
  709. /**
  710. * @param array<int, array<string, mixed>> $rows
  711. */
  712. protected function writePickMonthPoolCache(string $ym, array $rows): void
  713. {
  714. try {
  715. redis()->setex(
  716. 'procuremen_pick_pool:' . $ym,
  717. 600,
  718. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  719. );
  720. } catch (\Throwable $e) {
  721. }
  722. }
  723. /**
  724. * @param array<int, array<string, mixed>> $pool
  725. * @return array<int, array<string, mixed>>
  726. */
  727. protected function filterPoolRowsByYm(array $pool, string $ym): array
  728. {
  729. $out = [];
  730. foreach ($pool as $r) {
  731. if (!is_array($r)) {
  732. continue;
  733. }
  734. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  735. continue;
  736. }
  737. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  738. $out[] = $r;
  739. }
  740. }
  741. return $out;
  742. }
  743. /**
  744. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  745. *
  746. * @return array<int, array<string, mixed>>
  747. */
  748. protected function queryPickPoolForYmFromDb(string $ym): array
  749. {
  750. $monthStart = $ym . '-01 00:00:00';
  751. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  752. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  753. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  754. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  755. try {
  756. $list = Db::table('scydgy')
  757. ->alias('a')
  758. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  759. ->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')
  760. ->where([
  761. 'a.bwjg' => 1,
  762. 'a.iEndBz' => 0,
  763. 'a.iType' => 0,
  764. 'a.iStatus' => 10,
  765. ])
  766. ->where('a.dStamp', '>=', $queryStart)
  767. ->where('a.dStamp', '<=', $queryEnd)
  768. ->order('a.dStamp', 'desc')
  769. ->select();
  770. } catch (\Throwable $e) {
  771. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  772. return [];
  773. }
  774. if (!is_array($list)) {
  775. $list = [];
  776. }
  777. $out = $this->filterPoolRowsByYm($list, $ym);
  778. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  779. $this->writePickMonthPoolCache($ym, $out);
  780. try {
  781. $yms = $this->loadProcuremenSidebarYmList();
  782. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  783. $yms[] = $ym;
  784. $this->saveProcuremenSidebarYmList($yms);
  785. }
  786. } catch (\Throwable $e) {
  787. }
  788. return $out;
  789. }
  790. /**
  791. * 整包写入后拆成按月小缓存,供初选列表秒开
  792. *
  793. * @param array<int, array<string, mixed>> $pool
  794. */
  795. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  796. {
  797. if ($pool === []) {
  798. return;
  799. }
  800. $byYm = [];
  801. foreach ($pool as $r) {
  802. if (!is_array($r)) {
  803. continue;
  804. }
  805. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  806. continue;
  807. }
  808. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  809. if ($rowYm === null) {
  810. continue;
  811. }
  812. $byYm[$rowYm][] = $r;
  813. }
  814. if ($byYm === []) {
  815. return;
  816. }
  817. try {
  818. $redis = redis();
  819. foreach ($byYm as $rowYm => $rows) {
  820. $redis->setex(
  821. 'procuremen_pick_pool:' . $rowYm,
  822. 600,
  823. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  824. );
  825. }
  826. try {
  827. $redis->del('procuremen_pick_hidden_scydgy_v1');
  828. } catch (\Throwable $e) {
  829. }
  830. } catch (\Throwable $e) {
  831. }
  832. }
  833. /**
  834. * 刷新整包后清理近月缓存,避免脏读
  835. */
  836. protected function clearPickMonthPoolCaches(int $months = 24): void
  837. {
  838. try {
  839. $redis = redis();
  840. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  841. try {
  842. $redis->del('procuremen_pick_pool:' . $ym);
  843. } catch (\Throwable $e) {
  844. }
  845. }
  846. } catch (\Throwable $e) {
  847. }
  848. $this->invalidatePickHiddenScydgyCache();
  849. }
  850. /**
  851. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  852. */
  853. protected function invalidatePickHiddenScydgyCache(): void
  854. {
  855. $this->pickHiddenScydgySetCache = null;
  856. try {
  857. redis()->del('procuremen_pick_hidden_scydgy_v1');
  858. } catch (\Throwable $e) {
  859. }
  860. }
  861. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  862. protected function procuremenReleaseSessionLock(): void
  863. {
  864. if (session_status() === PHP_SESSION_ACTIVE) {
  865. @session_write_close();
  866. }
  867. }
  868. /**
  869. * @param string[] $ymList 形如 2026-06
  870. * @return array<int, array{year:string, months:array}>
  871. */
  872. protected function buildYearMonthSidebar(array $ymList): array
  873. {
  874. rsort($ymList, SORT_STRING);
  875. $byYear = [];
  876. foreach ($ymList as $ym) {
  877. $y = substr($ym, 0, 4);
  878. $mo = (int)substr($ym, 5, 2);
  879. if (!isset($byYear[$y])) {
  880. $byYear[$y] = [];
  881. }
  882. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  883. }
  884. krsort($byYear, SORT_NUMERIC);
  885. foreach ($byYear as $y => $items) {
  886. usort($byYear[$y], function ($a, $b) {
  887. return strcmp($b['ym'], $a['ym']);
  888. });
  889. }
  890. $sidebar = [];
  891. foreach ($byYear as $y => $months) {
  892. $sidebar[] = ['year' => $y, 'months' => $months];
  893. }
  894. return $sidebar;
  895. }
  896. /**
  897. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  898. */
  899. protected function GetIssuedOrderYearMonths(string $stage): array
  900. {
  901. $ymSet = [];
  902. try {
  903. $query = Db::table('purchase_order');
  904. $this->applyPurchaseOrderNotDeletedWhere($query);
  905. if ($stage === 'audit') {
  906. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  907. } elseif ($stage === 'confirm') {
  908. $this->applyPurchaseOrderConfirmStageWhere($query);
  909. } else {
  910. return $this->GetIndexYearMonths();
  911. }
  912. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  913. if (is_array($rows)) {
  914. foreach ($rows as $r) {
  915. if (!is_array($r)) {
  916. continue;
  917. }
  918. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  919. if ($ym !== null) {
  920. $ymSet[$ym] = true;
  921. }
  922. }
  923. }
  924. } catch (\Throwable $e) {
  925. $ymSet = [];
  926. }
  927. $ymList = array_keys($ymSet);
  928. if ($ymList === []) {
  929. $def = $this->resolveProcuremenDefaultYm($stage);
  930. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  931. }
  932. return $this->buildYearMonthSidebar($ymList);
  933. }
  934. /**
  935. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  936. */
  937. protected function resolveProcuremenDefaultYm(string $stage): string
  938. {
  939. if ($stage === 'pick') {
  940. $yms = $this->ensureProcuremenPickSidebarYmList();
  941. if ($yms !== []) {
  942. rsort($yms, SORT_STRING);
  943. return $yms[0];
  944. }
  945. return date('Y-m');
  946. }
  947. try {
  948. $query = Db::table('purchase_order');
  949. $this->applyPurchaseOrderNotDeletedWhere($query);
  950. if ($stage === 'audit') {
  951. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  952. } elseif ($stage === 'confirm') {
  953. $this->applyPurchaseOrderConfirmStageWhere($query);
  954. } else {
  955. return date('Y-m');
  956. }
  957. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  958. if ($latest === null || $latest === '') {
  959. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  960. }
  961. $t = $this->formatProcuremenDetailTime($latest);
  962. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  963. return $m[1] . '-' . $m[2];
  964. }
  965. } catch (\Throwable $e) {
  966. }
  967. return date('Y-m');
  968. }
  969. protected function applyPurchaseOrderNotDeletedWhere($query): void
  970. {
  971. $query->whereRaw(
  972. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  973. );
  974. }
  975. /**
  976. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  977. */
  978. protected function applyPurchaseOrderConfirmStageWhere($query): void
  979. {
  980. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  981. $quoted = [];
  982. foreach ($vals as $v) {
  983. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  984. }
  985. if ($quoted === []) {
  986. $query->whereRaw('1 = 0');
  987. return;
  988. }
  989. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  990. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  991. }
  992. /**
  993. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  994. *
  995. * @param array<string, mixed> $row
  996. * @return array<string, mixed>
  997. */
  998. protected function normalizePurchaseOrderListTimeRow(array $row): array
  999. {
  1000. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1001. $pick = trim((string)($row['pick_time'] ?? ''));
  1002. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1003. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1004. $t = trim((string)($row[$key] ?? ''));
  1005. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1006. $row['pick_time'] = $t;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. return $row;
  1012. }
  1013. /**
  1014. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1015. */
  1016. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1017. {
  1018. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1019. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1020. }
  1021. if ($pool === []) {
  1022. $def = $this->resolveProcuremenDefaultYm($stage);
  1023. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1024. }
  1025. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1026. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1027. return false;
  1028. }
  1029. $monthStart = $ym . '-01 00:00:00';
  1030. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1031. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1032. return $probe !== [];
  1033. };
  1034. if ($tryYm($requestedYm)) {
  1035. return $requestedYm;
  1036. }
  1037. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1038. if ($tryYm($fallback)) {
  1039. return $fallback;
  1040. }
  1041. $bestYm = '';
  1042. $bestTime = '';
  1043. foreach ($pool as $row) {
  1044. if (!is_array($row)) {
  1045. continue;
  1046. }
  1047. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1048. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1049. continue;
  1050. }
  1051. $ymRow = $m[1];
  1052. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1053. $bestTime = $t;
  1054. $bestYm = $ymRow;
  1055. }
  1056. }
  1057. if ($bestYm !== '') {
  1058. return $bestYm;
  1059. }
  1060. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1061. }
  1062. protected function isPurchaseOrderDetailVoid(array $row): bool
  1063. {
  1064. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1065. return true;
  1066. }
  1067. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1068. }
  1069. /**
  1070. * 仅当前有效下发明细(排除废弃归档)
  1071. */
  1072. protected function applyActivePurchaseOrderDetailWhere($query): void
  1073. {
  1074. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1075. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1076. }
  1077. /**
  1078. * @param array<string, mixed> $detailRow
  1079. */
  1080. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1081. {
  1082. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1083. return false;
  1084. }
  1085. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1086. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1087. }
  1088. /**
  1089. * 废弃退回初选:下发明细标记归档,不物理删除
  1090. *
  1091. * @param array<int, int|string> $scydgyIds
  1092. */
  1093. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1094. {
  1095. $ids = [];
  1096. foreach ($scydgyIds as $sid) {
  1097. $n = (int)$sid;
  1098. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1099. $ids[$n] = true;
  1100. }
  1101. }
  1102. if ($ids === []) {
  1103. return;
  1104. }
  1105. $void = ProcuremenStatus::POD_VOID;
  1106. Db::table('purchase_order_detail')
  1107. ->where('scydgy_id', 'in', array_keys($ids))
  1108. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1109. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1110. ->update([
  1111. 'status' => $void,
  1112. 'status_name' => $void,
  1113. ]);
  1114. }
  1115. /**
  1116. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1117. */
  1118. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1119. {
  1120. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1121. $norm = function (string $col) use ($p): string {
  1122. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1123. };
  1124. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1125. $parts = [];
  1126. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1127. if ($key === 'createtime') {
  1128. $parts[] = $createtime;
  1129. } else {
  1130. $parts[] = $norm($key);
  1131. }
  1132. }
  1133. return 'COALESCE(' . implode(', ', $parts) . ')';
  1134. }
  1135. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1136. {
  1137. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1138. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1139. }
  1140. /**
  1141. * @return array<int, array<string, mixed>>
  1142. */
  1143. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1144. {
  1145. $this->ensurePurchaseOrderCzlyqColumn();
  1146. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1147. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1148. try {
  1149. $query = Db::table('purchase_order')->field($fields);
  1150. $this->applyPurchaseOrderNotDeletedWhere($query);
  1151. if ($stage === 'audit') {
  1152. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1153. } elseif ($stage === 'confirm') {
  1154. $this->applyPurchaseOrderConfirmStageWhere($query);
  1155. } else {
  1156. return [];
  1157. }
  1158. $query->order('pick_time', 'desc')->order('id', 'desc');
  1159. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1160. $monthStart = $ym . '-01 00:00:00';
  1161. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1162. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1163. }
  1164. $rows = $query->select();
  1165. } catch (\Throwable $e) {
  1166. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1167. $rows = [];
  1168. }
  1169. return is_array($rows) ? $rows : [];
  1170. }
  1171. /**
  1172. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1173. */
  1174. protected function resolveProcuremenListStage(): string
  1175. {
  1176. $tab = trim((string)$this->request->request('wff_tab', ''));
  1177. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1178. return $tab;
  1179. }
  1180. $action = strtolower((string)$this->request->action());
  1181. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1182. return $action;
  1183. }
  1184. return 'pick';
  1185. }
  1186. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1187. {
  1188. $this->procuremenReleaseSessionLock();
  1189. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1190. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1191. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1192. $indexPhpRoot = $rootTrue . '/index.php';
  1193. }
  1194. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1195. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1196. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1197. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1198. $this->view->assign('defaultYm', $defaultYm);
  1199. $this->view->assign('sidebarYearMonths', $sidebar);
  1200. $this->view->assign('procuremenStage', $stage);
  1201. $this->view->assign('procuremenPageTitle', $pageTitle);
  1202. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1203. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1204. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1205. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1206. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1207. }
  1208. /**
  1209. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1210. *
  1211. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1212. */
  1213. protected function buildProcuremenFilterOptions(string $stage): array
  1214. {
  1215. $buckets = [
  1216. 'czlyq' => [],
  1217. 'CCLBMMC' => [],
  1218. 'cywyxm' => [],
  1219. 'CGYMC' => [],
  1220. ];
  1221. $maxPerField = 300;
  1222. try {
  1223. if ($stage === 'pick') {
  1224. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1225. return $buckets;
  1226. }
  1227. if (in_array($stage, ['audit', 'confirm'], true)) {
  1228. $this->ensurePurchaseOrderCzlyqColumn();
  1229. foreach (array_keys($buckets) as $field) {
  1230. try {
  1231. $query = Db::table('purchase_order')->field($field);
  1232. $this->applyPurchaseOrderNotDeletedWhere($query);
  1233. if ($stage === 'audit') {
  1234. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1235. } else {
  1236. $this->applyPurchaseOrderConfirmStageWhere($query);
  1237. }
  1238. $query->where($field, '<>', '')->whereNotNull($field);
  1239. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1240. if (!is_array($vals)) {
  1241. continue;
  1242. }
  1243. foreach ($vals as $v) {
  1244. $v = trim((string)$v);
  1245. if ($v !== '') {
  1246. $buckets[$field][$v] = $v;
  1247. }
  1248. }
  1249. } catch (\Throwable $e) {
  1250. // 单字段失败不影响其它
  1251. }
  1252. }
  1253. }
  1254. } catch (\Throwable $e) {
  1255. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1256. }
  1257. foreach ($buckets as &$set) {
  1258. if ($set !== []) {
  1259. ksort($set, SORT_STRING);
  1260. }
  1261. }
  1262. unset($set);
  1263. return $buckets;
  1264. }
  1265. /**
  1266. * filter JSON 是否含有效条件
  1267. *
  1268. * @param array<string, mixed> $filterArr
  1269. */
  1270. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1271. {
  1272. foreach ($filterArr as $v) {
  1273. if (is_array($v)) {
  1274. if (array_filter($v, function ($x) {
  1275. return $x !== '' && $x !== null;
  1276. })) {
  1277. return true;
  1278. }
  1279. } elseif ($v !== '' && $v !== null) {
  1280. return true;
  1281. }
  1282. }
  1283. return false;
  1284. }
  1285. /**
  1286. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1287. *
  1288. * @param array<string, mixed> $filterArr
  1289. * @param array<string, mixed> $opArr
  1290. */
  1291. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1292. {
  1293. if ($search !== '') {
  1294. return false;
  1295. }
  1296. foreach ($filterArr as $fk => $fv) {
  1297. if (is_array($fv)) {
  1298. continue;
  1299. }
  1300. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1301. continue;
  1302. }
  1303. if ($fv === null) {
  1304. continue;
  1305. }
  1306. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1307. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1308. if ($sym === '' || $sym === '=') {
  1309. continue;
  1310. }
  1311. return false;
  1312. }
  1313. return true;
  1314. }
  1315. /**
  1316. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1317. *
  1318. * @param array<int, mixed> $rows
  1319. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1320. */
  1321. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1322. {
  1323. $buckets = [
  1324. 'czlyq' => [],
  1325. 'CCLBMMC' => [],
  1326. 'cywyxm' => [],
  1327. 'CGYMC' => [],
  1328. ];
  1329. foreach ($rows as $r) {
  1330. if (!is_array($r)) {
  1331. continue;
  1332. }
  1333. foreach ($buckets as $field => &$set) {
  1334. if (count($set) >= $maxPerField) {
  1335. continue;
  1336. }
  1337. $v = trim((string)($r[$field] ?? ''));
  1338. if ($v !== '') {
  1339. $set[$v] = $v;
  1340. }
  1341. }
  1342. unset($set);
  1343. $full = true;
  1344. foreach ($buckets as $set) {
  1345. if (count($set) < $maxPerField) {
  1346. $full = false;
  1347. break;
  1348. }
  1349. }
  1350. if ($full) {
  1351. break;
  1352. }
  1353. }
  1354. foreach ($buckets as &$set) {
  1355. if ($set !== []) {
  1356. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1357. $normalized = [];
  1358. foreach ($set as $k => $v) {
  1359. $s = trim((string)(is_scalar($v) ? $v : $k));
  1360. if ($s === '') {
  1361. continue;
  1362. }
  1363. $normalized[$s] = $s;
  1364. }
  1365. ksort($normalized, SORT_STRING);
  1366. $set = $normalized;
  1367. }
  1368. }
  1369. unset($set);
  1370. return $buckets;
  1371. }
  1372. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1373. public function pick()
  1374. {
  1375. $this->request->filter(['strip_tags', 'trim']);
  1376. if (!$this->request->isAjax()) {
  1377. $this->assignProcuremenListPage('pick', '协助下发');
  1378. return $this->view->fetch('procuremen/index');
  1379. }
  1380. return $this->index();
  1381. }
  1382. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1383. public function audit()
  1384. {
  1385. $this->request->filter(['strip_tags', 'trim']);
  1386. if (!$this->request->isAjax()) {
  1387. $this->assignProcuremenListPage('audit', '确认供应商');
  1388. return $this->view->fetch('procuremen/index');
  1389. }
  1390. return $this->index();
  1391. }
  1392. /** 采购确认(定标) */
  1393. public function confirm()
  1394. {
  1395. $this->request->filter(['strip_tags', 'trim']);
  1396. if (!$this->request->isAjax()) {
  1397. $this->assignProcuremenListPage('confirm', '采购确认');
  1398. return $this->view->fetch('procuremen/index');
  1399. }
  1400. return $this->index();
  1401. }
  1402. /**
  1403. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1404. */
  1405. public function index()
  1406. {
  1407. $this->request->filter(['strip_tags', 'trim']);
  1408. if (!$this->request->isAjax()) {
  1409. $this->assignProcuremenListPage('pick', '协助下发');
  1410. return $this->view->fetch('procuremen/index');
  1411. }
  1412. if ($this->request->request('keyField')) {
  1413. return $this->selectpage();
  1414. }
  1415. $this->procuremenReleaseSessionLock();
  1416. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1417. $limit = max(10, min(500, (int)$limit));
  1418. $ym = $this->request->request('ym', '');
  1419. $ym = is_string($ym) ? trim($ym) : '';
  1420. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1421. $wffTab = $this->resolveProcuremenListStage();
  1422. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1423. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1424. ? $this->resolveProcuremenDefaultYm($wffTab)
  1425. : date('Y-m');
  1426. }
  1427. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1428. $ym = date('Y-m');
  1429. }
  1430. $monthStart = $ym . '-01 00:00:00';
  1431. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1432. $search = trim((string)$this->request->get('search', ''));
  1433. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1434. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1435. if (!is_array($filterArr)) {
  1436. $filterArr = [];
  1437. }
  1438. if (!is_array($opArr)) {
  1439. $opArr = [];
  1440. }
  1441. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1442. $bidOpenStatusFilter = '';
  1443. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1444. if (!array_key_exists($bidFk, $filterArr)) {
  1445. continue;
  1446. }
  1447. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1448. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1449. }
  1450. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1451. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1452. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1453. try {
  1454. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1455. if ($wffTab === 'audit') {
  1456. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1457. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1458. );
  1459. } elseif ($wffTab === 'confirm') {
  1460. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1461. if ($dbRows === []) {
  1462. try {
  1463. $dbRows = Db::table('purchase_order')
  1464. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1465. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1466. ->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%\')')
  1467. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1468. ->order('pick_time', 'desc')->order('id', 'desc')
  1469. ->select();
  1470. } catch (\Throwable $e) {
  1471. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1472. $dbRows = [];
  1473. }
  1474. }
  1475. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1476. if ($pool === []) {
  1477. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1478. }
  1479. } else {
  1480. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1481. if ($applyMonthRange) {
  1482. $pool = $this->loadPickPoolForYm($ym);
  1483. } else {
  1484. $pool = $this->procuremenEnsureRedisPool();
  1485. }
  1486. if (!is_array($pool)) {
  1487. $pool = [];
  1488. }
  1489. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1490. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1491. if ($pool !== [] && $hideSet !== []) {
  1492. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1493. if (!is_array($r)) {
  1494. return false;
  1495. }
  1496. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1497. return $id <= 0 || !isset($hideSet[$id]);
  1498. }));
  1499. }
  1500. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1501. if ($pool === []) {
  1502. return json([
  1503. 'total' => 0,
  1504. 'rows' => [],
  1505. 'activeYm' => $ym,
  1506. 'filterOptions' => (
  1507. (int)$offset === 0
  1508. && !$hasActiveSearch
  1509. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1510. )
  1511. ? $this->extractProcuremenFilterOptionsFromRows([])
  1512. : new \stdClass(),
  1513. ]);
  1514. }
  1515. }
  1516. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1517. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1518. $monthStart = $ym . '-01 00:00:00';
  1519. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1520. }
  1521. $filtered = $this->filterProcuremenIndexPool(
  1522. $pool,
  1523. $monthStart,
  1524. $monthEnd,
  1525. $applyMonthRange,
  1526. $search,
  1527. $filterArr,
  1528. $opArr,
  1529. $listTimePrimary
  1530. );
  1531. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1532. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1533. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1534. }
  1535. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1536. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1537. }
  1538. $sortField = 'ID';
  1539. if (is_string($sort) && $sort !== '') {
  1540. $parts = explode(',', $sort);
  1541. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1542. if ($sortField === '') {
  1543. $sortField = 'ID';
  1544. }
  1545. }
  1546. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1547. $nFiltered = count($filtered);
  1548. if ($nFiltered > 1) {
  1549. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1550. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1551. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1552. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1553. if ($ta === $tb) {
  1554. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1555. }
  1556. if ($ta === '') {
  1557. return 1;
  1558. }
  1559. if ($tb === '') {
  1560. return -1;
  1561. }
  1562. return strcmp($ta, $tb) * $ord;
  1563. });
  1564. } elseif ($sortField === 'ID') {
  1565. $sortKeys = [];
  1566. foreach ($filtered as $i => $row) {
  1567. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1568. }
  1569. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1570. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1571. } elseif ($sortField === 'CCYDH') {
  1572. usort($filtered, function ($a, $b) use ($ord) {
  1573. $sa = trim((string)($a['CCYDH'] ?? ''));
  1574. $sb = trim((string)($b['CCYDH'] ?? ''));
  1575. if ($sa === $sb) {
  1576. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1577. }
  1578. if ($sa === '') {
  1579. return 1;
  1580. }
  1581. if ($sb === '') {
  1582. return -1;
  1583. }
  1584. return strcmp($sa, $sb) * $ord;
  1585. });
  1586. } else {
  1587. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1588. $va = $a[$sortField] ?? null;
  1589. $vb = $b[$sortField] ?? null;
  1590. $sa = (string)$va;
  1591. $sb = (string)$vb;
  1592. if ($sa === $sb) {
  1593. return 0;
  1594. }
  1595. return strcmp($sa, $sb) * $ord;
  1596. });
  1597. }
  1598. }
  1599. $offset = max(0, (int)$offset);
  1600. $limit = max(1, (int)$limit);
  1601. $rows = array_slice($filtered, $offset, $limit);
  1602. foreach ($rows as &$rw) {
  1603. if (!is_array($rw)) {
  1604. continue;
  1605. }
  1606. $rid = (int)($rw['ID'] ?? 0);
  1607. $rw['_iss_out'] = ($wffTab !== 'pick');
  1608. }
  1609. unset($rw);
  1610. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1611. $idList = [];
  1612. foreach ($rows as $rw) {
  1613. if (!is_array($rw)) {
  1614. continue;
  1615. }
  1616. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1617. foreach ($rw['_order_merge_rows'] as $mr) {
  1618. $mid = (int)($mr['ID'] ?? 0);
  1619. if ($this->isValidScydgyRowId($mid)) {
  1620. $idList[$mid] = true;
  1621. }
  1622. }
  1623. }
  1624. $id = (int)($rw['ID'] ?? 0);
  1625. if ($this->isValidScydgyRowId($id)) {
  1626. $idList[$id] = true;
  1627. }
  1628. }
  1629. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1630. foreach ($rows as &$rw) {
  1631. if (!is_array($rw)) {
  1632. continue;
  1633. }
  1634. $mergeIds = [];
  1635. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1636. foreach ($rw['_order_merge_rows'] as $mr) {
  1637. $mid = (int)($mr['ID'] ?? 0);
  1638. if ($this->isValidScydgyRowId($mid)) {
  1639. $mergeIds[$mid] = true;
  1640. }
  1641. }
  1642. }
  1643. $rid = (int)($rw['ID'] ?? 0);
  1644. if ($this->isValidScydgyRowId($rid)) {
  1645. $mergeIds[$rid] = true;
  1646. }
  1647. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1648. $rw['po_detail_count'] = $s['cnt'];
  1649. $rw['po_amount_fill_cnt'] = $s['amt'];
  1650. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1651. }
  1652. unset($rw);
  1653. }
  1654. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1655. $idList = [];
  1656. foreach ($rows as $rw) {
  1657. if (!is_array($rw)) {
  1658. continue;
  1659. }
  1660. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1661. foreach ($rw['_order_merge_rows'] as $mr) {
  1662. $mid = (int)($mr['ID'] ?? 0);
  1663. if ($this->isValidScydgyRowId($mid)) {
  1664. $idList[$mid] = true;
  1665. }
  1666. }
  1667. }
  1668. $id = (int)($rw['ID'] ?? 0);
  1669. if ($this->isValidScydgyRowId($id)) {
  1670. $idList[$id] = true;
  1671. }
  1672. }
  1673. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1674. $bidOpenSet = [];
  1675. $manualPickSet = [];
  1676. if ($wffTab === 'audit') {
  1677. $ccydhList = [];
  1678. foreach ($rows as $rw0) {
  1679. if (!is_array($rw0)) {
  1680. continue;
  1681. }
  1682. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1683. if ($c0 !== '') {
  1684. $ccydhList[] = $c0;
  1685. }
  1686. }
  1687. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1688. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1689. }
  1690. foreach ($rows as &$rw) {
  1691. if (!is_array($rw)) {
  1692. continue;
  1693. }
  1694. $mergeIds = [];
  1695. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1696. foreach ($rw['_order_merge_rows'] as $mr) {
  1697. $mid = (int)($mr['ID'] ?? 0);
  1698. if ($this->isValidScydgyRowId($mid)) {
  1699. $mergeIds[$mid] = true;
  1700. }
  1701. }
  1702. }
  1703. $rid = (int)($rw['ID'] ?? 0);
  1704. if ($this->isValidScydgyRowId($rid)) {
  1705. $mergeIds[$rid] = true;
  1706. }
  1707. $buckets = [];
  1708. foreach (array_keys($mergeIds) as $mid) {
  1709. if (isset($quoteBucket[$mid])) {
  1710. $buckets[] = $quoteBucket[$mid];
  1711. }
  1712. }
  1713. $supplierText = $buckets !== []
  1714. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1715. : '';
  1716. if ($wffTab === 'confirm') {
  1717. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1718. if ($picked === '') {
  1719. // 兜底:从合并工序行取
  1720. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1721. foreach ($rw['_order_merge_rows'] as $mr) {
  1722. if (!is_array($mr)) {
  1723. continue;
  1724. }
  1725. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1726. if ($pn !== '') {
  1727. $picked = $pn;
  1728. break;
  1729. }
  1730. }
  1731. }
  1732. }
  1733. $rw['picked_supplier_name'] = $picked;
  1734. } else {
  1735. $rw['notify_supplier_text'] = $supplierText;
  1736. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1737. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1738. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1739. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1740. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1741. if ($verified) {
  1742. $rw['bid_open_status_text'] = '已开标';
  1743. } elseif ($manualPicked) {
  1744. $rw['bid_open_status_text'] = '已指定供应商';
  1745. } else {
  1746. $rw['bid_open_status_text'] = '待开标';
  1747. }
  1748. }
  1749. }
  1750. unset($rw);
  1751. }
  1752. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1753. $this->enrichProcuremenListMilestoneTimes($rows);
  1754. $this->syncCollapsedOrderQtyPriceForList($rows);
  1755. }
  1756. if ($wffTab === 'all' && count($rows) > 0) {
  1757. $this->mergePurchaseOrder($rows);
  1758. }
  1759. if ($wffTab === 'pick' && count($rows) > 0) {
  1760. $this->mergePurchaseOrder($rows);
  1761. }
  1762. foreach ($rows as &$rwClean) {
  1763. if (is_array($rwClean)) {
  1764. unset($rwClean['_order_merge_rows']);
  1765. if (array_key_exists('NGZL', $rwClean)) {
  1766. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1767. }
  1768. }
  1769. }
  1770. unset($rwClean);
  1771. return json([
  1772. 'total' => count($filtered),
  1773. 'rows' => $rows,
  1774. 'activeYm' => $ym,
  1775. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1776. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1777. ? $this->ensureProcuremenPickSidebarYmList()
  1778. : [],
  1779. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1780. 'filterOptions' => (
  1781. (int)$offset === 0
  1782. && !$hasActiveSearch
  1783. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1784. )
  1785. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1786. : new \stdClass(),
  1787. ]);
  1788. } catch (\Throwable $e) {
  1789. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1790. return json([
  1791. 'total' => 0,
  1792. 'rows' => [],
  1793. ]);
  1794. }
  1795. }
  1796. /**
  1797. * @param array<int, array<string, mixed>> $pool
  1798. * @return int[]
  1799. */
  1800. protected function extractScydgyIdsFromPool(array $pool): array
  1801. {
  1802. $ids = [];
  1803. foreach ($pool as $r) {
  1804. if (!is_array($r)) {
  1805. continue;
  1806. }
  1807. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1808. if ($id > 0) {
  1809. $ids[$id] = $id;
  1810. }
  1811. }
  1812. return array_values($ids);
  1813. }
  1814. /**
  1815. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1816. *
  1817. * @param int[] $scydgyIds
  1818. * @return array<int, true>
  1819. */
  1820. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1821. {
  1822. $hideSet = [];
  1823. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1824. return $id > 0;
  1825. }));
  1826. if ($scydgyIds === []) {
  1827. return $hideSet;
  1828. }
  1829. // 分批,避免 whereIn 过长
  1830. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1831. try {
  1832. $poIds = Db::table('purchase_order')
  1833. ->where('scydgy_id', 'in', $chunk)
  1834. ->where(function ($q) {
  1835. $q->whereIn('wflow_status', array_merge(
  1836. ProcuremenStatus::wflowPendingConfirmValues(),
  1837. ProcuremenStatus::wflowPendingApprovalValues()
  1838. ))
  1839. ->whereOr(function ($q1) {
  1840. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1841. })
  1842. ->whereOr(function ($q2) {
  1843. $q2->whereNotNull('pick_time')
  1844. ->where('pick_time', '<>', '')
  1845. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1846. })
  1847. ->whereOr(function ($q3) {
  1848. $q3->whereNotNull('mod_rq')
  1849. ->where('mod_rq', '<>', '')
  1850. ->where('mod_rq', 'not like', '0000-00-00%');
  1851. });
  1852. })
  1853. ->column('scydgy_id');
  1854. if (is_array($poIds)) {
  1855. foreach ($poIds as $pid) {
  1856. $k = (int)$pid;
  1857. if ($k !== 0) {
  1858. $hideSet[$k] = true;
  1859. }
  1860. }
  1861. }
  1862. } catch (\Throwable $e) {
  1863. }
  1864. try {
  1865. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1866. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1867. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1868. if (is_array($detIds)) {
  1869. foreach ($detIds as $pid) {
  1870. $k = (int)$pid;
  1871. if ($this->isValidScydgyRowId($k)) {
  1872. $hideSet[$k] = true;
  1873. }
  1874. }
  1875. }
  1876. } catch (\Throwable $e) {
  1877. }
  1878. }
  1879. return $hideSet;
  1880. }
  1881. /**
  1882. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1883. *
  1884. * @return array<int, true>
  1885. */
  1886. protected function loadPickHiddenScydgySet(): array
  1887. {
  1888. if ($this->pickHiddenScydgySetCache !== null) {
  1889. return $this->pickHiddenScydgySetCache;
  1890. }
  1891. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1892. try {
  1893. $raw = redis()->get($cacheKey);
  1894. if ($raw !== false && $raw !== null && $raw !== '') {
  1895. $ids = json_decode((string)$raw, true);
  1896. if (is_array($ids)) {
  1897. $hideSet = [];
  1898. foreach ($ids as $pid) {
  1899. $k = (int)$pid;
  1900. if ($k !== 0) {
  1901. $hideSet[$k] = true;
  1902. }
  1903. }
  1904. $this->pickHiddenScydgySetCache = $hideSet;
  1905. return $hideSet;
  1906. }
  1907. }
  1908. } catch (\Throwable $e) {
  1909. }
  1910. $hideSet = [];
  1911. try {
  1912. $poIds = Db::table('purchase_order')
  1913. ->where(function ($q) {
  1914. $q->whereIn('wflow_status', array_merge(
  1915. ProcuremenStatus::wflowPendingConfirmValues(),
  1916. ProcuremenStatus::wflowPendingApprovalValues()
  1917. ))
  1918. ->whereOr(function ($q1) {
  1919. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1920. })
  1921. ->whereOr(function ($q2) {
  1922. $q2->whereNotNull('pick_time')
  1923. ->where('pick_time', '<>', '')
  1924. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1925. })
  1926. ->whereOr(function ($q3) {
  1927. $q3->whereNotNull('mod_rq')
  1928. ->where('mod_rq', '<>', '')
  1929. ->where('mod_rq', 'not like', '0000-00-00%');
  1930. });
  1931. })
  1932. ->column('scydgy_id');
  1933. if (is_array($poIds)) {
  1934. foreach ($poIds as $pid) {
  1935. $k = (int)$pid;
  1936. if ($k !== 0) {
  1937. $hideSet[$k] = true;
  1938. }
  1939. }
  1940. }
  1941. } catch (\Throwable $e) {
  1942. }
  1943. try {
  1944. $detIdsQuery = Db::table('purchase_order_detail');
  1945. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1946. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1947. if (is_array($detIds)) {
  1948. foreach ($detIds as $pid) {
  1949. $k = (int)$pid;
  1950. if ($this->isValidScydgyRowId($k)) {
  1951. $hideSet[$k] = true;
  1952. }
  1953. }
  1954. }
  1955. } catch (\Throwable $e) {
  1956. }
  1957. $this->pickHiddenScydgySetCache = $hideSet;
  1958. try {
  1959. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1960. } catch (\Throwable $e) {
  1961. }
  1962. return $hideSet;
  1963. }
  1964. /**
  1965. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1966. *
  1967. * @return array<int, array<string, mixed>>
  1968. */
  1969. protected function loadPickManualOrderRows(): array
  1970. {
  1971. try {
  1972. $dbRows = Db::table('purchase_order')
  1973. ->where('scydgy_id', '<', 0)
  1974. ->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%\')')
  1975. ->order('scydgy_id', 'asc')
  1976. ->select();
  1977. } catch (\Throwable $e) {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1980. } catch (\Throwable $e2) {
  1981. return [];
  1982. }
  1983. }
  1984. if (!is_array($dbRows) || $dbRows === []) {
  1985. return [];
  1986. }
  1987. $detailSidSet = [];
  1988. try {
  1989. $negIds = [];
  1990. foreach ($dbRows as $dbRow) {
  1991. if (!is_array($dbRow)) {
  1992. continue;
  1993. }
  1994. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1995. if ($sid < 0) {
  1996. $negIds[$sid] = true;
  1997. }
  1998. }
  1999. if ($negIds !== []) {
  2000. $detQuery = Db::table('purchase_order_detail')
  2001. ->where('scydgy_id', 'in', array_keys($negIds));
  2002. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2003. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2004. if (is_array($detRows)) {
  2005. foreach ($detRows as $did) {
  2006. $detailSidSet[(int)$did] = true;
  2007. }
  2008. }
  2009. }
  2010. } catch (\Throwable $e) {
  2011. }
  2012. $pool = [];
  2013. foreach ($dbRows as $dbRow) {
  2014. if (!is_array($dbRow)) {
  2015. continue;
  2016. }
  2017. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2018. if ($sid >= 0) {
  2019. continue;
  2020. }
  2021. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2022. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2023. continue;
  2024. }
  2025. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2026. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2027. continue;
  2028. }
  2029. if (isset($detailSidSet[$sid])) {
  2030. continue;
  2031. }
  2032. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2033. $r['_is_manual'] = 1;
  2034. $pool[] = $r;
  2035. }
  2036. return $pool;
  2037. }
  2038. /**
  2039. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2040. */
  2041. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2042. {
  2043. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2044. foreach ($keys as $k) {
  2045. $t = trim((string)($row[$k] ?? ''));
  2046. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2047. return $t;
  2048. }
  2049. }
  2050. return '';
  2051. }
  2052. /**
  2053. * 分配手工新增工序行 ID(负数递减)
  2054. */
  2055. protected function allocateManualScydgyId(): int
  2056. {
  2057. try {
  2058. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2059. $min = (int)$min;
  2060. return $min < 0 ? $min - 1 : -1;
  2061. } catch (\Throwable $e) {
  2062. return -1;
  2063. }
  2064. }
  2065. /**
  2066. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2067. */
  2068. protected function allocateManualOrderCcydh(): string
  2069. {
  2070. $prefix = 'YW' . date('Ymd');
  2071. $maxSeq = 0;
  2072. try {
  2073. $rows = Db::table('purchase_order')
  2074. ->where('CCYDH', 'like', $prefix . '%')
  2075. ->column('CCYDH');
  2076. if (is_array($rows)) {
  2077. foreach ($rows as $ccydh) {
  2078. $ccydh = trim((string)$ccydh);
  2079. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2080. $maxSeq = max($maxSeq, (int)$m[1]);
  2081. }
  2082. }
  2083. }
  2084. } catch (\Throwable $e) {
  2085. }
  2086. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2087. }
  2088. /**
  2089. * purchase_order.mod_rq 是否有有效软删除时间
  2090. */
  2091. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2092. {
  2093. $t = trim((string)$modRq);
  2094. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2095. }
  2096. /**
  2097. * 列表行 → purchase_order 写入字段
  2098. *
  2099. * @return array<string, mixed>
  2100. */
  2101. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2102. {
  2103. return [
  2104. 'scydgy_id' => $scydgyId,
  2105. 'CCYDH' => $row['CCYDH'] ?? null,
  2106. 'CYJMC' => $row['CYJMC'] ?? null,
  2107. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2108. 'CDXMC' => $row['CDXMC'] ?? null,
  2109. 'CGYBH' => $row['CGYBH'] ?? null,
  2110. 'CGYMC' => $row['CGYMC'] ?? null,
  2111. 'CDW' => $row['CDW'] ?? null,
  2112. 'czlyq' => $row['czlyq'] ?? null,
  2113. 'NGZL' => $row['NGZL'] ?? null,
  2114. 'CDF' => $row['CDF'] ?? null,
  2115. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2116. 'MBZ' => $row['MBZ'] ?? null,
  2117. 'bwjg' => $row['bwjg'] ?? null,
  2118. 'iStatus' => $row['iStatus'] ?? null,
  2119. 'dStamp' => $row['dStamp'] ?? null,
  2120. 'dputrecord' => $row['dputrecord'] ?? null,
  2121. 'cywyxm' => $row['cywyxm'] ?? null,
  2122. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2123. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2124. ];
  2125. }
  2126. /**
  2127. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2128. *
  2129. * @return array{po:?array<string,mixed>, hidden:bool}
  2130. */
  2131. protected function resolvePickRowPoContext(int $sid): array
  2132. {
  2133. $po = null;
  2134. try {
  2135. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2136. if (is_array($found)) {
  2137. $po = $found;
  2138. }
  2139. } catch (\Throwable $e) {
  2140. }
  2141. $hideSet = $this->loadPickHiddenScydgySet();
  2142. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2143. }
  2144. /**
  2145. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2146. */
  2147. protected function assertPickRowCanDelete(int $sid, array $row): void
  2148. {
  2149. $ctx = $this->resolvePickRowPoContext($sid);
  2150. $po = $ctx['po'];
  2151. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2152. return;
  2153. }
  2154. if (is_array($po)) {
  2155. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2156. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2157. }
  2158. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2159. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2160. }
  2161. }
  2162. if ($ctx['hidden']) {
  2163. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2164. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2165. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2166. }
  2167. }
  2168. /**
  2169. * 初选直接完结前校验
  2170. */
  2171. protected function assertPickRowCanComplete(int $sid, array $row): void
  2172. {
  2173. $ctx = $this->resolvePickRowPoContext($sid);
  2174. $po = $ctx['po'];
  2175. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2176. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2177. }
  2178. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2179. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2180. }
  2181. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2182. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2183. }
  2184. }
  2185. /**
  2186. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2187. */
  2188. protected function softDeleteProcuremenPickRow(array $row): void
  2189. {
  2190. $sid = $this->extractScydgyRowId($row);
  2191. if (!$this->isValidScydgyRowId($sid)) {
  2192. throw new \InvalidArgumentException('无效的行主键');
  2193. }
  2194. $this->assertPickRowCanDelete($sid, $row);
  2195. $po = $this->resolvePickRowPoContext($sid)['po'];
  2196. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2197. return;
  2198. }
  2199. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2200. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2201. }
  2202. $now = date('Y-m-d H:i:s');
  2203. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2204. if (is_array($exists)) {
  2205. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2206. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2207. } else {
  2208. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2209. $data['mod_rq'] = $now;
  2210. $data['createtime'] = $now;
  2211. Db::table('purchase_order')->insert($data);
  2212. $poIdLog = (int)Db::getLastInsID();
  2213. }
  2214. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2215. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2216. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2217. if ($gymcLog !== '') {
  2218. $logTail .= ' / ' . $gymcLog;
  2219. }
  2220. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2221. }
  2222. /**
  2223. * 手工新增协助工序(写入 purchase_order)
  2224. *
  2225. * @param array<string, mixed> $params
  2226. * @return int scydgy_id
  2227. */
  2228. protected function saveManualPickOrder(array $params): int
  2229. {
  2230. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2231. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2232. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2233. if ($ccydh === '') {
  2234. $ccydh = $this->allocateManualOrderCcydh();
  2235. }
  2236. $now = date('Y-m-d H:i:s');
  2237. $sid = $this->allocateManualScydgyId();
  2238. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2239. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2240. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2241. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2242. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2243. $data = [
  2244. 'scydgy_id' => $sid,
  2245. 'CCYDH' => $ccydh,
  2246. 'CYJMC' => $cyjmc,
  2247. 'CGYMC' => $cgymc,
  2248. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2249. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2250. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2251. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2252. 'cGzzxMc' => $supplierName,
  2253. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2254. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2255. 'notify_salesman' => $notifySalesman,
  2256. 'rfq_salesman_notified' => 0,
  2257. 'rfq_salesman_notify_time' => null,
  2258. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2259. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2260. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2261. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2262. 'createtime' => $now,
  2263. 'dStamp' => $now,
  2264. 'dputrecord' => $now,
  2265. ];
  2266. Db::table('purchase_order')->insert($data);
  2267. $poId = (int)Db::getLastInsID();
  2268. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2269. return $sid;
  2270. }
  2271. protected function formatProcuremenRowLabel(array $row): string
  2272. {
  2273. $dh = trim((string)($row['CCYDH'] ?? ''));
  2274. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2275. if ($dh !== '' && $gymc !== '') {
  2276. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2277. }
  2278. if ($dh !== '') {
  2279. return '订单「' . $dh . '」';
  2280. }
  2281. if ($gymc !== '') {
  2282. return '工序「' . $gymc . '」';
  2283. }
  2284. $id = $this->extractScydgyRowId($row);
  2285. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2286. }
  2287. /**
  2288. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2289. */
  2290. protected function extractScydgyRowId(array $row): int
  2291. {
  2292. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2293. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2294. return (int)$row['scydgy_id'];
  2295. }
  2296. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2297. return (int)$row['SCYDGY_ID'];
  2298. }
  2299. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2300. }
  2301. protected function isValidScydgyRowId(int $id): bool
  2302. {
  2303. return ProcuremenGuard::isValidScydgyId($id);
  2304. }
  2305. protected function isManualScydgyRowId(int $id): bool
  2306. {
  2307. return $id < 0;
  2308. }
  2309. /**
  2310. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2311. *
  2312. * @param int[] $scydgyIds
  2313. * @return array<int, string[]>
  2314. */
  2315. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2316. {
  2317. $out = [];
  2318. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2319. if ($scydgyIds === []) {
  2320. return $out;
  2321. }
  2322. try {
  2323. $rows = Db::table('purchase_order_detail')
  2324. ->where('scydgy_id', 'in', $scydgyIds)
  2325. ->field('scydgy_id,company_name')
  2326. ->order('company_name', 'asc')
  2327. ->select();
  2328. } catch (\Throwable $e) {
  2329. $rows = [];
  2330. }
  2331. if (!is_array($rows)) {
  2332. return $out;
  2333. }
  2334. foreach ($rows as $r) {
  2335. if (!is_array($r)) {
  2336. continue;
  2337. }
  2338. $sid = (int)($r['scydgy_id'] ?? 0);
  2339. $cn = trim((string)($r['company_name'] ?? ''));
  2340. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2341. continue;
  2342. }
  2343. if (!isset($out[$sid])) {
  2344. $out[$sid] = [];
  2345. }
  2346. if (!in_array($cn, $out[$sid], true)) {
  2347. $out[$sid][] = $cn;
  2348. }
  2349. }
  2350. return $out;
  2351. }
  2352. /**
  2353. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2354. *
  2355. * @param string[] $names
  2356. */
  2357. protected function formatNotifySupplierDisplay(array $names): string
  2358. {
  2359. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2360. return trim((string)$n);
  2361. }, $names))));
  2362. if ($names === []) {
  2363. return '';
  2364. }
  2365. sort($names, SORT_STRING);
  2366. return implode("\n", $names);
  2367. }
  2368. /**
  2369. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2370. *
  2371. * @param int[] $scydgyIds
  2372. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2373. */
  2374. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2375. {
  2376. $out = [];
  2377. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2378. if ($scydgyIds === []) {
  2379. return $out;
  2380. }
  2381. try {
  2382. $rows = Db::table('purchase_order_detail')
  2383. ->where('scydgy_id', 'in', $scydgyIds)
  2384. ->field('scydgy_id,company_name,amount')
  2385. ->select();
  2386. } catch (\Throwable $e) {
  2387. $rows = [];
  2388. }
  2389. if (!is_array($rows)) {
  2390. return $out;
  2391. }
  2392. foreach ($rows as $r) {
  2393. if (!is_array($r)) {
  2394. continue;
  2395. }
  2396. $sid = (int)($r['scydgy_id'] ?? 0);
  2397. $cn = trim((string)($r['company_name'] ?? ''));
  2398. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2399. continue;
  2400. }
  2401. if (!isset($out[$sid])) {
  2402. $out[$sid] = ['all' => [], 'quoted' => []];
  2403. }
  2404. $out[$sid]['all'][$cn] = true;
  2405. $am = trim((string)($r['amount'] ?? ''));
  2406. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2407. $out[$sid]['quoted'][$cn] = true;
  2408. }
  2409. }
  2410. return $out;
  2411. }
  2412. /**
  2413. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2414. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2415. */
  2416. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2417. {
  2418. $merged = ['all' => [], 'quoted' => []];
  2419. foreach ($buckets as $b) {
  2420. if (!is_array($b)) {
  2421. continue;
  2422. }
  2423. foreach ($b['all'] ?? [] as $cn => $_) {
  2424. $merged['all'][$cn] = true;
  2425. }
  2426. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2427. $merged['quoted'][$cn] = true;
  2428. }
  2429. }
  2430. return $merged;
  2431. }
  2432. /**
  2433. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2434. */
  2435. protected function formatQuotedSupplierLines(array $bucket): string
  2436. {
  2437. $all = array_keys($bucket['all'] ?? []);
  2438. if ($all === []) {
  2439. return '';
  2440. }
  2441. sort($all, SORT_STRING);
  2442. $lines = [];
  2443. foreach ($all as $cn) {
  2444. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2445. $lines[] = $cn . '(' . $status . ')';
  2446. }
  2447. return implode("\n", $lines);
  2448. }
  2449. /**
  2450. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2451. */
  2452. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2453. {
  2454. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2455. $this->view->engine->layout(false);
  2456. try {
  2457. $bodyHtml = $this->view->fetch($view);
  2458. $this->view->assign('dialogBody', $bodyHtml);
  2459. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2460. return $this->view->fetch('procuremen/dialog_lite_shell');
  2461. } finally {
  2462. if ($restoreLayout) {
  2463. $this->view->engine->layout($restoreLayout);
  2464. }
  2465. }
  2466. }
  2467. /**
  2468. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2469. */
  2470. protected function resolveBundleSysRq(array $bundle): string
  2471. {
  2472. foreach ($bundle['pos'] ?? [] as $po) {
  2473. if (!is_array($po)) {
  2474. continue;
  2475. }
  2476. $sr = trim((string)($po['sys_rq'] ?? ''));
  2477. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2478. return $sr;
  2479. }
  2480. }
  2481. return '';
  2482. }
  2483. /**
  2484. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2485. */
  2486. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2487. {
  2488. $raw = trim((string)$sysRq);
  2489. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2490. return true;
  2491. }
  2492. $ts = strtotime(str_replace('T', ' ', $raw));
  2493. if ($ts === false || $ts <= 0) {
  2494. return true;
  2495. }
  2496. return time() >= $ts;
  2497. }
  2498. /**
  2499. * 开标前校验:必须已过报价截止时间
  2500. *
  2501. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2502. */
  2503. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2504. {
  2505. $sysRq = $this->resolveBundleSysRq($bundle);
  2506. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2507. $this->error('未到招标截止日期');
  2508. }
  2509. }
  2510. /**
  2511. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2512. *
  2513. * @param array<string, mixed> $d
  2514. * @param string $deliveryYmd
  2515. */
  2516. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2517. {
  2518. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2519. return max(0, (int)$d['lead_days']);
  2520. }
  2521. if ($deliveryYmd === '') {
  2522. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2523. }
  2524. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2525. return null;
  2526. }
  2527. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2528. $t2 = strtotime($m[1] . ' 00:00:00');
  2529. if ($t1 === false || $t2 === false) {
  2530. return null;
  2531. }
  2532. return max(0, (int)round(($t2 - $t1) / 86400));
  2533. }
  2534. /**
  2535. * @param int|null $days
  2536. */
  2537. protected function formatProcuremenLeadDaysText($days): string
  2538. {
  2539. if ($days === null || $days === '') {
  2540. return '未填写';
  2541. }
  2542. if (!is_numeric($days)) {
  2543. return '未填写';
  2544. }
  2545. return ((int)$days) . '天';
  2546. }
  2547. /**
  2548. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2549. *
  2550. * @param array<string, mixed> $line
  2551. */
  2552. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2553. {
  2554. $amountFilled = !empty($line['amount_filled']);
  2555. $deliveryFilled = !empty($line['delivery_filled']);
  2556. $leadFilled = !empty($line['lead_days_filled']);
  2557. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2558. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2559. $line['amount_show'] = '';
  2560. if (array_key_exists('amount_text', $line)) {
  2561. $line['amount_text'] = $line['unit_price_text'];
  2562. }
  2563. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2564. $line['delivery_show'] = $deliveryText;
  2565. if (array_key_exists('delivery_text', $line)) {
  2566. $line['delivery_text'] = $deliveryText;
  2567. }
  2568. $line['delivery_ymd'] = '';
  2569. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2570. $line['lead_days_show'] = $leadText;
  2571. $line['lead_days_text'] = $leadText;
  2572. $line['lead_days'] = '';
  2573. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2574. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2575. $line['subtotal_num'] = null;
  2576. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2577. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2578. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2579. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2580. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2581. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2582. $line['amount_filled'] = false;
  2583. $line['delivery_filled'] = false;
  2584. $line['lead_days_filled'] = false;
  2585. $line['is_quoted'] = false;
  2586. if (array_key_exists('quote_label', $line)) {
  2587. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2588. }
  2589. }
  2590. protected function ensurePurchaseOrderBidOpenTable(): void
  2591. {
  2592. static $ready = false;
  2593. if ($ready) {
  2594. return;
  2595. }
  2596. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2597. try {
  2598. if (Cache::get($cacheKey)) {
  2599. $ready = true;
  2600. return;
  2601. }
  2602. } catch (\Throwable $e) {
  2603. }
  2604. try {
  2605. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2606. $ready = true;
  2607. try {
  2608. Cache::set($cacheKey, 1, 86400);
  2609. } catch (\Throwable $e) {
  2610. }
  2611. } catch (\Throwable $e) {
  2612. Db::execute(
  2613. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2614. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2615. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2616. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2617. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2618. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2619. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2620. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2621. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2622. `createtime` datetime DEFAULT NULL,
  2623. PRIMARY KEY (`id`),
  2624. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2625. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2626. );
  2627. $ready = true;
  2628. try {
  2629. Cache::set($cacheKey, 1, 86400);
  2630. } catch (\Throwable $e2) {
  2631. }
  2632. }
  2633. }
  2634. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2635. {
  2636. $ccydh = trim($ccydh);
  2637. if ($ccydh === '') {
  2638. return false;
  2639. }
  2640. $this->ensurePurchaseOrderBidOpenTable();
  2641. try {
  2642. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2643. return is_array($row);
  2644. } catch (\Throwable $e) {
  2645. return false;
  2646. }
  2647. }
  2648. /**
  2649. * 批量查询订单是否已开标验证
  2650. *
  2651. * @param array<int, string> $ccydhs
  2652. * @return array<string, bool> ccydh => true
  2653. */
  2654. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2655. {
  2656. $set = [];
  2657. $list = [];
  2658. foreach ($ccydhs as $c) {
  2659. $c = trim((string)$c);
  2660. if ($c !== '') {
  2661. $list[$c] = true;
  2662. }
  2663. }
  2664. if ($list === []) {
  2665. return $set;
  2666. }
  2667. $this->ensurePurchaseOrderBidOpenTable();
  2668. try {
  2669. $rows = Db::table('purchase_order_bid_open')
  2670. ->where('ccydh', 'in', array_keys($list))
  2671. ->field('ccydh')
  2672. ->select();
  2673. foreach ($rows as $row) {
  2674. if (!is_array($row)) {
  2675. continue;
  2676. }
  2677. $c = trim((string)($row['ccydh'] ?? ''));
  2678. if ($c !== '') {
  2679. $set[$c] = true;
  2680. }
  2681. }
  2682. } catch (\Throwable $e) {
  2683. return [];
  2684. }
  2685. return $set;
  2686. }
  2687. /**
  2688. * 批量查询订单是否已指定供应商(免开标)
  2689. *
  2690. * @param array<int, string> $ccydhs
  2691. * @return array<string, bool> ccydh => true
  2692. */
  2693. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2694. {
  2695. $set = [];
  2696. $list = [];
  2697. foreach ($ccydhs as $c) {
  2698. $c = trim((string)$c);
  2699. if ($c !== '') {
  2700. $list[$c] = true;
  2701. }
  2702. }
  2703. if ($list === []) {
  2704. return $set;
  2705. }
  2706. $this->ensurePurchaseOrderManualPickColumns();
  2707. try {
  2708. $rows = Db::table('purchase_order')
  2709. ->where('CCYDH', 'in', array_keys($list))
  2710. ->where('manual_pick', 1)
  2711. ->field('CCYDH')
  2712. ->select();
  2713. foreach ($rows as $row) {
  2714. if (!is_array($row)) {
  2715. continue;
  2716. }
  2717. $c = trim((string)($row['CCYDH'] ?? ''));
  2718. if ($c !== '') {
  2719. $set[$c] = true;
  2720. }
  2721. }
  2722. } catch (\Throwable $e) {
  2723. return [];
  2724. }
  2725. return $set;
  2726. }
  2727. /**
  2728. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2729. *
  2730. * @param array<int, array<string, mixed>> $pool
  2731. * @return array<int, array<string, mixed>>
  2732. */
  2733. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2734. {
  2735. $status = trim($status);
  2736. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2737. return $pool;
  2738. }
  2739. $ccydhList = [];
  2740. foreach ($pool as $rw) {
  2741. if (!is_array($rw)) {
  2742. continue;
  2743. }
  2744. $c = trim((string)($rw['CCYDH'] ?? ''));
  2745. if ($c !== '') {
  2746. $ccydhList[] = $c;
  2747. }
  2748. }
  2749. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2750. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2751. $out = [];
  2752. foreach ($pool as $rw) {
  2753. if (!is_array($rw)) {
  2754. continue;
  2755. }
  2756. $c = trim((string)($rw['CCYDH'] ?? ''));
  2757. if ($c !== '' && isset($bidOpenSet[$c])) {
  2758. $t = '已开标';
  2759. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2760. $t = '已指定供应商';
  2761. } else {
  2762. $t = '待开标';
  2763. }
  2764. if ($t === $status) {
  2765. $out[] = $rw;
  2766. }
  2767. }
  2768. return $out;
  2769. }
  2770. /**
  2771. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2772. *
  2773. * @param array<string, mixed> $group
  2774. */
  2775. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2776. {
  2777. if ($quoteVisible) {
  2778. $group['remark_quote_pending'] = 0;
  2779. return;
  2780. }
  2781. $group['remark'] = '';
  2782. $group['remark_quote_pending'] = 0;
  2783. }
  2784. /**
  2785. * @param array{ccydh?:string} $bundle
  2786. */
  2787. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2788. {
  2789. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2790. }
  2791. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2792. {
  2793. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2794. return true;
  2795. }
  2796. return $this->isProcuremenManualPickedForBundle($bundle);
  2797. }
  2798. /**
  2799. * 确保 purchase_order 自选供应商字段
  2800. */
  2801. protected function ensurePurchaseOrderManualPickColumns(): void
  2802. {
  2803. static $done = false;
  2804. if ($done) {
  2805. return;
  2806. }
  2807. $done = true;
  2808. $adds = [
  2809. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2810. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2811. ];
  2812. foreach ($adds as $col => $ddl) {
  2813. try {
  2814. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2815. if (!is_array($cols) || $cols === []) {
  2816. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2817. }
  2818. } catch (\Throwable $e) {
  2819. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2820. }
  2821. }
  2822. }
  2823. /**
  2824. * 是否已自选供应商(免开标查看报价)
  2825. *
  2826. * @param array{pos?:array} $bundle
  2827. */
  2828. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2829. {
  2830. $this->ensurePurchaseOrderManualPickColumns();
  2831. foreach ($bundle['pos'] ?? [] as $poRow) {
  2832. if (!is_array($poRow)) {
  2833. continue;
  2834. }
  2835. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2836. return true;
  2837. }
  2838. }
  2839. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2840. if ($ccydh === '') {
  2841. return false;
  2842. }
  2843. try {
  2844. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2845. return $v !== null && $v !== false && (int)$v > 0;
  2846. } catch (\Throwable $e) {
  2847. return false;
  2848. }
  2849. }
  2850. /**
  2851. * @param array{pos?:array} $bundle
  2852. * @return array{company:string,reason:string}
  2853. */
  2854. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2855. {
  2856. $this->ensurePurchaseOrderManualPickColumns();
  2857. foreach ($bundle['pos'] ?? [] as $poRow) {
  2858. if (!is_array($poRow)) {
  2859. continue;
  2860. }
  2861. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2862. continue;
  2863. }
  2864. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2865. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2866. return ['company' => $cn, 'reason' => $reason];
  2867. }
  2868. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2869. if ($ccydh === '') {
  2870. return ['company' => '', 'reason' => ''];
  2871. }
  2872. try {
  2873. $row = Db::table('purchase_order')
  2874. ->where('CCYDH', $ccydh)
  2875. ->where('manual_pick', 1)
  2876. ->field('pick_company_name,manual_pick_reason')
  2877. ->order('id', 'asc')
  2878. ->find();
  2879. } catch (\Throwable $e) {
  2880. $row = null;
  2881. }
  2882. if (!is_array($row)) {
  2883. return ['company' => '', 'reason' => ''];
  2884. }
  2885. return [
  2886. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2887. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2888. ];
  2889. }
  2890. protected function loadBidOpenAdminUser(int $adminId): ?array
  2891. {
  2892. if ($adminId <= 0) {
  2893. return null;
  2894. }
  2895. try {
  2896. $row = Db::name('admin')->where('id', $adminId)->find();
  2897. } catch (\Throwable $e) {
  2898. return null;
  2899. }
  2900. if (!is_array($row)) {
  2901. return null;
  2902. }
  2903. $status = strtolower(trim((string)($row['status'] ?? '')));
  2904. if ($status !== '' && $status !== 'normal') {
  2905. return null;
  2906. }
  2907. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2908. return null;
  2909. }
  2910. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2911. if (!preg_match('/^1\d{10}$/', $phone)) {
  2912. return null;
  2913. }
  2914. $name = trim((string)($row['nickname'] ?? ''));
  2915. if ($name === '') {
  2916. $name = trim((string)($row['username'] ?? ''));
  2917. }
  2918. return [
  2919. 'id' => (int)$row['id'],
  2920. 'username' => trim((string)($row['username'] ?? '')),
  2921. 'nickname' => $name,
  2922. 'mobile' => $phone,
  2923. ];
  2924. }
  2925. /**
  2926. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2927. */
  2928. protected function bidOpenVerifierAuthGroupRootId(): int
  2929. {
  2930. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2931. return $id > 0 ? $id : 10;
  2932. }
  2933. /**
  2934. * @return int[]
  2935. */
  2936. protected function loadBidOpenVerifierAuthGroupIds(): array
  2937. {
  2938. static $memo = [];
  2939. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2940. if (isset($memo[$rootId])) {
  2941. return $memo[$rootId];
  2942. }
  2943. try {
  2944. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2945. } catch (\Throwable $e) {
  2946. $memo[$rootId] = [$rootId];
  2947. return $memo[$rootId];
  2948. }
  2949. if (!is_array($groups) || $groups === []) {
  2950. $memo[$rootId] = [$rootId];
  2951. return $memo[$rootId];
  2952. }
  2953. $groupList = [];
  2954. foreach ($groups as $g) {
  2955. if (is_array($g)) {
  2956. $groupList[] = $g;
  2957. }
  2958. }
  2959. if ($groupList === []) {
  2960. $memo[$rootId] = [$rootId];
  2961. return $memo[$rootId];
  2962. }
  2963. $tree = \fast\Tree::instance();
  2964. $tree->init($groupList);
  2965. $ids = $tree->getChildrenIds($rootId, true);
  2966. if (!is_array($ids) || $ids === []) {
  2967. $memo[$rootId] = [$rootId];
  2968. return $memo[$rootId];
  2969. }
  2970. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2971. return $memo[$rootId];
  2972. }
  2973. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2974. {
  2975. if ($adminId <= 0) {
  2976. return false;
  2977. }
  2978. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2979. if ($groupIds === []) {
  2980. return false;
  2981. }
  2982. try {
  2983. return (bool)Db::name('auth_group_access')
  2984. ->where('uid', $adminId)
  2985. ->where('group_id', 'in', $groupIds)
  2986. ->count();
  2987. } catch (\Throwable $e) {
  2988. return false;
  2989. }
  2990. }
  2991. /**
  2992. * @return array<int, array<string, mixed>>
  2993. */
  2994. protected function listBidOpenVerifierCandidates(): array
  2995. {
  2996. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2997. if ($groupIds === []) {
  2998. return [];
  2999. }
  3000. try {
  3001. $adminIds = Db::name('auth_group_access')
  3002. ->where('group_id', 'in', $groupIds)
  3003. ->column('uid');
  3004. } catch (\Throwable $e) {
  3005. $adminIds = [];
  3006. }
  3007. $adminIds = is_array($adminIds)
  3008. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3009. : [];
  3010. if ($adminIds === []) {
  3011. return [];
  3012. }
  3013. try {
  3014. $rows = Db::name('admin')
  3015. ->where('status', 'normal')
  3016. ->where('id', 'in', $adminIds)
  3017. ->where('mobile', '<>', '')
  3018. ->order('id', 'asc')
  3019. ->select();
  3020. } catch (\Throwable $e) {
  3021. return [];
  3022. }
  3023. if (!is_array($rows)) {
  3024. return [];
  3025. }
  3026. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3027. $out = [];
  3028. foreach ($rows as $row) {
  3029. if (!is_array($row)) {
  3030. continue;
  3031. }
  3032. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3033. if ($one === null) {
  3034. continue;
  3035. }
  3036. $out[] = [
  3037. 'id' => $one['id'],
  3038. 'username' => $one['username'],
  3039. 'nickname' => $one['nickname'],
  3040. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3041. 'mobile' => mask_phone($one['mobile']),
  3042. ];
  3043. }
  3044. return $out;
  3045. }
  3046. /**
  3047. * @param int[] $adminIds
  3048. * @return array<int, string>
  3049. */
  3050. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3051. {
  3052. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3053. if ($adminIds === []) {
  3054. return [];
  3055. }
  3056. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3057. try {
  3058. $rows = Db::name('auth_group_access')
  3059. ->alias('aga')
  3060. ->join('auth_group ag', 'aga.group_id = ag.id')
  3061. ->where('aga.uid', 'in', $adminIds)
  3062. ->where('aga.group_id', 'in', $groupIds)
  3063. ->field('aga.uid,ag.name')
  3064. ->order('aga.uid', 'asc')
  3065. ->order('aga.group_id', 'asc')
  3066. ->select();
  3067. } catch (\Throwable $e) {
  3068. return [];
  3069. }
  3070. if (!is_array($rows)) {
  3071. return [];
  3072. }
  3073. $out = [];
  3074. foreach ($rows as $row) {
  3075. if (!is_array($row)) {
  3076. continue;
  3077. }
  3078. $uid = (int)($row['uid'] ?? 0);
  3079. $name = trim((string)($row['name'] ?? ''));
  3080. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3081. continue;
  3082. }
  3083. $out[$uid] = $name;
  3084. }
  3085. return $out;
  3086. }
  3087. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3088. {
  3089. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3090. }
  3091. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3092. {
  3093. return 'procuremen_bidopen_wait_' . $adminId;
  3094. }
  3095. protected function renderBidOpenVerifySms(string $code): string
  3096. {
  3097. $tpl = '';
  3098. try {
  3099. $row = $this->loadNotifyTemplateRow('bid_open');
  3100. if (is_array($row)) {
  3101. $tpl = trim((string)($row['content'] ?? ''));
  3102. }
  3103. } catch (\Throwable $e) {
  3104. $tpl = '';
  3105. }
  3106. if ($tpl === '') {
  3107. $tpl = '【可集达】您的短信验证码是{code}';
  3108. }
  3109. return str_replace('{code}', $code, $tpl);
  3110. }
  3111. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3112. {
  3113. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3114. }
  3115. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3116. {
  3117. $code = trim($code);
  3118. if (!preg_match('/^\d{6}$/', $code)) {
  3119. return false;
  3120. }
  3121. $mock = Config::get('mproc.mock_sms_code');
  3122. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3123. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3124. return true;
  3125. }
  3126. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3127. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3128. return false;
  3129. }
  3130. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3131. return true;
  3132. }
  3133. /**
  3134. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3135. */
  3136. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3137. {
  3138. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3139. if ($ccydh === '') {
  3140. throw new \InvalidArgumentException('订单号无效');
  3141. }
  3142. $this->ensurePurchaseOrderBidOpenTable();
  3143. list($operatorId, $operatorName) = $this->GetUseName();
  3144. $now = date('Y-m-d H:i:s');
  3145. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3146. $payload = [
  3147. 'ccydh' => $ccydh,
  3148. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3149. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3150. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3151. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3152. 'operator_id' => (int)$operatorId,
  3153. 'operator_name' => trim((string)$operatorName),
  3154. 'createtime' => $now,
  3155. ];
  3156. if (is_array($exists)) {
  3157. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3158. } else {
  3159. Db::table('purchase_order_bid_open')->insert($payload);
  3160. }
  3161. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3162. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3163. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3164. (int)$payload['verifier1_id'],
  3165. (int)$payload['verifier2_id'],
  3166. ]);
  3167. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3168. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3169. }
  3170. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3171. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3172. }
  3173. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3174. $seenSid = [];
  3175. foreach ($bundle['pos'] ?? [] as $poRow) {
  3176. if (!is_array($poRow)) {
  3177. continue;
  3178. }
  3179. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3180. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3181. continue;
  3182. }
  3183. $seenSid[$sid] = true;
  3184. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3185. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3186. }
  3187. if ($seenSid === []) {
  3188. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3189. if ($this->isValidScydgyRowId($anchor)) {
  3190. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3191. }
  3192. }
  3193. // 开标通过后计算并写入供应商服务评分
  3194. try {
  3195. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3196. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3197. } catch (\Throwable $e) {
  3198. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3199. }
  3200. }
  3201. /**
  3202. * 报价行展示字段默认值(模板安全访问)
  3203. *
  3204. * @param array<string, mixed> $line
  3205. * @return array<string, mixed>
  3206. */
  3207. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3208. {
  3209. if (!array_key_exists('amount_quote_pending', $line)) {
  3210. $line['amount_quote_pending'] = 0;
  3211. }
  3212. if (!array_key_exists('delivery_quote_pending', $line)) {
  3213. $line['delivery_quote_pending'] = 0;
  3214. }
  3215. if (!array_key_exists('quote_before_deadline', $line)) {
  3216. $line['quote_before_deadline'] = 0;
  3217. }
  3218. if (!array_key_exists('amount_filled', $line)) {
  3219. $line['amount_filled'] = 0;
  3220. }
  3221. if (!array_key_exists('delivery_filled', $line)) {
  3222. $line['delivery_filled'] = 0;
  3223. }
  3224. if (!array_key_exists('lead_days_filled', $line)) {
  3225. $line['lead_days_filled'] = 0;
  3226. }
  3227. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3228. $line['lead_days_quote_pending'] = 0;
  3229. }
  3230. if (!array_key_exists('lead_days_show', $line)) {
  3231. $line['lead_days_show'] = '未填写';
  3232. }
  3233. if (!array_key_exists('lead_days_text', $line)) {
  3234. $line['lead_days_text'] = $line['lead_days_show'];
  3235. }
  3236. return $line;
  3237. }
  3238. /**
  3239. * 审核弹窗:按供应商汇总报价明细
  3240. *
  3241. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3242. * @return array<int, array<string, mixed>>
  3243. */
  3244. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3245. {
  3246. $sids = [];
  3247. foreach ($bundle['pos'] ?? [] as $po) {
  3248. if (!is_array($po)) {
  3249. continue;
  3250. }
  3251. $sid = (int)($po['scydgy_id'] ?? 0);
  3252. if ($this->isValidScydgyRowId($sid)) {
  3253. $sids[$sid] = true;
  3254. }
  3255. }
  3256. if ($sids === []) {
  3257. return [];
  3258. }
  3259. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3260. $gymcMap = [];
  3261. $qtyBySid = [];
  3262. $orderedSids = [];
  3263. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3264. if (!is_array($mr)) {
  3265. continue;
  3266. }
  3267. $gid = $this->extractScydgyRowId($mr);
  3268. if ($this->isValidScydgyRowId($gid)) {
  3269. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3270. $orderedSids[] = $gid;
  3271. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3272. if ($qty === '') {
  3273. $qty = trim((string)($mr['NGZL'] ?? ''));
  3274. }
  3275. $qtyBySid[$gid] = $qty;
  3276. }
  3277. }
  3278. foreach ($bundle['pos'] ?? [] as $po) {
  3279. if (!is_array($po)) {
  3280. continue;
  3281. }
  3282. $gid = (int)($po['scydgy_id'] ?? 0);
  3283. if ($this->isValidScydgyRowId($gid)) {
  3284. $nm = trim((string)($po['CGYMC'] ?? ''));
  3285. if ($nm !== '') {
  3286. $gymcMap[$gid] = $nm;
  3287. }
  3288. if (!in_array($gid, $orderedSids, true)) {
  3289. $orderedSids[] = $gid;
  3290. }
  3291. }
  3292. }
  3293. try {
  3294. $detailsQuery = Db::table('purchase_order_detail')
  3295. ->where('scydgy_id', 'in', array_keys($sids));
  3296. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3297. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3298. } catch (\Throwable $e) {
  3299. try {
  3300. $detailsQuery = Db::table('purchase_order_detail')
  3301. ->where('scydgy_id', 'in', array_keys($sids));
  3302. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3303. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3304. } catch (\Throwable $e2) {
  3305. $details = [];
  3306. }
  3307. }
  3308. if (!is_array($details)) {
  3309. $details = [];
  3310. }
  3311. $byCompany = [];
  3312. foreach ($details as $d) {
  3313. if (!is_array($d)) {
  3314. continue;
  3315. }
  3316. $cn = trim((string)($d['company_name'] ?? ''));
  3317. if ($cn === '') {
  3318. continue;
  3319. }
  3320. if (!isset($byCompany[$cn])) {
  3321. $ph = trim((string)($d['phone'] ?? ''));
  3322. $username = trim((string)($d['username'] ?? ''));
  3323. if ($username === '') {
  3324. $username = $this->resolveCustomerContactName($ph, $cn);
  3325. }
  3326. $byCompany[$cn] = [
  3327. 'name' => $cn,
  3328. 'email' => trim((string)($d['email'] ?? '')),
  3329. 'phone' => $ph,
  3330. 'username' => $username,
  3331. 'remark' => '',
  3332. 'has_quote' => false,
  3333. 'lines_map' => [],
  3334. ];
  3335. }
  3336. if ($byCompany[$cn]['remark'] === '') {
  3337. $rm = '';
  3338. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3339. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3340. $rm = trim((string)$d[$rk]);
  3341. break;
  3342. }
  3343. }
  3344. if ($rm !== '') {
  3345. $byCompany[$cn]['remark'] = $rm;
  3346. }
  3347. }
  3348. $sid = (int)($d['scydgy_id'] ?? 0);
  3349. $am = trim((string)($d['amount'] ?? ''));
  3350. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3351. if ($gymc === '') {
  3352. $gymc = '工序';
  3353. }
  3354. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3355. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3356. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3357. $deliveryShow = $deliveryRaw;
  3358. }
  3359. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3360. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3361. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3362. $subtotal = null;
  3363. if ($amountNum !== null) {
  3364. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3365. }
  3366. $unitPriceText = $amountFilled
  3367. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3368. : '未填写';
  3369. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3370. $leadFilled = ($leadDays !== null);
  3371. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3372. $lineRow = [
  3373. 'cgymc' => $gymc,
  3374. 'amount' => $am,
  3375. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3376. 'amount_filled' => $amountFilled,
  3377. 'unit_price_text' => $unitPriceText,
  3378. 'delivery' => $deliveryRaw,
  3379. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3380. 'delivery_filled' => $deliveryFilled,
  3381. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3382. 'lead_days' => $leadFilled ? $leadDays : '',
  3383. 'lead_days_filled'=> $leadFilled,
  3384. 'lead_days_show' => $leadText,
  3385. 'lead_days_text' => $leadText,
  3386. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3387. 'subtotal_num' => $subtotal,
  3388. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3389. 'is_quoted' => $amountFilled,
  3390. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3391. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3392. ];
  3393. if (!$quoteVisible) {
  3394. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3395. }
  3396. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3397. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3398. }
  3399. foreach ($byCompany as $cn => $g) {
  3400. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3401. $lines = [];
  3402. $usedSids = [];
  3403. foreach ($orderedSids as $sid) {
  3404. if (!isset($linesMap[$sid])) {
  3405. continue;
  3406. }
  3407. $lines[] = $linesMap[$sid];
  3408. $usedSids[$sid] = true;
  3409. }
  3410. foreach ($linesMap as $sid => $ln) {
  3411. if (isset($usedSids[$sid])) {
  3412. continue;
  3413. }
  3414. $lines[] = $ln;
  3415. }
  3416. $total = count($lines);
  3417. $quoted = 0;
  3418. $groupTotal = 0.0;
  3419. $groupHasTotal = false;
  3420. if ($quoteVisible) {
  3421. foreach ($lines as $ln) {
  3422. $am = trim((string)($ln['amount'] ?? ''));
  3423. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3424. $quoted++;
  3425. }
  3426. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3427. $groupTotal += (float)$ln['subtotal_num'];
  3428. $groupHasTotal = true;
  3429. }
  3430. }
  3431. }
  3432. unset($byCompany[$cn]['lines_map']);
  3433. $byCompany[$cn]['lines'] = $lines;
  3434. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3435. $byCompany[$cn]['line_count'] = $total;
  3436. $byCompany[$cn]['has_total'] = $total > 0;
  3437. $byCompany[$cn]['has_remark'] = $total > 0;
  3438. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3439. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3440. // 工序行 + 备注行 + 总计行
  3441. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3442. }
  3443. $groups = array_values($byCompany);
  3444. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3445. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3446. }
  3447. /**
  3448. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3449. *
  3450. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3451. * @return array<int, array<string, mixed>>
  3452. */
  3453. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3454. {
  3455. $sids = [];
  3456. $poIdMap = [];
  3457. foreach ($bundle['pos'] ?? [] as $po) {
  3458. if (!is_array($po)) {
  3459. continue;
  3460. }
  3461. $sid = (int)($po['scydgy_id'] ?? 0);
  3462. if ($this->isValidScydgyRowId($sid)) {
  3463. $sids[$sid] = true;
  3464. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3465. }
  3466. }
  3467. if ($sids === []) {
  3468. return [];
  3469. }
  3470. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3471. $gymcMap = [];
  3472. $qtyBySid = [];
  3473. $orderedSids = [];
  3474. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3475. if (!is_array($mr)) {
  3476. continue;
  3477. }
  3478. $gid = $this->extractScydgyRowId($mr);
  3479. if ($this->isValidScydgyRowId($gid)) {
  3480. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3481. $orderedSids[] = $gid;
  3482. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3483. if ($qty === '') {
  3484. $qty = trim((string)($mr['NGZL'] ?? ''));
  3485. }
  3486. $qtyBySid[$gid] = $qty;
  3487. }
  3488. }
  3489. foreach ($bundle['pos'] ?? [] as $po) {
  3490. if (!is_array($po)) {
  3491. continue;
  3492. }
  3493. $gid = (int)($po['scydgy_id'] ?? 0);
  3494. if ($this->isValidScydgyRowId($gid)) {
  3495. $nm = trim((string)($po['CGYMC'] ?? ''));
  3496. if ($nm !== '') {
  3497. $gymcMap[$gid] = $nm;
  3498. }
  3499. }
  3500. }
  3501. try {
  3502. $details = Db::table('purchase_order_detail')
  3503. ->where('scydgy_id', 'in', array_keys($sids))
  3504. ->order('company_name', 'asc')
  3505. ->order('id', 'asc')
  3506. ->select();
  3507. } catch (\Throwable $e) {
  3508. try {
  3509. $details = Db::table('purchase_order_detail')
  3510. ->where('scydgy_id', 'in', array_keys($sids))
  3511. ->order('company_name', 'asc')
  3512. ->order('ID', 'asc')
  3513. ->select();
  3514. } catch (\Throwable $e2) {
  3515. $details = [];
  3516. }
  3517. }
  3518. if (!is_array($details)) {
  3519. $details = [];
  3520. }
  3521. $byCompany = [];
  3522. foreach ($details as $d) {
  3523. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3524. continue;
  3525. }
  3526. $cn = trim((string)($d['company_name'] ?? ''));
  3527. if ($cn === '') {
  3528. continue;
  3529. }
  3530. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3531. $sid = (int)($d['scydgy_id'] ?? 0);
  3532. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3533. continue;
  3534. }
  3535. if (!isset($byCompany[$cn])) {
  3536. $ph = trim((string)($d['phone'] ?? ''));
  3537. $username = trim((string)($d['username'] ?? ''));
  3538. if ($username === '') {
  3539. $username = $this->resolveCustomerContactName($ph, $cn);
  3540. }
  3541. $byCompany[$cn] = [
  3542. 'name' => $cn,
  3543. 'email' => trim((string)($d['email'] ?? '')),
  3544. 'phone' => $ph,
  3545. 'username' => $username,
  3546. 'remark' => '',
  3547. 'pick_lines' => [],
  3548. 'detail_picks' => [],
  3549. ];
  3550. }
  3551. if ($byCompany[$cn]['remark'] === '') {
  3552. $rm = '';
  3553. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3554. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3555. $rm = trim((string)$d[$rk]);
  3556. break;
  3557. }
  3558. }
  3559. if ($rm !== '') {
  3560. $byCompany[$cn]['remark'] = $rm;
  3561. }
  3562. }
  3563. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3564. if ($gymc === '') {
  3565. $gymc = '工序';
  3566. }
  3567. $am = trim((string)($d['amount'] ?? ''));
  3568. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3569. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3570. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3571. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3572. $deliveryShow = $deliveryRaw;
  3573. }
  3574. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3575. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3576. $subtotal = null;
  3577. if ($amountNum !== null) {
  3578. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3579. }
  3580. $unitPriceText = $amountFilled
  3581. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3582. : '未填写';
  3583. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3584. $leadFilled = ($leadDays !== null);
  3585. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3586. $pickLine = [
  3587. 'cgymc' => $gymc,
  3588. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3589. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3590. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3591. 'amount_filled' => $amountFilled,
  3592. 'delivery_filled' => $deliveryFilled,
  3593. 'unit_price_text' => $unitPriceText,
  3594. 'lead_days' => $leadFilled ? $leadDays : '',
  3595. 'lead_days_filled'=> $leadFilled,
  3596. 'lead_days_show' => $leadText,
  3597. 'lead_days_text' => $leadText,
  3598. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3599. 'subtotal_num' => $subtotal,
  3600. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3601. 'is_quoted' => $amountFilled,
  3602. ];
  3603. if (!$quoteVisible) {
  3604. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3605. }
  3606. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3607. $byCompany[$cn]['detail_picks'][$sid] = [
  3608. 'scydgy_id' => $sid,
  3609. 'detail_id' => $detailId,
  3610. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3611. 'cgymc' => $gymc,
  3612. ];
  3613. }
  3614. $out = [];
  3615. foreach ($byCompany as $g) {
  3616. $pickLinesMap = $g['pick_lines'] ?? [];
  3617. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3618. continue;
  3619. }
  3620. $pickLines = [];
  3621. $usedLineSids = [];
  3622. foreach ($orderedSids as $sid) {
  3623. if (!isset($pickLinesMap[$sid])) {
  3624. continue;
  3625. }
  3626. $pickLines[] = $pickLinesMap[$sid];
  3627. $usedLineSids[$sid] = true;
  3628. }
  3629. foreach ($pickLinesMap as $sid => $ln) {
  3630. if (isset($usedLineSids[$sid])) {
  3631. continue;
  3632. }
  3633. $pickLines[] = $ln;
  3634. }
  3635. $groupTotal = 0.0;
  3636. $groupHasTotal = false;
  3637. if ($quoteVisible) {
  3638. foreach ($pickLines as $ln) {
  3639. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3640. $groupTotal += (float)$ln['subtotal_num'];
  3641. $groupHasTotal = true;
  3642. }
  3643. }
  3644. }
  3645. $lineCount = count($pickLines);
  3646. $g['pick_lines'] = $pickLines;
  3647. $g['line_count'] = $lineCount;
  3648. $g['has_total'] = $lineCount > 0;
  3649. $g['has_remark'] = $lineCount > 0;
  3650. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3651. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3652. // 工序行 + 备注行 + 总计行
  3653. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3654. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3655. $detailPicks = [];
  3656. $usedPickSids = [];
  3657. foreach ($orderedSids as $sid) {
  3658. if (!isset($detailPicksMap[$sid])) {
  3659. continue;
  3660. }
  3661. $detailPicks[] = $detailPicksMap[$sid];
  3662. $usedPickSids[$sid] = true;
  3663. }
  3664. foreach ($detailPicksMap as $sid => $dp) {
  3665. if (isset($usedPickSids[$sid])) {
  3666. continue;
  3667. }
  3668. $detailPicks[] = $dp;
  3669. }
  3670. $g['detail_picks'] = $detailPicks;
  3671. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3672. unset($g['detail_picks']);
  3673. $out[] = $g;
  3674. }
  3675. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3676. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3677. }
  3678. /**
  3679. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3680. * @return array<int, int[]> scydgy_id => detail_id[]
  3681. */
  3682. protected function mapDetailIdsByScydgyId(array $details): array
  3683. {
  3684. $out = [];
  3685. foreach ($details as $d) {
  3686. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3687. continue;
  3688. }
  3689. $sid = (int)($d['scydgy_id'] ?? 0);
  3690. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3691. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3692. continue;
  3693. }
  3694. if (!isset($out[$sid])) {
  3695. $out[$sid] = [];
  3696. }
  3697. $out[$sid][] = $pk;
  3698. }
  3699. foreach ($out as $sid => $ids) {
  3700. $out[$sid] = array_values(array_unique($ids));
  3701. }
  3702. return $out;
  3703. }
  3704. /**
  3705. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3706. *
  3707. * @param array<string, mixed> $dbRow
  3708. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3709. */
  3710. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3711. {
  3712. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3713. $r = [
  3714. 'ID' => $sid,
  3715. 'scydgy_id' => $sid,
  3716. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3717. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3718. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3719. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3720. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3721. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3722. 'CDW' => $dbRow['CDW'] ?? '',
  3723. 'czlyq' => $dbRow['czlyq'] ?? '',
  3724. 'NGZL' => $dbRow['NGZL'] ?? '',
  3725. 'CDF' => $dbRow['CDF'] ?? '',
  3726. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3727. 'MBZ' => $dbRow['MBZ'] ?? '',
  3728. 'bwjg' => $dbRow['bwjg'] ?? '',
  3729. 'iStatus' => $dbRow['iStatus'] ?? '',
  3730. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3731. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3732. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3733. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3734. 'dStamp' => $dbRow['dStamp'] ?? '',
  3735. 'pick_time' => $dbRow['pick_time'] ?? '',
  3736. ];
  3737. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3738. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3739. if ($sid > 0 && isset($dStampMap[$sid])) {
  3740. $t = trim((string)$dStampMap[$sid]);
  3741. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3742. $r['dStamp'] = $dStampMap[$sid];
  3743. }
  3744. }
  3745. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3746. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3747. $ct = $dbRow['createtime'];
  3748. if (is_numeric($ct) && (int)$ct > 946684800) {
  3749. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3750. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3751. $r['dStamp'] = trim($ct);
  3752. }
  3753. }
  3754. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3755. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3756. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3757. $fallback = trim((string)($r['dStamp'] ?? ''));
  3758. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3759. $r['dputrecord'] = $fallback;
  3760. }
  3761. }
  3762. if (array_key_exists('id', $dbRow)) {
  3763. $r['purchase_order_id'] = (int)$dbRow['id'];
  3764. }
  3765. if ($sid < 0) {
  3766. $r['_is_manual'] = 1;
  3767. }
  3768. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3769. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3770. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3771. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3772. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3773. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3774. $r['pick_time'] = $pickFallback;
  3775. break;
  3776. }
  3777. }
  3778. }
  3779. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3780. if ($pickNm !== '') {
  3781. $r['pick_company_name'] = $pickNm;
  3782. $r['picked_supplier_name'] = $pickNm;
  3783. }
  3784. return $r;
  3785. }
  3786. /**
  3787. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3788. *
  3789. * @return array<int, array<string, mixed>>
  3790. */
  3791. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3792. {
  3793. $pool = [];
  3794. if (!is_array($dbRows) || $dbRows === []) {
  3795. return $pool;
  3796. }
  3797. $dStampMap = [];
  3798. $sidList = [];
  3799. foreach ($dbRows as $tmpRow) {
  3800. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3801. $sid = (int)$tmpRow['scydgy_id'];
  3802. if ($sid > 0) {
  3803. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3804. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3805. $sidList[$sid] = true;
  3806. }
  3807. }
  3808. }
  3809. }
  3810. if ($sidList !== []) {
  3811. try {
  3812. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3813. } catch (\Throwable $e) {
  3814. $dStampMap = [];
  3815. }
  3816. }
  3817. foreach ($dbRows as $dbRow) {
  3818. if (!is_array($dbRow)) {
  3819. continue;
  3820. }
  3821. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3822. }
  3823. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3824. $needCcydh = [];
  3825. foreach ($pool as $row) {
  3826. if (!is_array($row)) {
  3827. continue;
  3828. }
  3829. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3830. continue;
  3831. }
  3832. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3833. if ($ccydh !== '') {
  3834. $needCcydh[$ccydh] = true;
  3835. }
  3836. }
  3837. if ($needCcydh !== []) {
  3838. $czMap = [];
  3839. try {
  3840. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3841. } catch (\Throwable $e) {
  3842. $czMap = [];
  3843. }
  3844. if (is_array($czMap) && $czMap !== []) {
  3845. foreach ($pool as &$row) {
  3846. if (!is_array($row)) {
  3847. continue;
  3848. }
  3849. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3850. continue;
  3851. }
  3852. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3853. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3854. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3855. }
  3856. }
  3857. unset($row);
  3858. }
  3859. }
  3860. return $pool;
  3861. }
  3862. /**
  3863. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3864. *
  3865. * @param int[] $scydgyIds
  3866. * @return array<int, array<string, mixed>>
  3867. */
  3868. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3869. {
  3870. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3871. if ($scydgyIds === []) {
  3872. return [];
  3873. }
  3874. try {
  3875. $list = Db::table('purchase_order_detail')
  3876. ->where('scydgy_id', 'in', $scydgyIds)
  3877. ->field('scydgy_id,company_name,amount,delivery')
  3878. ->select();
  3879. } catch (\Throwable $e) {
  3880. $list = [];
  3881. }
  3882. return is_array($list) ? $list : [];
  3883. }
  3884. /**
  3885. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3886. *
  3887. * @param int[] $scydgyIds
  3888. * @param array<int, array<string, mixed>> $allRows
  3889. * @return array{cnt:int, amt:int, deliv:int}
  3890. */
  3891. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3892. {
  3893. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3894. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3895. if ($scydgyIds === [] || $allRows === []) {
  3896. return $out;
  3897. }
  3898. $idSet = array_flip($scydgyIds);
  3899. $all = [];
  3900. $withAmt = [];
  3901. $withDeliv = [];
  3902. foreach ($allRows as $r) {
  3903. if (!is_array($r)) {
  3904. continue;
  3905. }
  3906. $sid = (int)($r['scydgy_id'] ?? 0);
  3907. if (!isset($idSet[$sid])) {
  3908. continue;
  3909. }
  3910. $cn = trim((string)($r['company_name'] ?? ''));
  3911. if ($cn === '') {
  3912. continue;
  3913. }
  3914. $all[$cn] = true;
  3915. $am = $r['amount'] ?? null;
  3916. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3917. $withAmt[$cn] = true;
  3918. }
  3919. $dv = $r['delivery'] ?? null;
  3920. if ($dv !== null && trim((string)$dv) !== '') {
  3921. $withDeliv[$cn] = true;
  3922. }
  3923. }
  3924. return [
  3925. 'cnt' => count($all),
  3926. 'amt' => count($withAmt),
  3927. 'deliv' => count($withDeliv),
  3928. ];
  3929. }
  3930. /**
  3931. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3932. *
  3933. * @param array<string, mixed> $row
  3934. */
  3935. protected function resolveProcuremenThisQuantity(array $row): string
  3936. {
  3937. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3938. if ($q !== '') {
  3939. return $q;
  3940. }
  3941. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3942. if (!is_scalar($ngzl)) {
  3943. return '';
  3944. }
  3945. $s = trim((string)$ngzl);
  3946. if ($s === '') {
  3947. return '';
  3948. }
  3949. if (is_numeric($s) && (float)$s === 0.0) {
  3950. return '';
  3951. }
  3952. return $s;
  3953. }
  3954. /**
  3955. * @param array<string, mixed> $row
  3956. */
  3957. protected function resolveProcuremenCeilingPrice(array $row): string
  3958. {
  3959. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3960. }
  3961. /**
  3962. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3963. *
  3964. * @param array<int, mixed> $parts
  3965. */
  3966. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3967. {
  3968. $out = [];
  3969. foreach ($parts as $p) {
  3970. $s = trim((string)$p);
  3971. if ($s !== '') {
  3972. $out[] = $s;
  3973. }
  3974. }
  3975. return $out === [] ? '' : implode($sep, $out);
  3976. }
  3977. /**
  3978. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3979. *
  3980. * @param array<int, array<string, mixed>> $rows
  3981. */
  3982. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3983. {
  3984. if ($rows === []) {
  3985. return;
  3986. }
  3987. $idList = [];
  3988. foreach ($rows as $rw) {
  3989. if (!is_array($rw)) {
  3990. continue;
  3991. }
  3992. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3993. foreach ($rw['_order_merge_rows'] as $mr) {
  3994. if (!is_array($mr)) {
  3995. continue;
  3996. }
  3997. $mid = (int)($mr['ID'] ?? 0);
  3998. if ($this->isValidScydgyRowId($mid)) {
  3999. $idList[$mid] = true;
  4000. }
  4001. }
  4002. }
  4003. $id = (int)($rw['ID'] ?? 0);
  4004. if ($this->isValidScydgyRowId($id)) {
  4005. $idList[$id] = true;
  4006. }
  4007. }
  4008. if ($idList === []) {
  4009. return;
  4010. }
  4011. try {
  4012. $list = Db::table('purchase_order')
  4013. ->where('scydgy_id', 'in', array_keys($idList))
  4014. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4015. ->select();
  4016. } catch (\Throwable $e) {
  4017. return;
  4018. }
  4019. if (!is_array($list)) {
  4020. return;
  4021. }
  4022. $byId = [];
  4023. foreach ($list as $dbRow) {
  4024. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4025. continue;
  4026. }
  4027. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4028. }
  4029. foreach ($rows as &$rw) {
  4030. if (!is_array($rw)) {
  4031. continue;
  4032. }
  4033. $mergeRows = [];
  4034. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4035. $mergeRows = $rw['_order_merge_rows'];
  4036. } else {
  4037. $mergeRows = [$rw];
  4038. }
  4039. $qtyList = [];
  4040. $priceList = [];
  4041. $picked = '';
  4042. foreach ($mergeRows as $mr) {
  4043. if (!is_array($mr)) {
  4044. continue;
  4045. }
  4046. $sid = (int)($mr['ID'] ?? 0);
  4047. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4048. $src = $mr;
  4049. if (is_array($db)) {
  4050. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4051. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4052. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4053. if ($qDb !== '') {
  4054. $src['This_quantity'] = $qDb;
  4055. }
  4056. if ($pDb !== '') {
  4057. $src['ceilingPrice'] = $pDb;
  4058. }
  4059. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4060. $src['NGZL'] = $ngzlDb;
  4061. }
  4062. if ($picked === '') {
  4063. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4064. }
  4065. }
  4066. if ($picked === '') {
  4067. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4068. }
  4069. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4070. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4071. }
  4072. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4073. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4074. if ($picked !== '') {
  4075. $rw['pick_company_name'] = $picked;
  4076. $rw['picked_supplier_name'] = $picked;
  4077. }
  4078. }
  4079. unset($rw);
  4080. }
  4081. /**
  4082. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4083. *
  4084. * @param int[] $scydgyIds
  4085. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4086. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4087. */
  4088. protected function OrderDetailSummary(array $scydgyIds)
  4089. {
  4090. $out = [];
  4091. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4092. if ($scydgyIds === []) {
  4093. return $out;
  4094. }
  4095. $list = [];
  4096. try {
  4097. $list = Db::table('purchase_order_detail')
  4098. ->where('scydgy_id', 'in', $scydgyIds)
  4099. ->field('id,scydgy_id,amount,delivery')
  4100. ->select();
  4101. } catch (\Throwable $e) {
  4102. $list = [];
  4103. }
  4104. if (!is_array($list)) {
  4105. return $out;
  4106. }
  4107. foreach ($list as $r) {
  4108. if (!is_array($r)) {
  4109. continue;
  4110. }
  4111. $ids = (int)($r['scydgy_id'] ?? 0);
  4112. if (!$this->isValidScydgyRowId($ids)) {
  4113. continue;
  4114. }
  4115. if (!isset($out[$ids])) {
  4116. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4117. }
  4118. $out[$ids]['cnt']++;
  4119. $am = $r['amount'] ?? null;
  4120. if ($am !== null && $am !== '') {
  4121. if (!(is_string($am) && trim($am) === '')) {
  4122. $out[$ids]['amt']++;
  4123. }
  4124. }
  4125. $dv = $r['delivery'] ?? null;
  4126. if ($dv !== null && trim((string)$dv) !== '') {
  4127. $out[$ids]['deliv']++;
  4128. }
  4129. }
  4130. return $out;
  4131. }
  4132. /**
  4133. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4134. *
  4135. * @return array
  4136. */
  4137. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4138. {
  4139. $strContains = function ($haystack, $needle) {
  4140. if ($needle === '') {
  4141. return false;
  4142. }
  4143. $haystack = (string)$haystack;
  4144. if (function_exists('mb_stripos')) {
  4145. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4146. }
  4147. return stripos($haystack, $needle) !== false;
  4148. };
  4149. $stripAlias = function ($f) {
  4150. return preg_replace('/^[ab]\./i', '', (string)$f);
  4151. };
  4152. $searchColNames = [];
  4153. foreach (explode(',', $this->searchFields) as $colRaw) {
  4154. $c = $stripAlias(trim($colRaw));
  4155. if ($c !== '') {
  4156. $searchColNames[] = $c;
  4157. }
  4158. }
  4159. // 等值条件先行(表头下拉),减少后续日期解析量
  4160. $eqFilters = [];
  4161. $otherFilters = [];
  4162. foreach ($filterArr as $fk => $fv) {
  4163. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4164. continue;
  4165. }
  4166. if (is_array($fv)) {
  4167. continue;
  4168. }
  4169. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4170. continue;
  4171. }
  4172. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4173. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4174. $field = $stripAlias($fk);
  4175. if ($sym === '=' || $sym === '') {
  4176. $eqFilters[$field] = trim((string)$fv);
  4177. } else {
  4178. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4179. }
  4180. }
  4181. $ymTarget = '';
  4182. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4183. $ymTarget = $ymM[1];
  4184. }
  4185. $filtered = [];
  4186. foreach ($pool as $r) {
  4187. if (!is_array($r)) {
  4188. continue;
  4189. }
  4190. foreach ($eqFilters as $field => $fv) {
  4191. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4192. continue 2;
  4193. }
  4194. }
  4195. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4196. // 初选池不应含手工单;若混入则直接剔除
  4197. if ($isManual) {
  4198. continue;
  4199. }
  4200. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4201. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4202. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4203. continue;
  4204. }
  4205. if ($applyMonthRange) {
  4206. $mo = (int)$m[2];
  4207. if ($mo < 1 || $mo > 12) {
  4208. continue;
  4209. }
  4210. if ($ymTarget !== '') {
  4211. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4212. if ($ymRow !== $ymTarget) {
  4213. continue;
  4214. }
  4215. } else {
  4216. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4217. $rowMonthStart = $ymRow . '-01 00:00:00';
  4218. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4219. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4220. continue;
  4221. }
  4222. }
  4223. }
  4224. if ($search !== '') {
  4225. $hitSearch = false;
  4226. foreach ($searchColNames as $c) {
  4227. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4228. if ($cell !== '' && $strContains($cell, $search)) {
  4229. $hitSearch = true;
  4230. break;
  4231. }
  4232. }
  4233. if (!$hitSearch) {
  4234. continue;
  4235. }
  4236. }
  4237. foreach ($otherFilters as $item) {
  4238. $fv = $item['fv'];
  4239. $sym = $item['sym'];
  4240. $field = $item['field'];
  4241. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4242. $cellStr = trim((string)$cell);
  4243. switch ($sym) {
  4244. case '<>':
  4245. if ((string)$cell === (string)$fv) {
  4246. continue 3;
  4247. }
  4248. break;
  4249. case 'LIKE':
  4250. case 'NOT LIKE':
  4251. $needle = trim((string)$fv);
  4252. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4253. if ($sym === 'LIKE' && !$hit) {
  4254. continue 3;
  4255. }
  4256. if ($sym === 'NOT LIKE' && $hit) {
  4257. continue 3;
  4258. }
  4259. break;
  4260. case 'BETWEEN':
  4261. case 'RANGE':
  4262. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4263. if (count($parts) < 2) {
  4264. $parts = is_string($fv) ? explode(',', $fv) : [];
  4265. }
  4266. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4267. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4268. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4269. continue 3;
  4270. }
  4271. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4272. continue 3;
  4273. }
  4274. break;
  4275. case '>':
  4276. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4277. continue 3;
  4278. }
  4279. break;
  4280. case '>=':
  4281. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4282. continue 3;
  4283. }
  4284. break;
  4285. case '<':
  4286. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4287. continue 3;
  4288. }
  4289. break;
  4290. case '<=':
  4291. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4292. continue 3;
  4293. }
  4294. break;
  4295. default:
  4296. if ((string)$cell !== (string)$fv) {
  4297. continue 3;
  4298. }
  4299. break;
  4300. }
  4301. }
  4302. $filtered[] = $r;
  4303. }
  4304. return $filtered;
  4305. }
  4306. /**
  4307. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4308. */
  4309. public function snapshotToProcure()
  4310. {
  4311. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4312. $this->error(__('Invalid parameters'));
  4313. }
  4314. $row = json_decode($this->request->post('row_json', ''), true);
  4315. if (!is_array($row)) {
  4316. $this->error(__('Invalid parameters'));
  4317. }
  4318. try {
  4319. $ids = $this->extractScydgyRowId($row);
  4320. if (!$this->isValidScydgyRowId($ids)) {
  4321. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4322. }
  4323. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4324. $data = [
  4325. 'scydgy_id' => $ids,
  4326. 'CCYDH' => $row['CCYDH'] ?? null,
  4327. 'CYJMC' => $row['CYJMC'] ?? null,
  4328. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4329. 'CDXMC' => $row['CDXMC'] ?? null,
  4330. 'CGYBH' => $row['CGYBH'] ?? null,
  4331. 'CGYMC' => $row['CGYMC'] ?? null,
  4332. 'CDW' => $row['CDW'] ?? null,
  4333. 'czlyq' => $row['czlyq'] ?? null,
  4334. 'NGZL' => $row['NGZL'] ?? null,
  4335. 'CDF' => $row['CDF'] ?? null,
  4336. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4337. 'MBZ' => $row['MBZ'] ?? null,
  4338. 'bwjg' => $row['bwjg'] ?? null,
  4339. 'iStatus' => $row['iStatus'] ?? null,
  4340. 'dStamp' => $row['dStamp'] ?? null,
  4341. 'dputrecord' => $row['dputrecord'] ?? null,
  4342. 'cywyxm' => $row['cywyxm'] ?? null,
  4343. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4344. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4345. ];
  4346. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4347. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4348. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4349. $this->success('操作成功');
  4350. return;
  4351. }
  4352. if ($exists) {
  4353. $upd = $data;
  4354. unset($upd['scydgy_id'], $upd['status']);
  4355. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4356. } else {
  4357. // 新增:不写 status(空/走库默认);仅写创建时间
  4358. $data['createtime'] = date('Y-m-d H:i:s');
  4359. Db::table('purchase_order')->insert($data);
  4360. }
  4361. } catch (\Throwable $e) {
  4362. $this->error($e->getMessage());
  4363. }
  4364. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4365. $this->success('操作成功');
  4366. }
  4367. /**
  4368. * 未发列表
  4369. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4370. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4371. */
  4372. public function completeDirectly()
  4373. {
  4374. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4375. $this->error(__('参数错误'));
  4376. }
  4377. if (!$this->procuremenCanComplete()) {
  4378. $this->error(__('You have no permission'));
  4379. }
  4380. $row = json_decode($this->request->post('row_json', ''), true);
  4381. if (!is_array($row)) {
  4382. $this->error(__('Invalid parameters'));
  4383. }
  4384. $finishRaw = $this->request->post('finish', '1');
  4385. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4386. $poIdLog = null;
  4387. try {
  4388. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4389. $ids = $this->extractScydgyRowId($row);
  4390. if (!$this->isValidScydgyRowId($ids)) {
  4391. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4392. }
  4393. if ($asComplete) {
  4394. $this->assertPickRowCanComplete($ids, $row);
  4395. }
  4396. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4397. $data = [
  4398. 'scydgy_id' => $ids,
  4399. 'CCYDH' => $row['CCYDH'] ?? null,
  4400. 'CYJMC' => $row['CYJMC'] ?? null,
  4401. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4402. 'CDXMC' => $row['CDXMC'] ?? null,
  4403. 'CGYBH' => $row['CGYBH'] ?? null,
  4404. 'CGYMC' => $row['CGYMC'] ?? null,
  4405. 'CDW' => $row['CDW'] ?? null,
  4406. 'czlyq' => $row['czlyq'] ?? null,
  4407. 'NGZL' => $row['NGZL'] ?? null,
  4408. 'CDF' => $row['CDF'] ?? null,
  4409. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4410. 'MBZ' => $row['MBZ'] ?? null,
  4411. 'bwjg' => $row['bwjg'] ?? null,
  4412. 'iStatus' => $row['iStatus'] ?? null,
  4413. 'dStamp' => $row['dStamp'] ?? null,
  4414. 'dputrecord' => $row['dputrecord'] ?? null,
  4415. 'cywyxm' => $row['cywyxm'] ?? null,
  4416. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4417. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4418. ];
  4419. if ($asComplete) {
  4420. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4421. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4422. }
  4423. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4424. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4425. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4426. $this->success('操作成功');
  4427. return;
  4428. }
  4429. if ($exists) {
  4430. $upd = $data;
  4431. unset($upd['scydgy_id']);
  4432. if (!$asComplete) {
  4433. unset($upd['status']);
  4434. }
  4435. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4436. } else {
  4437. // 新增:不写 status;完结时 $data 已含 status=1
  4438. $data['createtime'] = date('Y-m-d H:i:s');
  4439. Db::table('purchase_order')->insert($data);
  4440. }
  4441. } catch (\Throwable $e) {
  4442. $this->error($e->getMessage());
  4443. }
  4444. try {
  4445. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4446. if (is_array($rpo)) {
  4447. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4448. $poIdLog = $tid > 0 ? $tid : null;
  4449. }
  4450. } catch (\Throwable $e) {
  4451. $poIdLog = null;
  4452. }
  4453. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4454. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4455. if ($asComplete) {
  4456. $this->addOrderLog(
  4457. $ids,
  4458. 'mark_complete',
  4459. '点击「完结」,已标记为已完结',
  4460. $poIdLog
  4461. );
  4462. try {
  4463. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4464. if ($pdfPublicPath === '') {
  4465. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4466. }
  4467. } catch (\Throwable $e) {
  4468. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4469. }
  4470. } else {
  4471. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4472. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4473. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4474. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4475. $this->addOrderLog(
  4476. $ids,
  4477. 'save_qty_price',
  4478. '保存本次数量、最高限价:' . $detail,
  4479. $poIdLog
  4480. );
  4481. }
  4482. $this->pickHiddenScydgySetCache = null;
  4483. $this->success("操作成功");
  4484. }
  4485. /**
  4486. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4487. *
  4488. * @param array<int, array> $rows 引用传递当前页行
  4489. */
  4490. protected function mergePurchaseOrder(array &$rows)
  4491. {
  4492. if ($rows === []) {
  4493. return;
  4494. }
  4495. $ids = [];
  4496. foreach ($rows as $rw) {
  4497. if (!is_array($rw)) {
  4498. continue;
  4499. }
  4500. $id = (int)($rw['ID'] ?? 0);
  4501. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4502. if ($this->isValidScydgyRowId($id)) {
  4503. $ids[$id] = true;
  4504. }
  4505. }
  4506. $idList = array_keys($ids);
  4507. if ($idList === []) {
  4508. return;
  4509. }
  4510. try {
  4511. $list = Db::table('purchase_order')
  4512. ->where('scydgy_id', 'in', $idList)
  4513. ->field('scydgy_id,This_quantity,ceilingPrice')
  4514. ->select();
  4515. } catch (\Throwable $e) {
  4516. return;
  4517. }
  4518. if (!is_array($list)) {
  4519. return;
  4520. }
  4521. $byId = [];
  4522. foreach ($list as $dbRow) {
  4523. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4524. continue;
  4525. }
  4526. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4527. }
  4528. foreach ($rows as &$rw) {
  4529. if (!is_array($rw)) {
  4530. continue;
  4531. }
  4532. $sid = (int)($rw['ID'] ?? 0);
  4533. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4534. continue;
  4535. }
  4536. $db = $byId[$sid];
  4537. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4538. if (array_key_exists('This_quantity', $db)) {
  4539. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4540. }
  4541. if (array_key_exists('ceilingPrice', $db)) {
  4542. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4543. } elseif (array_key_exists('ceiling_price', $db)) {
  4544. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4545. }
  4546. }
  4547. unset($rw);
  4548. }
  4549. /**
  4550. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4551. */
  4552. public function purchaseConfirmPick()
  4553. {
  4554. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4555. $this->error(__('Invalid parameters'));
  4556. }
  4557. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4558. $this->error(__('You have no permission'));
  4559. }
  4560. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4561. if ($batchRaw !== '') {
  4562. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4563. return;
  4564. }
  4565. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4566. $sid = (int)$scydgyId;
  4567. if (!$this->isValidScydgyRowId($sid)) {
  4568. $this->error('参数无效');
  4569. }
  4570. $parseIdList = function ($raw) {
  4571. if (is_array($raw)) {
  4572. $arr = $raw;
  4573. } else {
  4574. $decoded = json_decode((string)$raw, true);
  4575. $arr = is_array($decoded) ? $decoded : [];
  4576. }
  4577. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4578. };
  4579. $selectedRaw = $this->request->post('selected_ids', null);
  4580. if ($selectedRaw === null || $selectedRaw === '') {
  4581. $legacy = (int)$this->request->post('selected_id', 0);
  4582. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4583. } else {
  4584. $selectedIds = $parseIdList($selectedRaw);
  4585. }
  4586. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4587. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4588. try {
  4589. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4590. } catch (\InvalidArgumentException $e) {
  4591. $this->error($e->getMessage());
  4592. } catch (\Throwable $e) {
  4593. $this->error($e->getMessage());
  4594. }
  4595. $this->pickHiddenScydgySetCache = null;
  4596. $this->success('操作成功', '', $result);
  4597. }
  4598. /**
  4599. * 整单采购确认(多道工序一次提交)
  4600. */
  4601. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4602. {
  4603. $decoded = json_decode($batchRaw, true);
  4604. if (!is_array($decoded) || $decoded === []) {
  4605. $this->error('提交数据无效');
  4606. }
  4607. $picks = [];
  4608. foreach ($decoded as $item) {
  4609. if (!is_array($item)) {
  4610. continue;
  4611. }
  4612. $sid = (int)($item['scydgy_id'] ?? 0);
  4613. if (!$this->isValidScydgyRowId($sid)) {
  4614. continue;
  4615. }
  4616. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4617. if (!is_array($sel)) {
  4618. $sel = [(int)$sel];
  4619. }
  4620. $unsel = $item['unselected_ids'] ?? [];
  4621. if (!is_array($unsel)) {
  4622. $unsel = json_decode((string)$unsel, true);
  4623. $unsel = is_array($unsel) ? $unsel : [];
  4624. }
  4625. $picks[] = [
  4626. 'scydgy_id' => $sid,
  4627. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4628. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4629. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4630. ];
  4631. }
  4632. if ($picks === []) {
  4633. $this->error('提交数据无效');
  4634. }
  4635. Db::startTrans();
  4636. $results = [];
  4637. try {
  4638. foreach ($picks as $pick) {
  4639. $results[] = $this->runPurchaseConfirmPick(
  4640. (int)$pick['scydgy_id'],
  4641. $pick['selected_ids'],
  4642. $pick['unselected_ids'],
  4643. (int)$pick['purchase_order_id'],
  4644. false,
  4645. false
  4646. );
  4647. }
  4648. Db::commit();
  4649. } catch (\Throwable $e) {
  4650. Db::rollback();
  4651. $msg = $e->getMessage();
  4652. $this->error($msg !== '' ? $msg : '提交失败');
  4653. }
  4654. try {
  4655. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4656. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4657. } catch (\Throwable $e) {
  4658. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4659. }
  4660. $this->pickHiddenScydgySetCache = null;
  4661. $this->success('操作成功', '', ['batch' => $results]);
  4662. }
  4663. /**
  4664. * @return array<string, mixed>
  4665. */
  4666. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4667. {
  4668. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4669. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4670. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4671. $scydgyId = (string)$sid;
  4672. if ($selectedIds === []) {
  4673. throw new \InvalidArgumentException('请至少勾选一条明细');
  4674. }
  4675. $inter = array_intersect($selectedIds, $unselectedIds);
  4676. if ($inter !== []) {
  4677. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4678. }
  4679. $allIds = $this->purchaseOrderDetail($sid);
  4680. if ($allIds === []) {
  4681. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4682. }
  4683. foreach ($selectedIds as $id) {
  4684. if (!in_array($id, $allIds, true)) {
  4685. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4686. }
  4687. }
  4688. foreach ($unselectedIds as $id) {
  4689. if (!in_array($id, $allIds, true)) {
  4690. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4691. }
  4692. }
  4693. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4694. sort($union, SORT_NUMERIC);
  4695. $expect = $allIds;
  4696. sort($expect, SORT_NUMERIC);
  4697. if ($union !== $expect) {
  4698. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4699. }
  4700. if ($manageTransaction) {
  4701. Db::startTrans();
  4702. }
  4703. try {
  4704. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4705. $aff = 0;
  4706. try {
  4707. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4708. } catch (\Throwable $e) {
  4709. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4710. }
  4711. if ($aff < 1) {
  4712. throw new \Exception('更新选中状态失败');
  4713. }
  4714. $poPayload = [
  4715. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4716. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4717. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4718. ];
  4719. if ($purchaseOrderId > 0) {
  4720. $poAff = (int)Db::table('purchase_order')
  4721. ->where('id', $purchaseOrderId)
  4722. ->where('scydgy_id', $sid)
  4723. ->update($poPayload);
  4724. if ($poAff < 1) {
  4725. throw new \Exception('主表订单不存在或与工序行不匹配');
  4726. }
  4727. } else {
  4728. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4729. if ($poAff < 1) {
  4730. throw new \Exception('未找到');
  4731. }
  4732. }
  4733. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4734. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4735. if ($manageTransaction) {
  4736. Db::commit();
  4737. }
  4738. } catch (\Throwable $e) {
  4739. if ($manageTransaction) {
  4740. Db::rollback();
  4741. }
  4742. throw $e;
  4743. }
  4744. $poIdFinal = $purchaseOrderId;
  4745. if ($poIdFinal <= 0) {
  4746. try {
  4747. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4748. if (is_array($rpo)) {
  4749. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4750. }
  4751. } catch (\Throwable $e) {
  4752. $poIdFinal = 0;
  4753. }
  4754. }
  4755. $pickNames = [];
  4756. foreach ($selectedIds as $pid) {
  4757. $dr = $this->purchaseOrderDetai($sid, $pid);
  4758. $nm = trim((string)($dr['company_name'] ?? ''));
  4759. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4760. }
  4761. $this->addOrderLog(
  4762. $sid,
  4763. 'purchase_confirm',
  4764. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4765. $poIdFinal > 0 ? $poIdFinal : null
  4766. );
  4767. if ($sendNotifications) {
  4768. try {
  4769. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4770. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4771. 'scydgy_id' => $sid,
  4772. 'selected_ids' => $selectedIds,
  4773. 'unselected_ids' => $unselectedIds,
  4774. 'purchase_order_id' => $purchaseOrderId,
  4775. ]]);
  4776. } catch (\Throwable $e) {
  4777. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4778. }
  4779. }
  4780. Log::write(sprintf(
  4781. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4782. $scydgyId,
  4783. $purchaseOrderId,
  4784. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4785. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4786. ), 'notice');
  4787. $pdfPublicPath = '';
  4788. try {
  4789. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4790. } catch (\Throwable $e) {
  4791. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4792. }
  4793. return [
  4794. 'scydgy_id' => $scydgyId,
  4795. 'purchase_order_id' => $purchaseOrderId,
  4796. 'selected_ids' => $selectedIds,
  4797. 'unselected_ids' => $unselectedIds,
  4798. 'purchase_confirm_pdf' => $pdfPublicPath,
  4799. ];
  4800. }
  4801. /**
  4802. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4803. *
  4804. * @param int[]|string[] $scydgyIds
  4805. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4806. */
  4807. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4808. {
  4809. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4810. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4811. if ($scydgyIds === []) {
  4812. return $empty;
  4813. }
  4814. $pos = [];
  4815. try {
  4816. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4817. } catch (\Throwable $e) {
  4818. $rows = [];
  4819. }
  4820. if (is_array($rows)) {
  4821. foreach ($rows as $po) {
  4822. if (is_array($po)) {
  4823. $pos[] = $po;
  4824. }
  4825. }
  4826. }
  4827. if ($pos === []) {
  4828. return $empty;
  4829. }
  4830. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4831. return [
  4832. 'ccydh' => $ccydh,
  4833. 'pos' => $pos,
  4834. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4835. ];
  4836. }
  4837. /**
  4838. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4839. *
  4840. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4841. * @param array<int, array<string, mixed>> $picks
  4842. */
  4843. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4844. {
  4845. if ($picks === []) {
  4846. return;
  4847. }
  4848. $fallbackDetailId = 0;
  4849. $winners = [];
  4850. $losers = [];
  4851. foreach ($picks as $pick) {
  4852. if (!is_array($pick)) {
  4853. continue;
  4854. }
  4855. $sid = (int)($pick['scydgy_id'] ?? 0);
  4856. if (!$this->isValidScydgyRowId($sid)) {
  4857. continue;
  4858. }
  4859. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4860. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4861. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4862. $fallbackDetailId = (int)$selectedIds[0];
  4863. }
  4864. foreach ($selectedIds as $pid) {
  4865. $dr = $this->purchaseOrderDetai($sid, $pid);
  4866. if (!is_array($dr)) {
  4867. continue;
  4868. }
  4869. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4870. }
  4871. foreach ($unselectedIds as $pid) {
  4872. $dr = $this->purchaseOrderDetai($sid, $pid);
  4873. if (!is_array($dr)) {
  4874. continue;
  4875. }
  4876. $key = $this->notifySupplierDedupeKey($dr);
  4877. if (!isset($winners[$key])) {
  4878. $losers[$key] = $dr;
  4879. }
  4880. }
  4881. }
  4882. if ($winners === [] && $losers === []) {
  4883. return;
  4884. }
  4885. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4886. $sendSmsSafe = function ($phone, $content) {
  4887. $phone = trim((string)$phone);
  4888. if ($phone === '') {
  4889. return;
  4890. }
  4891. try {
  4892. $this->smsbao($phone, $content);
  4893. } catch (\Throwable $e) {
  4894. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4895. }
  4896. };
  4897. foreach ($winners as $dr) {
  4898. $cname = trim((string)($dr['company_name'] ?? ''));
  4899. $ph = trim((string)($dr['phone'] ?? ''));
  4900. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4901. 'company_name' => $cname,
  4902. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4903. 'phone' => $ph,
  4904. ]));
  4905. $sendSmsSafe($ph, $sms);
  4906. }
  4907. foreach ($losers as $dr) {
  4908. $cname = trim((string)($dr['company_name'] ?? ''));
  4909. $ph = trim((string)($dr['phone'] ?? ''));
  4910. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4911. 'company_name' => $cname,
  4912. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4913. 'phone' => $ph,
  4914. ]));
  4915. $sendSmsSafe($ph, $sms);
  4916. }
  4917. }
  4918. /**
  4919. * 短信去重键:优先手机号,否则公司名
  4920. */
  4921. protected function notifySupplierDedupeKey(array $detailRow): string
  4922. {
  4923. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4924. if ($ph !== '') {
  4925. return 'p:' . $ph;
  4926. }
  4927. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4928. return 'c:' . $cn;
  4929. }
  4930. /**
  4931. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4932. *
  4933. * @param int[] $detailIds
  4934. */
  4935. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4936. {
  4937. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4938. if ($detailIds === []) {
  4939. return;
  4940. }
  4941. $payload = ['status_name' => $statusName];
  4942. try {
  4943. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4944. } catch (\Throwable $e) {
  4945. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4946. }
  4947. }
  4948. /**
  4949. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4950. */
  4951. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4952. {
  4953. try {
  4954. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4955. } catch (\Throwable $e) {
  4956. return;
  4957. }
  4958. if (!is_array($rows)) {
  4959. return;
  4960. }
  4961. foreach ($rows as $dr) {
  4962. if (!is_array($dr)) {
  4963. continue;
  4964. }
  4965. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4966. if ($id <= 0) {
  4967. continue;
  4968. }
  4969. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4970. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4971. try {
  4972. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4973. } catch (\Throwable $e) {
  4974. }
  4975. }
  4976. }
  4977. /**
  4978. * @param array<string, mixed> $detailRow
  4979. */
  4980. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4981. {
  4982. $am = $detailRow['amount'] ?? null;
  4983. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4984. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4985. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4986. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4987. }
  4988. /**
  4989. * @return int[]
  4990. */
  4991. protected function purchaseOrderDetail(int $scydgyId): array
  4992. {
  4993. if (!$this->isValidScydgyRowId($scydgyId)) {
  4994. return [];
  4995. }
  4996. try {
  4997. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4998. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  4999. $list = $listQuery->select();
  5000. } catch (\Throwable $e) {
  5001. return [];
  5002. }
  5003. if (!is_array($list)) {
  5004. return [];
  5005. }
  5006. $ids = [];
  5007. foreach ($list as $r) {
  5008. if (!is_array($r)) {
  5009. continue;
  5010. }
  5011. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5012. if ($pk > 0) {
  5013. $ids[] = $pk;
  5014. }
  5015. }
  5016. return array_values(array_unique($ids));
  5017. }
  5018. /**
  5019. * 获取当前登录用户信息 [id, 展示名]
  5020. */
  5021. protected function GetUseName(): array
  5022. {
  5023. $id = 0;
  5024. $name = '';
  5025. try {
  5026. if ($this->auth && $this->auth->isLogin()) {
  5027. $u = $this->auth->getUserInfo();
  5028. if (is_array($u)) {
  5029. $id = (int)($u['id'] ?? 0);
  5030. $name = trim((string)($u['nickname'] ?? ''));
  5031. if ($name === '') {
  5032. $name = trim((string)($u['username'] ?? ''));
  5033. }
  5034. }
  5035. }
  5036. } catch (\Throwable $e) {
  5037. }
  5038. if ($name === '') {
  5039. $name = '未知用户';
  5040. }
  5041. return [$id, $name];
  5042. }
  5043. /**
  5044. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5045. */
  5046. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5047. {
  5048. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5049. }
  5050. /**
  5051. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5052. *
  5053. * @param array<int, array<string, mixed>> $rows
  5054. */
  5055. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5056. {
  5057. $sidList = [];
  5058. foreach ($rows as $rw) {
  5059. if (!is_array($rw)) {
  5060. continue;
  5061. }
  5062. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5063. foreach ($rw['_order_merge_rows'] as $mr) {
  5064. $mid = (int)($mr['ID'] ?? 0);
  5065. if ($this->isValidScydgyRowId($mid)) {
  5066. $sidList[$mid] = true;
  5067. }
  5068. }
  5069. }
  5070. $id = (int)($rw['ID'] ?? 0);
  5071. if ($this->isValidScydgyRowId($id)) {
  5072. $sidList[$id] = true;
  5073. }
  5074. }
  5075. $sids = array_keys($sidList);
  5076. $issueBySid = [];
  5077. $confirmBySid = [];
  5078. $approveBySid = [];
  5079. if ($sids !== []) {
  5080. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5081. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5082. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5083. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5084. try {
  5085. $logs = Db::table('purchase_order_oper_log')
  5086. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5087. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5088. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5089. ->order('id', 'asc')
  5090. ->select();
  5091. } catch (\Throwable $e) {
  5092. $logs = [];
  5093. }
  5094. if (is_array($logs)) {
  5095. $issueSet = array_fill_keys($issueActs, true);
  5096. $confirmSet = array_fill_keys($confirmActs, true);
  5097. $approveSet = array_fill_keys($approveActs, true);
  5098. foreach ($logs as $lg) {
  5099. if (!is_array($lg)) {
  5100. continue;
  5101. }
  5102. $lg = ProcuremenOperLog::normalizeRow($lg);
  5103. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5104. if ($sid === 0) {
  5105. continue;
  5106. }
  5107. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5108. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5109. if ($t === '') {
  5110. continue;
  5111. }
  5112. if (isset($issueSet[$action])) {
  5113. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5114. $issueBySid[$sid] = $t;
  5115. }
  5116. }
  5117. if (isset($confirmSet[$action])) {
  5118. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5119. $confirmBySid[$sid] = $t;
  5120. }
  5121. }
  5122. if (isset($approveSet[$action])) {
  5123. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5124. $approveBySid[$sid] = $t;
  5125. }
  5126. }
  5127. }
  5128. }
  5129. }
  5130. foreach ($rows as &$rw) {
  5131. if (!is_array($rw)) {
  5132. continue;
  5133. }
  5134. $mergeSids = [];
  5135. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5136. foreach ($rw['_order_merge_rows'] as $mr) {
  5137. $mid = (int)($mr['ID'] ?? 0);
  5138. if ($this->isValidScydgyRowId($mid)) {
  5139. $mergeSids[] = $mid;
  5140. }
  5141. }
  5142. }
  5143. $rid = (int)($rw['ID'] ?? 0);
  5144. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5145. $mergeSids[] = $rid;
  5146. }
  5147. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5148. $issue = $pick;
  5149. $confirm = '';
  5150. $approve = '';
  5151. foreach ($mergeSids as $sid) {
  5152. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5153. $issue = $issueBySid[$sid];
  5154. }
  5155. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5156. $confirm = $confirmBySid[$sid];
  5157. }
  5158. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5159. $approve = $approveBySid[$sid];
  5160. }
  5161. }
  5162. if ($issue === '' && $pick !== '') {
  5163. $issue = $pick;
  5164. }
  5165. $rw['issue_time'] = $issue;
  5166. $rw['confirm_time'] = $confirm;
  5167. $rw['approve_time'] = $approve;
  5168. }
  5169. unset($rw);
  5170. }
  5171. /**
  5172. * 按主键取一条
  5173. */
  5174. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5175. {
  5176. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5177. return [];
  5178. }
  5179. try {
  5180. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5181. if (is_array($one)) {
  5182. return $one;
  5183. }
  5184. } catch (\Throwable $e) {
  5185. }
  5186. try {
  5187. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5188. if (is_array($one)) {
  5189. return $one;
  5190. }
  5191. } catch (\Throwable $e) {
  5192. }
  5193. return [];
  5194. }
  5195. /**
  5196. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5197. */
  5198. protected function formatProcuremenDetailTime($v): string
  5199. {
  5200. if ($v === null || $v === '') {
  5201. return '';
  5202. }
  5203. if (is_numeric($v) && (int)$v > 946684800) {
  5204. return date('Y-m-d H:i:s', (int)$v);
  5205. }
  5206. return ProcuremenTime::formatDisplayDateTime($v);
  5207. }
  5208. /**
  5209. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5210. */
  5211. protected function formatDeliveryYmd($v): string
  5212. {
  5213. if ($v === null || $v === '') {
  5214. return '';
  5215. }
  5216. $s = trim((string)$v);
  5217. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5218. return '';
  5219. }
  5220. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5221. return $m[1];
  5222. }
  5223. $ts = strtotime($s);
  5224. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5225. }
  5226. /**
  5227. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5228. */
  5229. protected function detailRowSupplierOperated(array $r): bool
  5230. {
  5231. $am = $r['amount'] ?? null;
  5232. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5233. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5234. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5235. return $okAmt || $okDel;
  5236. }
  5237. /**
  5238. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5239. */
  5240. protected function resolveDetailSupplierOperTime(array $r): string
  5241. {
  5242. if (!$this->detailRowSupplierOperated($r)) {
  5243. return '';
  5244. }
  5245. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5246. if ($t !== '') {
  5247. return $t;
  5248. }
  5249. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5250. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5251. continue;
  5252. }
  5253. $t = $this->formatProcuremenDetailTime($r[$col]);
  5254. if ($t !== '') {
  5255. return $t;
  5256. }
  5257. }
  5258. return '';
  5259. }
  5260. /**
  5261. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5262. */
  5263. protected function detailRowSupplierAccepted(array $r): bool
  5264. {
  5265. $am = $r['amount'] ?? null;
  5266. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5267. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5268. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5269. return $okAmt && $okDel;
  5270. }
  5271. /**
  5272. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5273. */
  5274. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5275. {
  5276. if ($detailCount > 0) {
  5277. return true;
  5278. }
  5279. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5280. return true;
  5281. }
  5282. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5283. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5284. return true;
  5285. }
  5286. return false;
  5287. }
  5288. /**
  5289. * 下发时间:优先 pick_time,其次首条下发明细时间
  5290. */
  5291. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5292. {
  5293. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5294. if ($issueTime !== '') {
  5295. return $issueTime;
  5296. }
  5297. foreach ($details as $dr) {
  5298. if (!is_array($dr)) {
  5299. continue;
  5300. }
  5301. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5302. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5303. $issueTime = $t;
  5304. }
  5305. }
  5306. if ($issueTime !== '') {
  5307. return $issueTime;
  5308. }
  5309. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5310. }
  5311. /**
  5312. * 直接点「完结」时间:优先操作记录 mark_complete
  5313. */
  5314. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5315. {
  5316. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5317. }
  5318. /**
  5319. * 操作记录时间(取指定 action 最近一条)
  5320. *
  5321. * @param string|array<int, string> $actions
  5322. */
  5323. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5324. {
  5325. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5326. }
  5327. /**
  5328. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5329. *
  5330. * @param array $main purchase_order 一行
  5331. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5332. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5333. */
  5334. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5335. {
  5336. $issueCnt = count($details);
  5337. $acceptCnt = 0;
  5338. $pickedName = '';
  5339. $pickedTime = '';
  5340. foreach ($details as $dr) {
  5341. if (!is_array($dr)) {
  5342. continue;
  5343. }
  5344. if ($this->detailRowSupplierAccepted($dr)) {
  5345. $acceptCnt++;
  5346. }
  5347. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5348. if ($pickedName === '') {
  5349. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5350. }
  5351. if ($pickedTime === '') {
  5352. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5353. if ($pickedTime === '') {
  5354. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5355. }
  5356. }
  5357. }
  5358. }
  5359. $hasMain = $main !== [];
  5360. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5361. if ($poTime === '') {
  5362. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5363. }
  5364. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5365. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5366. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5367. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5368. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5369. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5370. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5371. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5372. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5373. $inboundResult = '';
  5374. if ($scydgyId > 0) {
  5375. try {
  5376. $inRow = Db::table('purchase_order_inbound_score')
  5377. ->where('scydgy_id', $scydgyId)
  5378. ->field('result,updatetime,createtime')
  5379. ->find();
  5380. } catch (\Throwable $e) {
  5381. $inRow = null;
  5382. }
  5383. if (is_array($inRow) && $inRow !== []) {
  5384. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5385. if ($inboundScoreTime === '') {
  5386. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5387. }
  5388. }
  5389. }
  5390. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5391. $supplierTime = '';
  5392. if ($acceptCnt > 0) {
  5393. foreach ($details as $dr) {
  5394. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5395. continue;
  5396. }
  5397. $t = $this->resolveDetailSupplierOperTime($dr);
  5398. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5399. $supplierTime = $t;
  5400. }
  5401. }
  5402. }
  5403. $directComplete = ($mainCompleted && !$issued);
  5404. $doneTime = '';
  5405. if ($mainCompleted) {
  5406. if ($directComplete) {
  5407. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5408. }
  5409. if ($doneTime === '' && $inboundScoreTime !== '') {
  5410. $doneTime = $inboundScoreTime;
  5411. }
  5412. if ($doneTime === '') {
  5413. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5414. }
  5415. if ($doneTime === '') {
  5416. foreach ($details as $dr) {
  5417. if (!is_array($dr)) {
  5418. continue;
  5419. }
  5420. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5421. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5422. $doneTime = $t;
  5423. }
  5424. }
  5425. }
  5426. if ($doneTime === '') {
  5427. $doneTime = $poTime;
  5428. }
  5429. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5430. if ($doneTime === '' && $confirmApproveTime !== '') {
  5431. $doneTime = $confirmApproveTime;
  5432. }
  5433. }
  5434. if ($directComplete) {
  5435. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5436. $step1Done = $hasMain;
  5437. $step2Done = false;
  5438. $step3Done = false;
  5439. $step4Done = false;
  5440. $step5Done = false;
  5441. $stepInboundDone = $inboundScored;
  5442. $step6Done = $mainCompleted && $inboundScored;
  5443. } else {
  5444. $step1Done = $issued;
  5445. $step2Done = $issued;
  5446. $step3Done = $acceptCnt > 0;
  5447. $step4Done = $wflowPendingApproval;
  5448. if (!$step4Done) {
  5449. foreach ($details as $dr) {
  5450. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5451. $step4Done = true;
  5452. break;
  5453. }
  5454. }
  5455. }
  5456. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5457. $stepInboundDone = $inboundScored;
  5458. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5459. $step6Done = $mainCompleted && $inboundScored;
  5460. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5461. if ($mainCompleted && $issued) {
  5462. $step3Done = true;
  5463. $step4Done = true;
  5464. $step5Done = true;
  5465. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5466. if ($supplierTime === '') {
  5467. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5468. if ($fillT !== '') {
  5469. $supplierTime = $fillT;
  5470. }
  5471. }
  5472. if ($pickedTime === '') {
  5473. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5474. if ($fillT !== '') {
  5475. $pickedTime = $fillT;
  5476. }
  5477. }
  5478. if ($auditSelectTime === '') {
  5479. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5480. if ($fillT !== '') {
  5481. $auditSelectTime = $fillT;
  5482. }
  5483. }
  5484. if ($confirmApproveTime === '') {
  5485. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5486. if ($fillT !== '') {
  5487. $confirmApproveTime = $fillT;
  5488. }
  5489. }
  5490. }
  5491. }
  5492. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5493. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5494. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5495. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5496. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5497. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5498. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5499. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5500. $deadlineLines = [];
  5501. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5502. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5503. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5504. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5505. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5506. }
  5507. }
  5508. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5509. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5510. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5511. if ($deliveryDisp === '') {
  5512. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5513. }
  5514. if ($deliveryDisp !== '') {
  5515. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5516. }
  5517. }
  5518. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5519. $deadlineText = implode("\n", $deadlineLines);
  5520. $prefixOperTime = static function (string $t): string {
  5521. $t = trim($t);
  5522. if ($t === '' || $t === '—') {
  5523. return $t;
  5524. }
  5525. if (strpos($t, '操作时间') === 0) {
  5526. return $t;
  5527. }
  5528. return '操作时间:' . $t;
  5529. };
  5530. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5531. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5532. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5533. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5534. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5535. $steps = [
  5536. [
  5537. 'title' => '未发',
  5538. 'subtitle' => '',
  5539. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5540. 'done' => $step1Done,
  5541. ],
  5542. [
  5543. 'title' => '下发',
  5544. 'subtitle' => $deadlineText,
  5545. 'time' => $prefixOperTime($step2Time),
  5546. 'done' => $step2Done,
  5547. ],
  5548. [
  5549. 'title' => '供应商接单',
  5550. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5551. 'time' => '',
  5552. 'done' => $step3Done,
  5553. ],
  5554. [
  5555. 'title' => '待确认',
  5556. 'subtitle' => $step4Done
  5557. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5558. : ($issued ? '待选供应商' : ''),
  5559. 'time' => $prefixOperTime($step4Time),
  5560. 'done' => $step4Done,
  5561. ],
  5562. [
  5563. 'title' => '待审批',
  5564. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5565. 'time' => $prefixOperTime($step5Time),
  5566. 'done' => $step5Done,
  5567. ],
  5568. [
  5569. 'title' => '是否合格',
  5570. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5571. 'time' => $prefixOperTime($stepInboundTime),
  5572. 'done' => $stepInboundDone,
  5573. ],
  5574. [
  5575. 'title' => '已完结',
  5576. 'subtitle' => '',
  5577. 'time' => $prefixOperTime($step6Time),
  5578. 'done' => $step6Done,
  5579. ],
  5580. ];
  5581. $currentIdx = count($steps) - 1;
  5582. if ($directComplete) {
  5583. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5584. if (!$step6Done) {
  5585. foreach ($steps as $i => $s) {
  5586. if (($s['title'] ?? '') === '是否合格') {
  5587. $currentIdx = $i;
  5588. break;
  5589. }
  5590. }
  5591. }
  5592. } else {
  5593. foreach ($steps as $i => $s) {
  5594. if (!$s['done']) {
  5595. $currentIdx = $i;
  5596. break;
  5597. }
  5598. }
  5599. }
  5600. $nSteps = count($steps);
  5601. foreach ($steps as $idx => &$s) {
  5602. $s['current'] = ($idx === $currentIdx);
  5603. if ($idx === 0) {
  5604. $s['pdf_left_bg'] = '';
  5605. } else {
  5606. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5607. }
  5608. if ($idx >= $nSteps - 1) {
  5609. $s['pdf_right_bg'] = '';
  5610. } else {
  5611. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5612. }
  5613. }
  5614. unset($s);
  5615. $labelMap = [
  5616. 'CCYDH' => '订单号',
  5617. 'CYJMC' => '印件名称',
  5618. 'CCLBMMC' => '承揽部门',
  5619. 'CGYMC' => '工序名称',
  5620. 'CDW' => '单位',
  5621. 'czlyq' => '类型',
  5622. 'NGZL' => '工作量',
  5623. 'CDF' => '单价',
  5624. 'cGzzxMc' => '工作中心',
  5625. 'MBZ' => '备注',
  5626. 'This_quantity' => '本次数量',
  5627. 'ceilingPrice' => '最高限价',
  5628. ];
  5629. $orderSummary = [];
  5630. foreach ($labelMap as $key => $lab) {
  5631. if (!array_key_exists($key, $main)) {
  5632. continue;
  5633. }
  5634. $val = $main[$key];
  5635. if ($val === null) {
  5636. $val = '';
  5637. } elseif (!is_scalar($val)) {
  5638. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5639. } else {
  5640. $val = (string)$val;
  5641. }
  5642. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5643. }
  5644. $orderSummary[] = [
  5645. 'label' => '是否合格',
  5646. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5647. ];
  5648. $orderSummaryGrid = [];
  5649. $n = count($orderSummary);
  5650. for ($i = 0; $i < $n; $i += 2) {
  5651. $left = $orderSummary[$i];
  5652. $hasRight = ($i + 1) < $n;
  5653. $orderSummaryGrid[] = [
  5654. 'l1' => $left['label'],
  5655. 'v1' => $left['value'],
  5656. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5657. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5658. ];
  5659. }
  5660. return [
  5661. 'steps' => $steps,
  5662. 'orderSummary' => $orderSummary,
  5663. 'orderSummaryGrid' => $orderSummaryGrid,
  5664. 'inbound_result' => $inboundResult,
  5665. 'inbound_score_time'=> $inboundScoreTime,
  5666. 'detailRows' => $details,
  5667. ];
  5668. }
  5669. /**
  5670. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5671. *
  5672. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5673. */
  5674. protected function prepareProcuremenDetailsView(string $ids): array
  5675. {
  5676. $main = [];
  5677. try {
  5678. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5679. $main = is_array($one) ? $one : [];
  5680. } catch (\Throwable $e) {
  5681. $main = [];
  5682. }
  5683. $details = [];
  5684. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5685. if ($mergeRows === []) {
  5686. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5687. if ($mergeRows === [] && $main !== []) {
  5688. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5689. }
  5690. }
  5691. $detailSidList = [];
  5692. $anchorSid = (int)$ids;
  5693. if ($anchorSid !== 0) {
  5694. $detailSidList[$anchorSid] = true;
  5695. }
  5696. foreach ($mergeRows as $mr) {
  5697. if (!is_array($mr)) {
  5698. continue;
  5699. }
  5700. $sid = $this->extractScydgyRowId($mr);
  5701. if ($sid !== 0) {
  5702. $detailSidList[$sid] = true;
  5703. }
  5704. }
  5705. try {
  5706. if ($detailSidList !== []) {
  5707. $details = Db::table('purchase_order_detail')
  5708. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5709. ->order('id', 'asc')
  5710. ->select();
  5711. }
  5712. } catch (\Throwable $e) {
  5713. $details = [];
  5714. }
  5715. if (!is_array($details)) {
  5716. $details = [];
  5717. }
  5718. foreach ($details as &$r) {
  5719. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5720. $r['id'] = $r['ID'];
  5721. }
  5722. if (isset($r['createtime'])) {
  5723. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5724. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5725. } else {
  5726. $r['createtime_text'] = (string)$r['createtime'];
  5727. }
  5728. } else {
  5729. $r['createtime_text'] = '';
  5730. }
  5731. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5732. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5733. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5734. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5735. if (is_array($r)) {
  5736. $r = $this->maskSupplierContactFields($r);
  5737. }
  5738. }
  5739. unset($r);
  5740. $activeDetails = [];
  5741. foreach ($details as $r) {
  5742. if (is_array($r) && empty($r['is_void'])) {
  5743. $activeDetails[] = $r;
  5744. }
  5745. }
  5746. $operLogs = [];
  5747. try {
  5748. $operSidList = array_keys($detailSidList);
  5749. if ($operSidList === [] && (int)$ids !== 0) {
  5750. $operSidList = [(int)$ids];
  5751. }
  5752. if ($operSidList !== []) {
  5753. $operLogs = Db::table('purchase_order_oper_log')
  5754. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5755. ->order('id', 'asc')
  5756. ->select();
  5757. }
  5758. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5759. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5760. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5761. if ($poId > 0) {
  5762. $operLogs = Db::table('purchase_order_oper_log')
  5763. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5764. ->order('id', 'asc')
  5765. ->select();
  5766. }
  5767. }
  5768. } catch (\Throwable $e) {
  5769. $operLogs = [];
  5770. }
  5771. if (!is_array($operLogs)) {
  5772. $operLogs = [];
  5773. }
  5774. $operLogsRaw = $operLogs;
  5775. $processNameBySid = [];
  5776. foreach ($mergeRows as $mr) {
  5777. if (!is_array($mr)) {
  5778. continue;
  5779. }
  5780. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5781. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5782. if ($psid !== 0 && $gymc !== '') {
  5783. $processNameBySid[$psid] = $gymc;
  5784. }
  5785. }
  5786. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5787. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5788. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5789. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5790. if ($ccydh === '') {
  5791. foreach ($details as $r) {
  5792. if (!is_array($r)) {
  5793. continue;
  5794. }
  5795. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5796. if ($ccydh !== '') {
  5797. break;
  5798. }
  5799. }
  5800. }
  5801. $this->view->assign('ccydh', $ccydh);
  5802. $this->view->assign('steps', $bundle['steps']);
  5803. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5804. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5805. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5806. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5807. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5808. $this->view->assign('processCount', count($mergeRows));
  5809. $this->view->assign('detailRows', $details);
  5810. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5811. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5812. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5813. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5814. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5815. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5816. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5817. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5818. $this->view->assign('operLogs', $operLogs);
  5819. $sg = $quoteView['supplier_groups'] ?? [];
  5820. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5821. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5822. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5823. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5824. return [
  5825. 'ok' => $main !== [] || $details !== [],
  5826. 'ccydh' => $ccydh,
  5827. ];
  5828. }
  5829. /**
  5830. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5831. */
  5832. public function details()
  5833. {
  5834. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5835. if (is_array($ids)) {
  5836. $ids = isset($ids[0]) ? $ids[0] : '';
  5837. }
  5838. $ids = trim((string)$ids);
  5839. if ($ids === '') {
  5840. $this->error(__('Invalid parameters'));
  5841. }
  5842. $this->assertManualOrderDetailsViewable((int)$ids);
  5843. $this->prepareProcuremenDetailsView($ids);
  5844. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5845. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5846. $this->view->engine->layout(false);
  5847. try {
  5848. return $this->view->fetch('procuremen/details_dialog_shell');
  5849. } finally {
  5850. if ($restoreLayout) {
  5851. $this->view->engine->layout($restoreLayout);
  5852. }
  5853. }
  5854. }
  5855. /**
  5856. * 解析合并审核工序行(订单号须一致,且均未协助)
  5857. *
  5858. * @return array<int, array<string, mixed>>
  5859. */
  5860. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5861. {
  5862. $primary = json_decode($rowJson, true);
  5863. if (!is_array($primary)) {
  5864. $this->error(__('Invalid parameters'));
  5865. }
  5866. $merge = json_decode($mergeRowsJson, true);
  5867. if (!is_array($merge) || $merge === []) {
  5868. $merge = [$primary];
  5869. }
  5870. $seen = [];
  5871. $out = [];
  5872. foreach ($merge as $r) {
  5873. if (!is_array($r)) {
  5874. continue;
  5875. }
  5876. $id = $this->extractScydgyRowId($r);
  5877. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5878. continue;
  5879. }
  5880. $seen[$id] = true;
  5881. $out[] = $r;
  5882. }
  5883. if ($out === []) {
  5884. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5885. }
  5886. $ccydh = null;
  5887. foreach ($out as $r) {
  5888. $dh = trim((string)($r['CCYDH'] ?? ''));
  5889. if ($ccydh === null) {
  5890. $ccydh = $dh;
  5891. } elseif ($dh !== $ccydh) {
  5892. $this->error('合并审核要求所选行的订单号一致');
  5893. }
  5894. }
  5895. $ids = [];
  5896. foreach ($out as $r) {
  5897. $id = $this->extractScydgyRowId($r);
  5898. if ($this->isValidScydgyRowId($id)) {
  5899. $ids[$id] = true;
  5900. }
  5901. }
  5902. $poBySid = [];
  5903. $detCntBySid = [];
  5904. if ($ids !== []) {
  5905. $idList = array_keys($ids);
  5906. try {
  5907. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5908. if (is_array($poList)) {
  5909. foreach ($poList as $po) {
  5910. if (!is_array($po)) {
  5911. continue;
  5912. }
  5913. $sid = (int)($po['scydgy_id'] ?? 0);
  5914. if ($this->isValidScydgyRowId($sid)) {
  5915. $poBySid[$sid] = $po;
  5916. }
  5917. }
  5918. }
  5919. } catch (\Throwable $e) {
  5920. }
  5921. try {
  5922. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5923. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5924. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5925. if (is_array($detRows)) {
  5926. foreach ($detRows as $dr) {
  5927. if (!is_array($dr)) {
  5928. continue;
  5929. }
  5930. $sid = (int)($dr['scydgy_id'] ?? 0);
  5931. if ($this->isValidScydgyRowId($sid)) {
  5932. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5933. }
  5934. }
  5935. }
  5936. } catch (\Throwable $e) {
  5937. }
  5938. }
  5939. foreach ($out as $r) {
  5940. $id = $this->extractScydgyRowId($r);
  5941. if (!$this->isValidScydgyRowId($id)) {
  5942. continue;
  5943. }
  5944. $po = $poBySid[$id] ?? null;
  5945. if (!is_array($po)) {
  5946. continue;
  5947. }
  5948. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5949. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5950. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5951. }
  5952. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5953. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5954. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5955. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5956. }
  5957. }
  5958. return $out;
  5959. }
  5960. /**
  5961. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5962. */
  5963. protected function maskSupplierContactFields(array $item): array
  5964. {
  5965. if (array_key_exists('email', $item)) {
  5966. $item['email'] = mask_email((string)$item['email']);
  5967. }
  5968. if (array_key_exists('phone', $item)) {
  5969. $item['phone'] = mask_phone((string)$item['phone']);
  5970. }
  5971. return $item;
  5972. }
  5973. /**
  5974. * @param array<int, array<string, mixed>> $list
  5975. * @return array<int, array<string, mixed>>
  5976. */
  5977. protected function maskSupplierContactList(array $list): array
  5978. {
  5979. $out = [];
  5980. foreach ($list as $item) {
  5981. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5982. }
  5983. return $out;
  5984. }
  5985. /**
  5986. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5987. *
  5988. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5989. * @return array<string, string>|null
  5990. */
  5991. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  5992. {
  5993. if (!is_array($row)) {
  5994. return null;
  5995. }
  5996. $norm = [];
  5997. foreach ($row as $k => $v) {
  5998. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  5999. }
  6000. $row = $norm;
  6001. $st = $row['status'] ?? '';
  6002. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6003. return null;
  6004. }
  6005. $companyName = '';
  6006. foreach (['company_name', 'name'] as $nk) {
  6007. if (!empty($row[$nk])) {
  6008. $companyName = trim((string)$row[$nk]);
  6009. break;
  6010. }
  6011. }
  6012. if ($companyName === '') {
  6013. return null;
  6014. }
  6015. $username = '';
  6016. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6017. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6018. $username = trim((string)$row[$uk]);
  6019. break;
  6020. }
  6021. }
  6022. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6023. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6024. if ($phone === '' && isset($row['account'])) {
  6025. $phone = trim((string)$row['account']);
  6026. }
  6027. if ($phone === '' && isset($row['mobile'])) {
  6028. $phone = trim((string)$row['mobile']);
  6029. }
  6030. if ($requireContactChannels && $email === '' && $phone === '') {
  6031. return null;
  6032. }
  6033. $category = '';
  6034. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6035. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6036. $category = trim((string)$row[$ck]);
  6037. break;
  6038. }
  6039. }
  6040. return [
  6041. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6042. 'name' => $companyName,
  6043. 'company_name' => $companyName,
  6044. 'username' => $username,
  6045. 'email' => $email,
  6046. 'phone' => $phone,
  6047. 'category' => $category,
  6048. 'company_type' => $category,
  6049. ];
  6050. }
  6051. /**
  6052. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6053. */
  6054. protected function resolveCustomerContactById(string $id): ?array
  6055. {
  6056. $id = trim($id);
  6057. if ($id === '' || !ctype_digit($id)) {
  6058. return null;
  6059. }
  6060. try {
  6061. $row = Db::table('customer')->where('id', (int)$id)->find();
  6062. } catch (\Throwable $e) {
  6063. return null;
  6064. }
  6065. return $this->buildCustomerContactPayloadFromRow($row);
  6066. }
  6067. /**
  6068. * 按供应商名称解析联系信息(兼容旧提交数据)
  6069. *
  6070. * @param bool $requireContactChannels true 时须有邮箱或手机
  6071. */
  6072. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6073. {
  6074. $name = trim($name);
  6075. if ($name === '') {
  6076. return null;
  6077. }
  6078. try {
  6079. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6080. $row = Db::table('customer')
  6081. ->where('company_name', $name)
  6082. ->order('id', 'desc')
  6083. ->find();
  6084. } catch (\Throwable $e) {
  6085. return null;
  6086. }
  6087. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6088. }
  6089. /**
  6090. * 规范化下发/确认时勾选的供应商
  6091. *
  6092. * @param array<int, mixed> $companies
  6093. * @return array<int, array<string, string>>
  6094. */
  6095. protected function normalizePickCompanies(array $companies): array
  6096. {
  6097. $out = [];
  6098. foreach ($companies as $c) {
  6099. if (!is_array($c)) {
  6100. continue;
  6101. }
  6102. $resolved = null;
  6103. $cid = trim((string)($c['id'] ?? ''));
  6104. if ($cid !== '') {
  6105. $resolved = $this->resolveCustomerContactById($cid);
  6106. }
  6107. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6108. if ($resolved === null && $name !== '') {
  6109. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6110. }
  6111. if ($resolved === null) {
  6112. continue;
  6113. }
  6114. $out[] = $resolved;
  6115. }
  6116. return $out;
  6117. }
  6118. /**
  6119. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6120. *
  6121. * @param array<int, array<string, mixed>> $pool
  6122. * @return array<int, array<string, mixed>>
  6123. */
  6124. protected function collapseProcuremenPoolByOrder(array $pool): array
  6125. {
  6126. if ($pool === []) {
  6127. return [];
  6128. }
  6129. $groups = [];
  6130. foreach ($pool as $row) {
  6131. if (!is_array($row)) {
  6132. continue;
  6133. }
  6134. $dh = trim((string)($row['CCYDH'] ?? ''));
  6135. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6136. if (!isset($groups[$key])) {
  6137. $groups[$key] = [];
  6138. }
  6139. $groups[$key][] = $row;
  6140. }
  6141. $out = [];
  6142. foreach ($groups as $ccydh => $rows) {
  6143. if ($rows === []) {
  6144. continue;
  6145. }
  6146. usort($rows, function ($a, $b) {
  6147. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6148. });
  6149. $head = $rows[0];
  6150. $gymcList = [];
  6151. foreach ($rows as $r) {
  6152. $g = trim((string)($r['CGYMC'] ?? ''));
  6153. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6154. $gymcList[] = $g;
  6155. }
  6156. }
  6157. $merged = $head;
  6158. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6159. $merged['process_count'] = count($rows);
  6160. $merged['_order_merge_rows'] = $rows;
  6161. $qtyList = [];
  6162. $priceList = [];
  6163. foreach ($rows as $r) {
  6164. if (!is_array($r)) {
  6165. continue;
  6166. }
  6167. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6168. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6169. }
  6170. if (count($rows) > 1) {
  6171. $merged['CGYMC'] = implode('、', $gymcList);
  6172. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6173. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6174. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6175. } else {
  6176. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6177. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6178. }
  6179. // 已选供应商:取合并行中首个非空 pick_company_name
  6180. $pickedName = '';
  6181. foreach ($rows as $r) {
  6182. if (!is_array($r)) {
  6183. continue;
  6184. }
  6185. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6186. if ($pn !== '') {
  6187. $pickedName = $pn;
  6188. break;
  6189. }
  6190. }
  6191. if ($pickedName !== '') {
  6192. $merged['pick_company_name'] = $pickedName;
  6193. $merged['picked_supplier_name'] = $pickedName;
  6194. }
  6195. $mergedPickTime = '';
  6196. foreach ($rows as $r) {
  6197. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6198. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6199. $mergedPickTime = $t;
  6200. }
  6201. }
  6202. if ($mergedPickTime !== '') {
  6203. $merged['pick_time'] = $mergedPickTime;
  6204. }
  6205. $out[] = $merged;
  6206. }
  6207. usort($out, function ($a, $b) {
  6208. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6209. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6210. if ($ta === $tb) {
  6211. $ida = (int)($a['purchase_order_id'] ?? 0);
  6212. $idb = (int)($b['purchase_order_id'] ?? 0);
  6213. if ($ida !== $idb) {
  6214. return $idb <=> $ida;
  6215. }
  6216. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6217. }
  6218. if ($ta === '') {
  6219. return 1;
  6220. }
  6221. if ($tb === '') {
  6222. return -1;
  6223. }
  6224. return strcmp($tb, $ta);
  6225. });
  6226. return $out;
  6227. }
  6228. /**
  6229. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6230. *
  6231. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6232. */
  6233. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6234. {
  6235. $scydgyId = trim($scydgyId);
  6236. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6237. if ($scydgyId === '') {
  6238. return $empty;
  6239. }
  6240. try {
  6241. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6242. } catch (\Throwable $e) {
  6243. $anchor = null;
  6244. }
  6245. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6246. return $empty;
  6247. }
  6248. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6249. if ($ccydh === '') {
  6250. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6251. }
  6252. try {
  6253. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6254. } catch (\Throwable $e) {
  6255. $pos = [$anchor];
  6256. }
  6257. if (!is_array($pos) || $pos === []) {
  6258. $pos = [$anchor];
  6259. }
  6260. return [
  6261. 'ccydh' => $ccydh,
  6262. 'pos' => $pos,
  6263. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6264. ];
  6265. }
  6266. /**
  6267. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6268. */
  6269. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6270. {
  6271. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6272. return false;
  6273. }
  6274. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6275. return false;
  6276. }
  6277. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6278. return true;
  6279. }
  6280. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6281. $sid = (int)($po['scydgy_id'] ?? 0);
  6282. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6283. }
  6284. return false;
  6285. }
  6286. /**
  6287. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6288. *
  6289. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6290. */
  6291. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6292. {
  6293. $scydgyId = trim($scydgyId);
  6294. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6295. if ($scydgyId === '') {
  6296. return $empty;
  6297. }
  6298. try {
  6299. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6300. } catch (\Throwable $e) {
  6301. $anchor = null;
  6302. }
  6303. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6304. return $empty;
  6305. }
  6306. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6307. if ($ccydh === '') {
  6308. return [
  6309. 'ccydh' => '',
  6310. 'pos' => [$anchor],
  6311. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6312. ];
  6313. }
  6314. try {
  6315. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6316. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6317. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6318. } catch (\Throwable $e) {
  6319. $pos = [$anchor];
  6320. }
  6321. if (!is_array($pos) || $pos === []) {
  6322. $pos = [$anchor];
  6323. }
  6324. $pos = array_values(array_filter($pos, function ($po) {
  6325. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6326. }));
  6327. if ($pos === []) {
  6328. $pos = [$anchor];
  6329. }
  6330. return [
  6331. 'ccydh' => $ccydh,
  6332. 'pos' => $pos,
  6333. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6334. ];
  6335. }
  6336. /**
  6337. * @param array<int, array<string, mixed>> $purchaseOrders
  6338. * @return array<int, array<string, mixed>>
  6339. */
  6340. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6341. {
  6342. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6343. $byId = [];
  6344. foreach ($pool as $r) {
  6345. if (!is_array($r)) {
  6346. continue;
  6347. }
  6348. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6349. if ($this->isValidScydgyRowId($sid)) {
  6350. $byId[$sid] = $r;
  6351. }
  6352. }
  6353. $out = [];
  6354. foreach ($purchaseOrders as $po) {
  6355. if (!is_array($po)) {
  6356. continue;
  6357. }
  6358. $sid = (int)($po['scydgy_id'] ?? 0);
  6359. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6360. $out[] = $byId[$sid];
  6361. }
  6362. }
  6363. return $out;
  6364. }
  6365. /**
  6366. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6367. *
  6368. * @return array<int, array<string, mixed>>
  6369. */
  6370. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6371. {
  6372. $scydgyId = trim($scydgyId);
  6373. if ($scydgyId === '') {
  6374. return [];
  6375. }
  6376. try {
  6377. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6378. } catch (\Throwable $e) {
  6379. $anchor = null;
  6380. }
  6381. if (!is_array($anchor)) {
  6382. return [];
  6383. }
  6384. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6385. return [];
  6386. }
  6387. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6388. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6389. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6390. try {
  6391. $q = Db::table('purchase_order');
  6392. if ($ccydh !== '') {
  6393. $q->where('CCYDH', $ccydh);
  6394. } else {
  6395. $q->where('scydgy_id', $scydgyId);
  6396. }
  6397. if ($isValidPick) {
  6398. $q->where('pick_time', $pickTime);
  6399. }
  6400. $pos = $q->order('scydgy_id', 'asc')->select();
  6401. } catch (\Throwable $e) {
  6402. $pos = [$anchor];
  6403. }
  6404. if (!is_array($pos) || $pos === []) {
  6405. $pos = [$anchor];
  6406. }
  6407. $pos = array_values(array_filter($pos, function ($po) {
  6408. if (!is_array($po)) {
  6409. return false;
  6410. }
  6411. $mr = $po['mod_rq'] ?? null;
  6412. if ($mr === null || $mr === '') {
  6413. return true;
  6414. }
  6415. $mrs = trim((string)$mr);
  6416. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6417. }));
  6418. if ($pos === []) {
  6419. $pos = [$anchor];
  6420. }
  6421. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6422. if ($rows === []) {
  6423. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6424. }
  6425. return $rows;
  6426. }
  6427. /**
  6428. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6429. *
  6430. * @param array<int, array<string, mixed>> $mergeRows
  6431. * @return array<int, array<string, mixed>>
  6432. */
  6433. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6434. {
  6435. $list = array_values($mergeRows);
  6436. $n = count($list);
  6437. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6438. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6439. $mergeSame = $n > 1 && $orderKey0 !== '';
  6440. if ($mergeSame) {
  6441. foreach ($list as $rr) {
  6442. if (!is_array($rr)) {
  6443. $mergeSame = false;
  6444. break;
  6445. }
  6446. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6447. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6448. $mergeSame = false;
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. $out = [];
  6454. foreach ($list as $idx => $r) {
  6455. if (!is_array($r)) {
  6456. continue;
  6457. }
  6458. $qty = $this->resolveProcuremenThisQuantity($r);
  6459. $price = $this->resolveProcuremenCeilingPrice($r);
  6460. $sid = $this->extractScydgyRowId($r);
  6461. $out[] = [
  6462. 'seq' => $idx + 1,
  6463. 'scydgy_id' => $sid,
  6464. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6465. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6466. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6467. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6468. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6469. 'NGZL' => $r['NGZL'] ?? '',
  6470. 'This_quantity' => $qty,
  6471. 'ceilingPrice' => $price,
  6472. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6473. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6474. 'show_order_cells' => !$mergeSame || $idx === 0,
  6475. 'order_rowspan' => $mergeSame ? $n : 1,
  6476. ];
  6477. }
  6478. return $out;
  6479. }
  6480. /**
  6481. * 解析金额/数量(去千分位等非数字字符)
  6482. */
  6483. protected function parseProcuremenMoneyNumber($value): ?float
  6484. {
  6485. if ($value === null || $value === '') {
  6486. return null;
  6487. }
  6488. if (is_numeric($value)) {
  6489. return (float)$value;
  6490. }
  6491. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6492. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6493. }
  6494. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6495. {
  6496. if ($amount === null) {
  6497. return '';
  6498. }
  6499. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6500. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6501. return $s === '' ? '0' : $s;
  6502. }
  6503. /**
  6504. * 列表/详情展示:工作量为 0 时显示空
  6505. */
  6506. protected function formatProcuremenWorkloadDisplay($value): string
  6507. {
  6508. if ($value === null || $value === '') {
  6509. return '';
  6510. }
  6511. $s = trim((string)$value);
  6512. if ($s === '') {
  6513. return '';
  6514. }
  6515. if (is_numeric($s) && (float)$s == 0) {
  6516. return '';
  6517. }
  6518. return $s;
  6519. }
  6520. /**
  6521. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6522. */
  6523. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6524. {
  6525. foreach ($details as $d) {
  6526. if (!is_array($d)) {
  6527. continue;
  6528. }
  6529. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6530. $cn = trim((string)($d['company_name'] ?? ''));
  6531. if ($cn !== '') {
  6532. return $cn;
  6533. }
  6534. }
  6535. }
  6536. return trim((string)($main['pick_company_name'] ?? ''));
  6537. }
  6538. /**
  6539. * 详情报价小计:单价 × 本工序本次数量
  6540. */
  6541. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6542. {
  6543. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6544. if ($unit === null) {
  6545. return null;
  6546. }
  6547. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6548. if ($qty === null || $qty <= 0) {
  6549. return null;
  6550. }
  6551. return $unit * $qty;
  6552. }
  6553. /**
  6554. * 详情页:工序小计 + 供应商分组报价与总计
  6555. *
  6556. * @param array<int, array<string, mixed>> $mergeRows
  6557. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6558. * @return array{
  6559. * process_rows: array,
  6560. * supplier_groups: array,
  6561. * order_total_text: string,
  6562. * order_total_has: bool,
  6563. * selected_company: string
  6564. * }
  6565. */
  6566. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6567. {
  6568. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6569. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6570. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6571. || ((int)($main['manual_pick'] ?? 0) === 1);
  6572. $qtyBySid = [];
  6573. $gymcBySid = [];
  6574. $orderedSids = [];
  6575. foreach ($mergeRows as $mr) {
  6576. if (!is_array($mr)) {
  6577. continue;
  6578. }
  6579. $sid = $this->extractScydgyRowId($mr);
  6580. if ($this->isValidScydgyRowId($sid)) {
  6581. $orderedSids[] = $sid;
  6582. }
  6583. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6584. if ($qty === '') {
  6585. $qty = trim((string)($mr['NGZL'] ?? ''));
  6586. }
  6587. $qtyBySid[$sid] = $qty;
  6588. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6589. }
  6590. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6591. $detailByCompanySid = [];
  6592. foreach ($details as $d) {
  6593. if (!is_array($d)) {
  6594. continue;
  6595. }
  6596. $cn = trim((string)($d['company_name'] ?? ''));
  6597. $sid = (int)($d['scydgy_id'] ?? 0);
  6598. if ($cn === '' || $sid === 0) {
  6599. continue;
  6600. }
  6601. if (!isset($detailByCompanySid[$cn])) {
  6602. $detailByCompanySid[$cn] = [];
  6603. }
  6604. $detailByCompanySid[$cn][$sid] = $d;
  6605. }
  6606. $supplierGroups = [];
  6607. foreach ($detailByCompanySid as $cn => $bySid) {
  6608. $lines = [];
  6609. $groupTotal = 0.0;
  6610. $groupHas = false;
  6611. $groupVoid = true;
  6612. $usedSids = [];
  6613. $appendLine = function (int $sid, array $d) use (
  6614. &$lines,
  6615. &$groupTotal,
  6616. &$groupHas,
  6617. &$groupVoid,
  6618. $qtyBySid,
  6619. $gymcBySid,
  6620. $quoteVisible
  6621. ) {
  6622. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6623. if (!$isVoid) {
  6624. $groupVoid = false;
  6625. }
  6626. $qtyStr = $qtyBySid[$sid] ?? '';
  6627. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6628. $am = trim((string)($d['amount'] ?? ''));
  6629. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6630. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6631. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6632. $sub = null;
  6633. if (!$isVoid && $amountNum !== null) {
  6634. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6635. }
  6636. $ct = $this->resolveDetailSupplierOperTime($d);
  6637. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6638. $leadFilled = ($leadDays !== null);
  6639. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6640. $line = [
  6641. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6642. 'amount' => $am,
  6643. 'unit_price_text' => $amountFilled
  6644. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6645. : '未填写',
  6646. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6647. 'delivery_ymd' => $deliveryYmd,
  6648. 'amount_filled' => $amountFilled,
  6649. 'delivery_filled' => $deliveryFilled,
  6650. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6651. 'lead_days' => $leadFilled ? $leadDays : '',
  6652. 'lead_days_filled'=> $leadFilled,
  6653. 'lead_days_show' => $leadText,
  6654. 'lead_days_text' => $leadText,
  6655. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6656. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6657. 'is_void' => $isVoid,
  6658. 'oper_time_text' => $ct,
  6659. ];
  6660. if (!$quoteVisible && !$isVoid) {
  6661. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6662. } elseif ($sub !== null) {
  6663. $groupTotal += $sub;
  6664. $groupHas = true;
  6665. }
  6666. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6667. };
  6668. foreach ($orderedSids as $sid) {
  6669. if (!isset($bySid[$sid])) {
  6670. continue;
  6671. }
  6672. $usedSids[$sid] = true;
  6673. $appendLine($sid, $bySid[$sid]);
  6674. }
  6675. foreach ($bySid as $sid => $d) {
  6676. if (isset($usedSids[$sid])) {
  6677. continue;
  6678. }
  6679. $appendLine((int)$sid, $d);
  6680. }
  6681. $firstDetail = null;
  6682. foreach ($bySid as $d) {
  6683. if (is_array($d)) {
  6684. $firstDetail = $d;
  6685. break;
  6686. }
  6687. }
  6688. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6689. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6690. if ($username === '' && $ph !== '') {
  6691. $username = $this->resolveCustomerContactName($ph, $cn);
  6692. }
  6693. $remark = '';
  6694. foreach ($bySid as $d) {
  6695. if (!is_array($d)) {
  6696. continue;
  6697. }
  6698. $rm = '';
  6699. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6700. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6701. $rm = trim((string)$d[$rk]);
  6702. break;
  6703. }
  6704. }
  6705. if ($rm !== '') {
  6706. $remark = $rm;
  6707. break;
  6708. }
  6709. }
  6710. $lineCount = count($lines);
  6711. $hasRemark = $lineCount > 0;
  6712. $supplierGroup = [
  6713. 'company_name' => $cn,
  6714. 'username' => $username,
  6715. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6716. 'phone' => $ph,
  6717. 'remark' => $remark,
  6718. 'has_remark' => $hasRemark,
  6719. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6720. 'is_void' => $groupVoid,
  6721. 'lines' => $lines,
  6722. 'line_count' => $lineCount,
  6723. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6724. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6725. 'has_total' => $lineCount > 0,
  6726. ];
  6727. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6728. $supplierGroups[] = $supplierGroup;
  6729. }
  6730. usort($supplierGroups, function ($a, $b) {
  6731. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6732. return ($a['is_void'] ?? false) ? 1 : -1;
  6733. }
  6734. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6735. return ($a['is_selected'] ?? false) ? -1 : 1;
  6736. }
  6737. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6738. });
  6739. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6740. return [
  6741. 'process_rows' => $processRows,
  6742. 'supplier_groups' => $supplierGroups,
  6743. 'order_total_text' => '',
  6744. 'order_total_has' => false,
  6745. 'selected_company' => $selectedCompany,
  6746. ];
  6747. }
  6748. /**
  6749. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6750. */
  6751. protected function buildProcessLinesPlain(array $mergeRows): string
  6752. {
  6753. $lines = [];
  6754. $i = 1;
  6755. foreach ($mergeRows as $r) {
  6756. if (!is_array($r)) {
  6757. continue;
  6758. }
  6759. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6760. $dw = trim((string)($r['CDW'] ?? ''));
  6761. $gzl = trim((string)($r['NGZL'] ?? ''));
  6762. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6763. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6764. if ($dw !== '') {
  6765. $parts[] = '单位:' . $dw;
  6766. }
  6767. if ($gzl !== '') {
  6768. $parts[] = '工作量:' . $gzl;
  6769. }
  6770. if ($qty !== '') {
  6771. $parts[] = '本次数量:' . $qty;
  6772. }
  6773. $lines[] = implode(' ', $parts);
  6774. $i++;
  6775. }
  6776. return implode("\n", $lines);
  6777. }
  6778. /**
  6779. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6780. *
  6781. * @return array<string, string>
  6782. */
  6783. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6784. {
  6785. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6786. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6787. }
  6788. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6789. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6790. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6791. $cyjmc = '';
  6792. foreach ($mergeRows as $mr) {
  6793. if (!is_array($mr)) {
  6794. continue;
  6795. }
  6796. if ($ccydh === '') {
  6797. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6798. }
  6799. if ($cyjmc === '') {
  6800. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6801. }
  6802. }
  6803. if ($pos !== []) {
  6804. $firstPo = $pos[0];
  6805. if (is_array($firstPo)) {
  6806. if ($ccydh === '') {
  6807. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6808. }
  6809. if ($cyjmc === '') {
  6810. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6811. }
  6812. }
  6813. }
  6814. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6815. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6816. if (is_array($any)) {
  6817. if ($ccydh === '') {
  6818. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6819. }
  6820. if ($cyjmc === '') {
  6821. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6822. }
  6823. }
  6824. }
  6825. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6826. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6827. $cgymc = '';
  6828. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6829. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6830. }
  6831. return [
  6832. 'ccydh' => $ccydh,
  6833. 'cyjmc' => $cyjmc,
  6834. 'cgymc' => $cgymc,
  6835. 'process_lines' => $processLines,
  6836. 'process_lines_html' => '',
  6837. ];
  6838. }
  6839. /**
  6840. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6841. */
  6842. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6843. {
  6844. $lines = [];
  6845. if ($ccydh !== '') {
  6846. $lines[] = '订单号:' . $ccydh;
  6847. }
  6848. if ($cyjmc !== '') {
  6849. $lines[] = '印件名称:' . $cyjmc;
  6850. }
  6851. if ($processPlain !== '') {
  6852. $lines[] = $processPlain;
  6853. }
  6854. return implode("\n", $lines);
  6855. }
  6856. /**
  6857. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6858. *
  6859. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6860. */
  6861. protected function buildPlatformLinksPlain(array $detailLinks): string
  6862. {
  6863. $lines = [];
  6864. $i = 1;
  6865. foreach ($detailLinks as $lk) {
  6866. if (!is_array($lk)) {
  6867. continue;
  6868. }
  6869. $url = trim((string)($lk['url'] ?? ''));
  6870. if ($url === '') {
  6871. continue;
  6872. }
  6873. $label = trim((string)($lk['cgymc'] ?? ''));
  6874. if ($label === '') {
  6875. $label = '工序' . $i;
  6876. }
  6877. $lines[] = $label . ':' . $url;
  6878. $i++;
  6879. }
  6880. return implode("\n", $lines);
  6881. }
  6882. /**
  6883. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6884. *
  6885. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6886. */
  6887. protected function buildPlatformLinksHtml(array $detailLinks): string
  6888. {
  6889. $parts = [];
  6890. $i = 1;
  6891. foreach ($detailLinks as $lk) {
  6892. if (!is_array($lk)) {
  6893. continue;
  6894. }
  6895. $url = trim((string)($lk['url'] ?? ''));
  6896. if ($url === '') {
  6897. continue;
  6898. }
  6899. $label = trim((string)($lk['cgymc'] ?? ''));
  6900. if ($label === '') {
  6901. $label = '工序' . $i;
  6902. }
  6903. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6904. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6905. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6906. $i++;
  6907. }
  6908. return implode("<br>\n", $parts);
  6909. }
  6910. /**
  6911. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6912. *
  6913. * @return array<string, mixed>
  6914. */
  6915. protected function loadMailerConfig(): array
  6916. {
  6917. try {
  6918. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6919. } catch (\Throwable $e) {
  6920. $cfg = [];
  6921. }
  6922. return is_array($cfg) ? $cfg : [];
  6923. }
  6924. protected function loadNotifyTemplateRow(string $scene): ?array
  6925. {
  6926. try {
  6927. $row = Db::table('purchase_sms_template')
  6928. ->where('scene', $scene)
  6929. ->where(function ($q) {
  6930. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6931. })
  6932. ->order('id', 'asc')
  6933. ->find();
  6934. } catch (\Throwable $e) {
  6935. return null;
  6936. }
  6937. if (!is_array($row) || $row === []) {
  6938. return null;
  6939. }
  6940. return [
  6941. 'title' => trim((string)($row['title'] ?? '')),
  6942. 'content' => trim((string)($row['content'] ?? '')),
  6943. ];
  6944. }
  6945. /**
  6946. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6947. */
  6948. protected function buildProcessLinesHtml(array $mergeRows): string
  6949. {
  6950. if (count($mergeRows) <= 1) {
  6951. $r = $mergeRows[0] ?? [];
  6952. if (!is_array($r)) {
  6953. return '';
  6954. }
  6955. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6956. $dw = trim((string)($r['CDW'] ?? ''));
  6957. $gzl = trim((string)($r['NGZL'] ?? ''));
  6958. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6959. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6960. if ($dw !== '') {
  6961. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6962. }
  6963. if ($gzl !== '') {
  6964. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6965. }
  6966. if ($qty !== '') {
  6967. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6968. }
  6969. return $html;
  6970. }
  6971. $rows = '';
  6972. $i = 1;
  6973. foreach ($mergeRows as $r) {
  6974. if (!is_array($r)) {
  6975. continue;
  6976. }
  6977. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6978. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6979. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6980. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6981. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6982. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6983. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6984. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6985. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6986. $i++;
  6987. }
  6988. if ($rows === '') {
  6989. return '';
  6990. }
  6991. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  6992. . '<thead><tr style="background:#f5f5f5;">'
  6993. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  6994. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  6995. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  6996. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  6997. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  6998. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  6999. }
  7000. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7001. {
  7002. $sysRq = trim($sysRq);
  7003. if ($sysRq === '') {
  7004. if ($required) {
  7005. $this->error('请选择招标截止日期');
  7006. }
  7007. return '';
  7008. }
  7009. $ts = strtotime($sysRq);
  7010. if ($ts === false || $ts <= 0) {
  7011. $this->error('招标截止日期格式无效');
  7012. }
  7013. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7014. if (!$allowPast) {
  7015. $ymd = date('Y-m-d', $ts);
  7016. if ($ymd < date('Y-m-d')) {
  7017. $this->error('招标截止日期不能早于今天');
  7018. }
  7019. if ($ts <= time()) {
  7020. $this->error('招标截止时间不能早于当前时间');
  7021. }
  7022. }
  7023. return date('Y-m-d H:i:s', $ts);
  7024. }
  7025. /**
  7026. * 确保 purchase_order.czlyq(类型)存在
  7027. */
  7028. protected function ensurePurchaseOrderCzlyqColumn(): void
  7029. {
  7030. static $done = false;
  7031. if ($done) {
  7032. return;
  7033. }
  7034. $done = true;
  7035. try {
  7036. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7037. if (empty($cols)) {
  7038. Db::execute(
  7039. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7040. );
  7041. }
  7042. } catch (\Throwable $e) {
  7043. // ignore
  7044. }
  7045. }
  7046. /**
  7047. * 确保 purchase_order.delivery_deadline 存在
  7048. */
  7049. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7050. {
  7051. static $done = false;
  7052. if ($done) {
  7053. return;
  7054. }
  7055. $done = true;
  7056. try {
  7057. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7058. if (empty($cols)) {
  7059. Db::execute(
  7060. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7061. );
  7062. }
  7063. } catch (\Throwable $e) {
  7064. // ignore
  7065. }
  7066. }
  7067. /**
  7068. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7069. */
  7070. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7071. {
  7072. static $done = false;
  7073. if ($done) {
  7074. return;
  7075. }
  7076. $done = true;
  7077. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7078. $adds = [
  7079. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7080. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7081. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7082. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7083. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7084. ];
  7085. $changed = false;
  7086. foreach ($adds as $col => $ddl) {
  7087. try {
  7088. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7089. if (!is_array($cols) || $cols === []) {
  7090. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7091. $changed = true;
  7092. }
  7093. } catch (\Throwable $e) {
  7094. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7095. }
  7096. }
  7097. if ($changed) {
  7098. $this->clearPurchaseOrderTableFieldsCache();
  7099. }
  7100. }
  7101. /**
  7102. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7103. */
  7104. protected function clearPurchaseOrderTableFieldsCache(): void
  7105. {
  7106. try {
  7107. $db = (string)Config::get('database.database');
  7108. $key = $db . '.purchase_order';
  7109. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7110. $ref->setAccessible(true);
  7111. $info = $ref->getValue();
  7112. if (is_array($info) && isset($info[$key])) {
  7113. unset($info[$key]);
  7114. $ref->setValue(null, $info);
  7115. }
  7116. } catch (\Throwable $e) {
  7117. }
  7118. try {
  7119. $db = (string)Config::get('database.database');
  7120. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7121. if (is_file($schemaFile)) {
  7122. @unlink($schemaFile);
  7123. }
  7124. } catch (\Throwable $e) {
  7125. }
  7126. }
  7127. /**
  7128. * @return array<string, bool>
  7129. */
  7130. protected function loadPurchaseOrderColumnSet(): array
  7131. {
  7132. static $set = null;
  7133. if (is_array($set)) {
  7134. return $set;
  7135. }
  7136. $set = [];
  7137. try {
  7138. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7139. } catch (\Throwable $e) {
  7140. return $set;
  7141. }
  7142. if (!is_array($cols)) {
  7143. return $set;
  7144. }
  7145. foreach ($cols as $c) {
  7146. if (!is_array($c)) {
  7147. continue;
  7148. }
  7149. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7150. if ($f !== '') {
  7151. $set[$f] = true;
  7152. }
  7153. }
  7154. return $set;
  7155. }
  7156. /**
  7157. * 解析交货截止日期(仅年月日)
  7158. */
  7159. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7160. {
  7161. $raw = trim($raw);
  7162. if ($raw === '') {
  7163. if ($required) {
  7164. $this->error('请选择交货截止日期');
  7165. }
  7166. return '';
  7167. }
  7168. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7169. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7170. } else {
  7171. $ts = strtotime(str_replace('/', '-', $raw));
  7172. if ($ts === false || $ts <= 0) {
  7173. $this->error('交货截止日期格式无效');
  7174. }
  7175. $ymd = date('Y-m-d', $ts);
  7176. }
  7177. if ($ymd < date('Y-m-d')) {
  7178. $this->error('交货截止日期不能早于今天');
  7179. }
  7180. return $ymd;
  7181. }
  7182. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7183. {
  7184. $s = trim((string)$value);
  7185. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7186. return '';
  7187. }
  7188. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7189. return $m[1];
  7190. }
  7191. $ts = strtotime(str_replace('/', '-', $s));
  7192. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7193. }
  7194. /**
  7195. * @param array{pos?:array} $bundle
  7196. */
  7197. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7198. {
  7199. foreach ($bundle['pos'] ?? [] as $po) {
  7200. if (!is_array($po)) {
  7201. continue;
  7202. }
  7203. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7204. if ($d !== '') {
  7205. return $d;
  7206. }
  7207. }
  7208. return '';
  7209. }
  7210. protected function formatProcuremenSysRqForInput($sysRq): string
  7211. {
  7212. $sr = trim((string)$sysRq);
  7213. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7214. return '';
  7215. }
  7216. $ts = strtotime($sr);
  7217. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7218. }
  7219. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7220. {
  7221. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7222. if ($sr === '') {
  7223. return '—';
  7224. }
  7225. $ts = strtotime($sr);
  7226. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7227. }
  7228. /**
  7229. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7230. *
  7231. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7232. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7233. */
  7234. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7235. {
  7236. return $bundle;
  7237. }
  7238. /**
  7239. * 写入/更新 purchase_order(单道工序行)
  7240. *
  7241. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7242. */
  7243. protected function upsertPurchaseOrderFromRow(
  7244. array $row,
  7245. string $sysRqDb,
  7246. $wflowStatus = null,
  7247. ?string $pickTime = null,
  7248. ?array $exists = null,
  7249. ?string $deliveryDeadline = null,
  7250. $scoreRuleId = null
  7251. ): void {
  7252. $ids = $this->extractScydgyRowId($row);
  7253. if (!$this->isValidScydgyRowId($ids)) {
  7254. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7255. }
  7256. if ($exists === null) {
  7257. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7258. }
  7259. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7260. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7261. $this->ensurePurchaseOrderCzlyqColumn();
  7262. $data = [
  7263. 'scydgy_id' => $ids,
  7264. 'CCYDH' => $row['CCYDH'] ?? null,
  7265. 'CYJMC' => $row['CYJMC'] ?? null,
  7266. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7267. 'CDXMC' => $row['CDXMC'] ?? null,
  7268. 'CGYBH' => $row['CGYBH'] ?? null,
  7269. 'CGYMC' => $row['CGYMC'] ?? null,
  7270. 'CDW' => $row['CDW'] ?? null,
  7271. 'czlyq' => $row['czlyq'] ?? null,
  7272. 'NGZL' => $row['NGZL'] ?? null,
  7273. 'CDF' => $row['CDF'] ?? null,
  7274. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7275. 'MBZ' => $row['MBZ'] ?? null,
  7276. 'bwjg' => $row['bwjg'] ?? null,
  7277. 'iStatus' => $row['iStatus'] ?? null,
  7278. 'dStamp' => $row['dStamp'] ?? null,
  7279. 'dputrecord' => $row['dputrecord'] ?? null,
  7280. 'cywyxm' => $row['cywyxm'] ?? null,
  7281. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7282. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7283. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7284. 'sys_rq' => $sysRqDb,
  7285. ];
  7286. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7287. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7288. if ($qtyUp === '') {
  7289. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7290. 'This_quantity' => '',
  7291. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7292. ]);
  7293. if ($qtyFallback !== '') {
  7294. $data['This_quantity'] = $qtyFallback;
  7295. }
  7296. }
  7297. if ($deliveryDeadline !== null) {
  7298. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7299. }
  7300. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7301. $scoreRule = null;
  7302. if (is_array($scoreRuleId)) {
  7303. $scoreRule = $scoreRuleId;
  7304. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7305. } else {
  7306. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7307. }
  7308. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7309. $poCols = $this->loadPurchaseOrderColumnSet();
  7310. if (!empty($poCols['score_rule_id'])) {
  7311. $data['score_rule_id'] = $scoreRuleId;
  7312. if (is_array($scoreRule)) {
  7313. if (!empty($poCols['score_rule_name'])) {
  7314. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7315. }
  7316. if (!empty($poCols['score_quality_weight'])) {
  7317. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7318. }
  7319. if (!empty($poCols['score_price_weight'])) {
  7320. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7321. }
  7322. if (!empty($poCols['score_lead_weight'])) {
  7323. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7324. }
  7325. }
  7326. }
  7327. }
  7328. if ($wflowStatus !== null && $wflowStatus !== '') {
  7329. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7330. }
  7331. if ($pickTime !== null && $pickTime !== '') {
  7332. $data['pick_time'] = $pickTime;
  7333. $data['pick_company_name'] = '';
  7334. }
  7335. if ($exists) {
  7336. $upd = $data;
  7337. unset($upd['scydgy_id']);
  7338. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7339. } else {
  7340. $data['createtime'] = date('Y-m-d H:i:s');
  7341. Db::table('purchase_order')->insert($data);
  7342. }
  7343. }
  7344. /**
  7345. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7346. *
  7347. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7348. */
  7349. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7350. {
  7351. $toDb = function ($value) {
  7352. if ($value === null) {
  7353. return null;
  7354. }
  7355. if (is_scalar($value)) {
  7356. return $value;
  7357. }
  7358. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7359. };
  7360. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7361. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7362. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7363. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7364. if ($username === '') {
  7365. $username = $this->resolveCustomerContactName($phone, $companyName);
  7366. }
  7367. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7368. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7369. }
  7370. if ($requirePhone && $phone === '') {
  7371. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7372. }
  7373. $detailLinks = [];
  7374. foreach ($mergeRows as $row) {
  7375. if (!is_array($row)) {
  7376. continue;
  7377. }
  7378. $sid = $this->extractScydgyRowId($row);
  7379. $detailId = 0;
  7380. if ($skipExisting) {
  7381. try {
  7382. $existsQuery = Db::table('purchase_order_detail')
  7383. ->where('scydgy_id', $sid)
  7384. ->where('company_name', $companyName);
  7385. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7386. $exists = $existsQuery->find();
  7387. } catch (\Throwable $e) {
  7388. $exists = null;
  7389. }
  7390. if (is_array($exists)) {
  7391. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7392. }
  7393. }
  7394. if ($detailId <= 0) {
  7395. $one = [
  7396. 'scydgy_id' => $toDb($sid),
  7397. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7398. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7399. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7400. 'username' => $username !== '' ? $username : null,
  7401. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7402. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7403. 'createtime' => date('Y-m-d H:i:s'),
  7404. 'status' => ProcuremenStatus::POD_UNPICKED,
  7405. 'status_name' => '未提交',
  7406. ];
  7407. Db::table('purchase_order_detail')->insert($one);
  7408. $detailId = (int)Db::getLastInsID();
  7409. }
  7410. $mprocUrl = '';
  7411. if ($buildMobileLinks && $detailId > 0) {
  7412. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7413. }
  7414. $detailLinks[] = [
  7415. 'detail_id' => $detailId,
  7416. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7417. 'url' => $mprocUrl,
  7418. ];
  7419. }
  7420. $this->invalidatePickHiddenScydgyCache();
  7421. return $detailLinks;
  7422. }
  7423. /**
  7424. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7425. * @return array<string, mixed>
  7426. */
  7427. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  7428. {
  7429. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7430. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7431. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7432. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7433. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7434. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7435. $isMerge = !empty($ctx['is_merge']);
  7436. $contactName = trim((string)($c['username'] ?? ''));
  7437. if ($contactName === '') {
  7438. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7439. }
  7440. $notifyVars = [
  7441. 'company_name' => $companyName,
  7442. 'contact_name' => $contactName,
  7443. 'phone' => $phone,
  7444. 'email' => $toEmail,
  7445. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7446. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7447. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7448. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7449. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7450. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7451. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7452. 'platform_url' => $platformUrl,
  7453. 'platform_links' => $platformLinksPlain,
  7454. 'platform_links_html' => $platformLinksHtml,
  7455. ];
  7456. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7457. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  7458. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7459. return [
  7460. 'company_name' => $companyName,
  7461. 'phone' => $phone,
  7462. 'email' => $toEmail,
  7463. 'sms_content' => $smsContent,
  7464. 'mail_plain' => $mailPlain,
  7465. 'mail_body' => $mailBody,
  7466. 'notify_vars' => $notifyVars,
  7467. 'detail_links' => $detailLinks,
  7468. ];
  7469. }
  7470. /**
  7471. * @param array<string, mixed> $chosen
  7472. * @param array<int, array<string, mixed>> $mergeRows
  7473. * @param array{ccydh:string, pos:array} $bundle
  7474. */
  7475. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  7476. {
  7477. if (!$sendSms && !$sendEmail) {
  7478. return;
  7479. }
  7480. $companyName = trim((string)($chosen['name'] ?? ''));
  7481. $phone = trim((string)($chosen['phone'] ?? ''));
  7482. $toEmail = trim((string)($chosen['email'] ?? ''));
  7483. if ($companyName === '') {
  7484. throw new \Exception('供应商名称无效');
  7485. }
  7486. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7487. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7488. }
  7489. if ($sendSms && $phone === '') {
  7490. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7491. }
  7492. $sids = [];
  7493. foreach ($mergeRows as $mr) {
  7494. if (!is_array($mr)) {
  7495. continue;
  7496. }
  7497. $sid = $this->extractScydgyRowId($mr);
  7498. if ($this->isValidScydgyRowId($sid)) {
  7499. $sids[$sid] = true;
  7500. }
  7501. }
  7502. if ($sids === []) {
  7503. throw new \Exception('未找到工序行,无法发送通知');
  7504. }
  7505. $sysRqNotify = '';
  7506. $pos = $bundle['pos'] ?? [];
  7507. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7508. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7509. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7510. $ts = strtotime($sr);
  7511. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7512. }
  7513. }
  7514. try {
  7515. $detailsQuery = Db::table('purchase_order_detail')
  7516. ->where('scydgy_id', 'in', array_keys($sids))
  7517. ->where('company_name', $companyName);
  7518. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7519. $details = $detailsQuery->order('id', 'asc')->select();
  7520. } catch (\Throwable $e) {
  7521. $details = [];
  7522. }
  7523. if (!is_array($details) || $details === []) {
  7524. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7525. try {
  7526. $detailsQuery = Db::table('purchase_order_detail')
  7527. ->where('scydgy_id', 'in', array_keys($sids))
  7528. ->where('company_name', $companyName);
  7529. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7530. $details = $detailsQuery->order('id', 'asc')->select();
  7531. } catch (\Throwable $e) {
  7532. $details = [];
  7533. }
  7534. }
  7535. if (!is_array($details) || $details === []) {
  7536. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7537. }
  7538. $detailLinks = [];
  7539. foreach ($details as $d) {
  7540. if (!is_array($d)) {
  7541. continue;
  7542. }
  7543. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7544. if ($detailId <= 0) {
  7545. continue;
  7546. }
  7547. $sid = (int)($d['scydgy_id'] ?? 0);
  7548. $gymc = '';
  7549. foreach ($mergeRows as $mr) {
  7550. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7551. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7552. break;
  7553. }
  7554. }
  7555. $detailLinks[] = [
  7556. 'detail_id' => $detailId,
  7557. 'cgymc' => $gymc,
  7558. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7559. ];
  7560. }
  7561. if ($detailLinks === []) {
  7562. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7563. }
  7564. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7565. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  7566. $notifyBundle['email_log_scene'] = $emailLogScene;
  7567. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7568. $poIdLog = 0;
  7569. $pos = $bundle['pos'] ?? [];
  7570. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7571. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7572. }
  7573. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7574. if ($sendEmail) {
  7575. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  7576. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7577. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  7578. }
  7579. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  7580. $mailConfig = $this->loadMailerConfig();
  7581. if (!$this->isProcuremenNotifyDryRun()) {
  7582. if (empty($mailConfig['host'])) {
  7583. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7584. }
  7585. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7586. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7587. }
  7588. }
  7589. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7590. }
  7591. if ($sendSms) {
  7592. $this->issueSendSupplierSms($notifyBundle);
  7593. }
  7594. }
  7595. /**
  7596. * @param array<int, array<string, mixed>> $quoteGroups
  7597. * @return array<int, array<string, mixed>>
  7598. */
  7599. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7600. {
  7601. $names = [];
  7602. if (is_string($companiesJson) && $companiesJson !== '') {
  7603. $decoded = json_decode($companiesJson, true);
  7604. if (is_array($decoded)) {
  7605. foreach ($decoded as $nm) {
  7606. $nm = trim((string)$nm);
  7607. if ($nm !== '') {
  7608. $names[] = $nm;
  7609. }
  7610. }
  7611. }
  7612. }
  7613. $names = array_values(array_unique($names));
  7614. if ($names === [] && $selectedCompany !== '') {
  7615. $names = [$selectedCompany];
  7616. }
  7617. if ($names === []) {
  7618. return $quoteGroups;
  7619. }
  7620. $targets = [];
  7621. foreach ($quoteGroups as $g) {
  7622. if (!is_array($g)) {
  7623. continue;
  7624. }
  7625. $cn = trim((string)($g['name'] ?? ''));
  7626. if ($cn !== '' && in_array($cn, $names, true)) {
  7627. $targets[] = $g;
  7628. }
  7629. }
  7630. return $targets;
  7631. }
  7632. /**
  7633. * @return array{pos:array, merge_rows:array, bundle:array}
  7634. */
  7635. protected function loadAuditResendBundle(string $scydgyId): array
  7636. {
  7637. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7638. $pos = $bundle['pos'];
  7639. $mergeRows = $bundle['merge_rows'];
  7640. if ($pos === [] || $mergeRows === []) {
  7641. $this->error('该订单不在待确认供应商状态');
  7642. }
  7643. $sysRqDb = '';
  7644. if (isset($pos[0]) && is_array($pos[0])) {
  7645. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7646. }
  7647. foreach ($pos as $i => $poRow) {
  7648. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7649. $pos[$i]['sys_rq'] = $sysRqDb;
  7650. }
  7651. }
  7652. $bundle['pos'] = $pos;
  7653. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7654. }
  7655. /**
  7656. * @param array<int, array<string, mixed>> $targets
  7657. */
  7658. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7659. {
  7660. if ($targets === []) {
  7661. $this->error('未找到可通知的供应商');
  7662. }
  7663. $notifyErrors = [];
  7664. try {
  7665. $this->notifyDryRunPreview = [];
  7666. foreach ($targets as $g) {
  7667. if (!is_array($g)) {
  7668. continue;
  7669. }
  7670. $cname = trim((string)($g['name'] ?? ''));
  7671. if ($cname === '') {
  7672. continue;
  7673. }
  7674. $chosen = [
  7675. 'name' => $cname,
  7676. 'company_name' => $cname,
  7677. 'email' => trim((string)($g['email'] ?? '')),
  7678. 'phone' => trim((string)($g['phone'] ?? '')),
  7679. 'username' => trim((string)($g['username'] ?? '')),
  7680. ];
  7681. try {
  7682. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7683. } catch (\Throwable $e) {
  7684. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7685. }
  7686. }
  7687. } catch (\Throwable $e) {
  7688. $this->error('通知发送失败:' . $e->getMessage());
  7689. }
  7690. if ($notifyErrors !== []) {
  7691. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7692. }
  7693. if ($this->isProcuremenNotifyDryRun()) {
  7694. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7695. 'notify_dry_run' => true,
  7696. 'notify_preview' => $this->notifyDryRunPreview,
  7697. ]);
  7698. }
  7699. $nameLabels = [];
  7700. foreach ($targets as $g) {
  7701. if (!is_array($g)) {
  7702. continue;
  7703. }
  7704. $n = trim((string)($g['name'] ?? ''));
  7705. if ($n !== '') {
  7706. $nameLabels[] = $n;
  7707. }
  7708. }
  7709. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7710. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7711. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7712. $seenLogSid = [];
  7713. foreach ($bundle['pos'] ?? [] as $poRow) {
  7714. if (!is_array($poRow)) {
  7715. continue;
  7716. }
  7717. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7718. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7719. continue;
  7720. }
  7721. $seenLogSid[$sid] = true;
  7722. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7723. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7724. }
  7725. if ($seenLogSid === []) {
  7726. foreach ($mergeRows as $mr) {
  7727. if (!is_array($mr)) {
  7728. continue;
  7729. }
  7730. $sid = $this->extractScydgyRowId($mr);
  7731. if ($this->isValidScydgyRowId($sid)) {
  7732. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7733. break;
  7734. }
  7735. }
  7736. }
  7737. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7738. }
  7739. /**
  7740. * 协助下发 — 发送短信(一家供应商)
  7741. *
  7742. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7743. */
  7744. protected function issueSendSupplierSms(array $bundle): void
  7745. {
  7746. $companyName = (string)($bundle['company_name'] ?? '');
  7747. $phone = (string)($bundle['phone'] ?? '');
  7748. $smsContent = (string)($bundle['sms_content'] ?? '');
  7749. $this->logIssueNotifyDebug('短信', [
  7750. 'company' => $companyName,
  7751. 'phone' => $phone,
  7752. 'sms_content' => $smsContent,
  7753. ]);
  7754. if ($this->isProcuremenNotifyDryRun()) {
  7755. $this->recordNotifyDryRunPreview([
  7756. 'scene' => 'issue_sms',
  7757. 'company_name' => $companyName,
  7758. 'phone' => $phone,
  7759. 'sms_content' => $smsContent,
  7760. ]);
  7761. return;
  7762. }
  7763. $this->smsbao($phone, $smsContent);
  7764. }
  7765. /**
  7766. * 协助下发 — 发送邮件(一家供应商)
  7767. *
  7768. * @param array<string, mixed> $bundle
  7769. * @param array<string, mixed> $mailConfig
  7770. */
  7771. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7772. {
  7773. $companyName = (string)($bundle['company_name'] ?? '');
  7774. $toEmail = (string)($bundle['email'] ?? '');
  7775. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7776. $mailBody = (string)($bundle['mail_body'] ?? '');
  7777. $this->logIssueNotifyDebug('邮件', [
  7778. 'company' => $companyName,
  7779. 'email' => $toEmail,
  7780. 'mail_subject' => $mailSubject,
  7781. 'mail_body' => $mailPlain,
  7782. ]);
  7783. if ($this->isProcuremenNotifyDryRun()) {
  7784. $this->recordNotifyDryRunPreview([
  7785. 'scene' => 'issue_email',
  7786. 'company_name' => $companyName,
  7787. 'email' => $toEmail,
  7788. 'mail_subject' => $mailSubject,
  7789. 'mail_body' => $mailPlain,
  7790. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7791. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7792. 'detail_links' => $bundle['detail_links'] ?? [],
  7793. ]);
  7794. return;
  7795. }
  7796. $mail = new PHPMailer(true);
  7797. $mail->isSMTP();
  7798. $mail->Host = $mailConfig['host'];
  7799. $mail->SMTPAuth = true;
  7800. $mail->Username = $mailConfig['addr'];
  7801. $mail->Password = $mailConfig['pass'];
  7802. $mail->SMTPSecure = $mailConfig['security'];
  7803. $mail->Port = $mailConfig['port'];
  7804. $mail->CharSet = $mailConfig['charset'];
  7805. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7806. $mail->addAddress($toEmail, $companyName);
  7807. $mail->isHTML(true);
  7808. $mail->Subject = $mailSubject;
  7809. $mail->Body = $mailBody;
  7810. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7811. $sendOk = true;
  7812. $failReason = '';
  7813. try {
  7814. $mail->send();
  7815. } catch (\Throwable $e) {
  7816. $sendOk = false;
  7817. $failReason = $e->getMessage();
  7818. $this->persistEmailSendLog([
  7819. 'from_email' => $fromEmail,
  7820. 'to_email' => $toEmail,
  7821. 'send_time' => date('Y-m-d H:i:s'),
  7822. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7823. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7824. 'company_name' => $companyName,
  7825. 'mail_subject' => $mailSubject,
  7826. 'status' => 0,
  7827. 'fail_reason' => $failReason,
  7828. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7829. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7830. ]);
  7831. throw $e;
  7832. }
  7833. $this->persistEmailSendLog([
  7834. 'from_email' => $fromEmail,
  7835. 'to_email' => $toEmail,
  7836. 'send_time' => date('Y-m-d H:i:s'),
  7837. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7838. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7839. 'company_name' => $companyName,
  7840. 'mail_subject' => $mailSubject,
  7841. 'status' => 1,
  7842. 'fail_reason' => '',
  7843. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7844. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7845. ]);
  7846. }
  7847. /**
  7848. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7849. *
  7850. * @param array<int, array<string, mixed>> $mergeRows
  7851. * @return array<string, mixed>
  7852. */
  7853. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7854. {
  7855. $head = $mergeRows[0] ?? [];
  7856. $isMerge = count($mergeRows) > 1;
  7857. return [
  7858. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7859. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7860. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7861. 'is_merge' => $isMerge,
  7862. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7863. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7864. 'deadline' => $sysRqNotify,
  7865. ];
  7866. }
  7867. /**
  7868. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7869. *
  7870. * @param array<string, mixed> $data
  7871. */
  7872. protected function logIssueNotifyDebug(string $type, array $data): void
  7873. {
  7874. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7875. return;
  7876. }
  7877. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7878. }
  7879. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7880. {
  7881. try {
  7882. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7883. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7884. return;
  7885. } catch (\Throwable $e) {
  7886. }
  7887. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7888. if (is_file($sqlFile)) {
  7889. $sql = file_get_contents($sqlFile);
  7890. if (is_string($sql) && $sql !== '') {
  7891. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7892. $stmt = trim($stmt);
  7893. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7894. continue;
  7895. }
  7896. try {
  7897. Db::execute($stmt);
  7898. } catch (\Throwable $ignore) {
  7899. }
  7900. }
  7901. }
  7902. }
  7903. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7904. }
  7905. /**
  7906. * @param array<string, mixed> $row
  7907. */
  7908. protected function persistEmailSendLog(array $row): void
  7909. {
  7910. try {
  7911. $this->ensurePurchaseEmailSendLogTableOnce();
  7912. } catch (\Throwable $e) {
  7913. return;
  7914. }
  7915. list($adminId, $adminName) = $this->GetUseName();
  7916. $cut = function ($s, $max) {
  7917. $s = (string)$s;
  7918. if (function_exists('mb_substr')) {
  7919. return mb_substr($s, 0, $max, 'UTF-8');
  7920. }
  7921. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7922. };
  7923. $data = [
  7924. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7925. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7926. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7927. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7928. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7929. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7930. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7931. 'status' => !empty($row['status']) ? 1 : 0,
  7932. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7933. 'admin_id' => (int)$adminId,
  7934. 'admin_name' => $cut($adminName, 64),
  7935. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7936. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7937. 'createtime' => date('Y-m-d H:i:s'),
  7938. ];
  7939. try {
  7940. Db::table('purchase_email_send_log')->insert($data);
  7941. } catch (\Throwable $e) {
  7942. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7943. }
  7944. }
  7945. protected function formatEmailLogSceneText(string $scene): string
  7946. {
  7947. $map = [
  7948. 'pick_issue' => '初选下发',
  7949. 'audit_resend' => '确认页重发',
  7950. 'rfq_salesman' => '询价通知业务员',
  7951. ];
  7952. return $map[$scene] ?? $scene;
  7953. }
  7954. /**
  7955. * 邮件发送日志列表
  7956. */
  7957. public function emailLog()
  7958. {
  7959. $this->relationSearch = false;
  7960. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7961. $this->request->filter(['strip_tags', 'trim']);
  7962. $bakModel = $this->model;
  7963. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7964. if ($this->request->isAjax()) {
  7965. $this->ensurePurchaseEmailSendLogTableOnce();
  7966. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7967. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7968. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7969. $list = $this->model
  7970. ->where($where)
  7971. ->order($sortField, $orderDir)
  7972. ->paginate($limit);
  7973. $rows = [];
  7974. foreach ($list->items() as $item) {
  7975. $row = is_array($item) ? $item : $item->toArray();
  7976. $scene = trim((string)($row['scene'] ?? ''));
  7977. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7978. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7979. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7980. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7981. $rows[] = $row;
  7982. }
  7983. $this->model = $bakModel;
  7984. return json(['total' => $list->total(), 'rows' => $rows]);
  7985. }
  7986. $this->model = $bakModel;
  7987. return $this->view->fetch('procuremen/emaillog');
  7988. }
  7989. /**
  7990. * 协助下发弹窗(选多家供应商并通知)
  7991. */
  7992. public function pickReview()
  7993. {
  7994. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  7995. $this->error(__('You have no permission'));
  7996. }
  7997. if ($this->request->isPost()) {
  7998. $this->error('请使用弹窗内「确认下发」提交');
  7999. }
  8000. $this->view->assign('pickMode', 1);
  8001. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8002. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8003. }
  8004. /**
  8005. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8006. */
  8007. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8008. {
  8009. static $done = false;
  8010. if ($done) {
  8011. return;
  8012. }
  8013. $done = true;
  8014. try {
  8015. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8016. if (empty($cols)) {
  8017. Db::execute(
  8018. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8019. );
  8020. } else {
  8021. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8022. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8023. Db::execute(
  8024. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8025. );
  8026. }
  8027. }
  8028. } catch (\Throwable $e) {
  8029. // ignore
  8030. }
  8031. }
  8032. /**
  8033. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8034. */
  8035. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8036. {
  8037. static $done = false;
  8038. if ($done) {
  8039. return;
  8040. }
  8041. $done = true;
  8042. try {
  8043. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8044. if (empty($cols)) {
  8045. Db::execute(
  8046. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8047. );
  8048. }
  8049. } catch (\Throwable $e) {
  8050. // ignore
  8051. }
  8052. try {
  8053. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8054. if (empty($cols2)) {
  8055. Db::execute(
  8056. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8057. );
  8058. }
  8059. } catch (\Throwable $e) {
  8060. // ignore
  8061. }
  8062. }
  8063. /**
  8064. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8065. */
  8066. protected function ensureRfqSalesmanEmailTemplate(): void
  8067. {
  8068. static $done = false;
  8069. if ($done) {
  8070. return;
  8071. }
  8072. $done = true;
  8073. $content = "您好,{contact_name}:\n\n"
  8074. . "有新的协助采购询价需求,请知悉。\n"
  8075. . "印件名称:{cyjmc}\n"
  8076. . "工序名称:{cgymc}\n"
  8077. . "本次数量:{this_quantity}\n"
  8078. . "供应商:{supplier_name}\n"
  8079. . "需求发起人:{cywyxm}\n";
  8080. try {
  8081. $row = Db::table('purchase_sms_template')
  8082. ->where('scene', 'rfq_salesman_email')
  8083. ->find();
  8084. } catch (\Throwable $e) {
  8085. return;
  8086. }
  8087. $now = date('Y-m-d H:i:s');
  8088. if (is_array($row) && $row !== []) {
  8089. $old = (string)($row['content'] ?? '');
  8090. $needMigrate = (strpos($old, '需求编号:{ccydh}') !== false)
  8091. || (strpos($old, '{supplier_name}') === false && strpos($old, '供应商:') === false);
  8092. if ($needMigrate) {
  8093. $data = ['content' => $content];
  8094. try {
  8095. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8096. if (!empty($cols)) {
  8097. $data['updatetime'] = $now;
  8098. }
  8099. } catch (\Throwable $e) {
  8100. }
  8101. try {
  8102. Db::table('purchase_sms_template')
  8103. ->where('id', (int)($row['id'] ?? 0))
  8104. ->update($data);
  8105. } catch (\Throwable $e) {
  8106. }
  8107. }
  8108. return;
  8109. }
  8110. try {
  8111. $data = [
  8112. 'scene' => 'rfq_salesman_email',
  8113. 'title' => '询价邮箱通知',
  8114. 'content' => $content,
  8115. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8116. 'status' => 1,
  8117. ];
  8118. try {
  8119. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8120. } catch (\Throwable $e) {
  8121. $cols = [];
  8122. }
  8123. $colNames = [];
  8124. foreach ($cols as $c) {
  8125. if (!is_array($c)) {
  8126. continue;
  8127. }
  8128. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8129. if ($n !== '') {
  8130. $colNames[$n] = true;
  8131. }
  8132. }
  8133. if (isset($colNames['updatetime'])) {
  8134. $data['updatetime'] = $now;
  8135. }
  8136. if (isset($colNames['createtime'])) {
  8137. $data['createtime'] = $now;
  8138. }
  8139. Db::table('purchase_sms_template')->insert($data);
  8140. } catch (\Throwable $e) {
  8141. // ignore
  8142. }
  8143. }
  8144. /**
  8145. * 询价多选字段:数组或字符串统一为顿号拼接
  8146. *
  8147. * @param mixed $raw
  8148. */
  8149. protected function joinRfqMultiSelectValues($raw): string
  8150. {
  8151. $parts = [];
  8152. if (is_array($raw)) {
  8153. foreach ($raw as $item) {
  8154. if (is_array($item)) {
  8155. continue;
  8156. }
  8157. $v = trim((string)$item);
  8158. if ($v !== '') {
  8159. $parts[] = $v;
  8160. }
  8161. }
  8162. } else {
  8163. $s = trim((string)$raw);
  8164. if ($s !== '') {
  8165. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8166. $v = trim((string)$piece);
  8167. if ($v !== '') {
  8168. $parts[] = $v;
  8169. }
  8170. }
  8171. }
  8172. }
  8173. $parts = array_values(array_unique($parts));
  8174. return implode('、', $parts);
  8175. }
  8176. /**
  8177. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8178. *
  8179. * @return string[]
  8180. */
  8181. protected function loadRfqSupplierNameOptions(): array
  8182. {
  8183. $out = [];
  8184. try {
  8185. $rows = Db::table('customer')
  8186. ->where(function ($q) {
  8187. $q->where('status', 1)
  8188. ->whereOr('status', '1')
  8189. ->whereOr('status', '')
  8190. ->whereNull('status');
  8191. })
  8192. ->order('id', 'desc')
  8193. ->column('company_name');
  8194. } catch (\Throwable $e) {
  8195. return [];
  8196. }
  8197. if (!is_array($rows)) {
  8198. return [];
  8199. }
  8200. foreach ($rows as $name) {
  8201. $name = trim((string)$name);
  8202. if ($name === '' || isset($out[$name])) {
  8203. continue;
  8204. }
  8205. $out[$name] = $name;
  8206. }
  8207. return array_values($out);
  8208. }
  8209. /**
  8210. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8211. */
  8212. protected function rfqNotifySalesmanAuthGroupId(): int
  8213. {
  8214. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8215. if ($id > 0) {
  8216. return $id;
  8217. }
  8218. try {
  8219. $found = Db::name('auth_group')
  8220. ->where('name', '业务员')
  8221. ->where('status', 'normal')
  8222. ->order('id', 'asc')
  8223. ->value('id');
  8224. $id = (int)$found;
  8225. } catch (\Throwable $e) {
  8226. $id = 0;
  8227. }
  8228. return $id > 0 ? $id : 12;
  8229. }
  8230. /**
  8231. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8232. *
  8233. * @return string[]
  8234. */
  8235. protected function loadRfqSalesmanNameOptions(): array
  8236. {
  8237. $out = [];
  8238. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8239. $name = trim((string)($row['name'] ?? ''));
  8240. if ($name !== '') {
  8241. $out[] = $name;
  8242. }
  8243. }
  8244. return $out;
  8245. }
  8246. /**
  8247. * 业务员角色组下管理员:姓名、邮箱、手机
  8248. *
  8249. * @return array<int, array{name:string,email:string,mobile:string}>
  8250. */
  8251. protected function loadRfqSalesmanContactOptions(): array
  8252. {
  8253. $out = [];
  8254. $seen = [];
  8255. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8256. if ($groupId <= 0) {
  8257. return [];
  8258. }
  8259. try {
  8260. $adminIds = Db::name('auth_group_access')
  8261. ->where('group_id', $groupId)
  8262. ->column('uid');
  8263. } catch (\Throwable $e) {
  8264. return [];
  8265. }
  8266. $adminIds = is_array($adminIds)
  8267. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8268. : [];
  8269. if ($adminIds === []) {
  8270. return [];
  8271. }
  8272. try {
  8273. $rows = Db::name('admin')
  8274. ->where('status', 'normal')
  8275. ->where('id', 'in', $adminIds)
  8276. ->order('id', 'asc')
  8277. ->field('id,nickname,username,email,mobile')
  8278. ->select();
  8279. } catch (\Throwable $e) {
  8280. return [];
  8281. }
  8282. if (!is_array($rows)) {
  8283. return [];
  8284. }
  8285. foreach ($rows as $row) {
  8286. if (!is_array($row)) {
  8287. continue;
  8288. }
  8289. $name = trim((string)($row['nickname'] ?? ''));
  8290. if ($name === '') {
  8291. $name = trim((string)($row['username'] ?? ''));
  8292. }
  8293. if ($name === '' || isset($seen[$name])) {
  8294. continue;
  8295. }
  8296. $seen[$name] = true;
  8297. $out[] = [
  8298. 'name' => $name,
  8299. 'email' => trim((string)($row['email'] ?? '')),
  8300. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8301. ];
  8302. }
  8303. return $out;
  8304. }
  8305. /**
  8306. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8307. *
  8308. * @return string[]
  8309. */
  8310. protected function loadRfqDeptNameOptions(): array
  8311. {
  8312. $out = [];
  8313. // ERP 承揽部门(主来源)
  8314. try {
  8315. $vals = Db::table('mcyd')
  8316. ->where('CCLBMMC', '<>', '')
  8317. ->whereNotNull('CCLBMMC')
  8318. ->distinct(true)
  8319. ->limit(300)
  8320. ->column('CCLBMMC');
  8321. } catch (\Throwable $e) {
  8322. $vals = [];
  8323. }
  8324. if (is_array($vals)) {
  8325. foreach ($vals as $v) {
  8326. $v = trim((string)$v);
  8327. if ($v === '' || isset($out[$v])) {
  8328. continue;
  8329. }
  8330. $out[$v] = $v;
  8331. }
  8332. }
  8333. // 手工询价历史部门补全
  8334. try {
  8335. $poVals = Db::table('purchase_order')
  8336. ->where('CCLBMMC', '<>', '')
  8337. ->whereNotNull('CCLBMMC')
  8338. ->distinct(true)
  8339. ->limit(200)
  8340. ->column('CCLBMMC');
  8341. } catch (\Throwable $e) {
  8342. $poVals = [];
  8343. }
  8344. if (is_array($poVals)) {
  8345. foreach ($poVals as $v) {
  8346. $v = trim((string)$v);
  8347. if ($v === '' || isset($out[$v])) {
  8348. continue;
  8349. }
  8350. $out[$v] = $v;
  8351. }
  8352. }
  8353. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8354. if (!isset($out[$preset])) {
  8355. $out[$preset] = $preset;
  8356. }
  8357. }
  8358. $list = array_values($out);
  8359. // 常用部门靠前
  8360. usort($list, static function ($a, $b) {
  8361. $weight = [
  8362. '营销中心' => 1,
  8363. '业务部' => 2,
  8364. '市场部' => 3,
  8365. '外贸部' => 4,
  8366. '新华技术业务部' => 5,
  8367. ];
  8368. $wa = $weight[$a] ?? 100;
  8369. $wb = $weight[$b] ?? 100;
  8370. if ($wa !== $wb) {
  8371. return $wa <=> $wb;
  8372. }
  8373. return strcmp((string)$a, (string)$b);
  8374. });
  8375. return $list;
  8376. }
  8377. /**
  8378. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8379. */
  8380. public function add()
  8381. {
  8382. if ($this->request->isPost()) {
  8383. $params = $this->request->post('row/a');
  8384. if (!is_array($params)) {
  8385. $this->error(__('Parameter %s can not be empty', ''));
  8386. }
  8387. [, $adminName] = $this->GetUseName();
  8388. $params['cywyxm'] = $adminName;
  8389. try {
  8390. $sid = $this->saveManualPickOrder($params);
  8391. } catch (\InvalidArgumentException $e) {
  8392. $this->error($e->getMessage());
  8393. } catch (\Throwable $e) {
  8394. $this->error($e->getMessage());
  8395. }
  8396. $this->success('新增成功', '', [
  8397. 'scydgy_id' => $sid,
  8398. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8399. ]);
  8400. }
  8401. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8402. [, $adminName] = $this->GetUseName();
  8403. $this->view->assign('adminNickname', $adminName);
  8404. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8405. $this->view->assign('defaultCclbmmc', '营销中心');
  8406. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8407. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8408. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8409. return $this->view->fetch();
  8410. }
  8411. /**
  8412. * 业务员新增进度查询(手工询价;发起人 / 通知业务员可见,超管看全部)
  8413. */
  8414. public function rfqlist()
  8415. {
  8416. $this->relationSearch = false;
  8417. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8418. $this->request->filter(['strip_tags', 'trim']);
  8419. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8420. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8421. $this->ensureRfqSalesmanEmailTemplate();
  8422. if ($this->request->isAjax()) {
  8423. try {
  8424. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8425. $limit = max(10, min(500, (int)$limit));
  8426. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8427. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8428. $filterYm = date('Y-m');
  8429. }
  8430. $applyFilters = function ($query) use ($where, $filterYm) {
  8431. $query->where('scydgy_id', '<', 0);
  8432. $this->applyPurchaseOrderNotDeletedWhere($query);
  8433. $this->applyManualRfqViewerWhere($query);
  8434. $this->applyRfqListMonthFilter($query, $filterYm);
  8435. if (!empty($where)) {
  8436. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8437. $safeWhere = [];
  8438. $skipFields = [
  8439. 'supplier_name' => true,
  8440. 'progress_text' => true,
  8441. 'createtime_text' => true,
  8442. 'notify_time_text' => true,
  8443. 'can_notify_salesman' => true,
  8444. 'has_issued' => true,
  8445. 'has_quoted' => true,
  8446. ];
  8447. foreach ((array)$where as $cond) {
  8448. if (!is_array($cond) || !isset($cond[0])) {
  8449. continue;
  8450. }
  8451. $field = (string)$cond[0];
  8452. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8453. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8454. if (isset($skipFields[$fieldBase])) {
  8455. continue;
  8456. }
  8457. if ($fieldBase === 'supplier_name') {
  8458. continue;
  8459. }
  8460. $safeWhere[] = $cond;
  8461. }
  8462. if ($safeWhere !== []) {
  8463. $query->where($safeWhere);
  8464. }
  8465. }
  8466. };
  8467. $countQuery = Db::table('purchase_order');
  8468. $applyFilters($countQuery);
  8469. $total = (int)$countQuery->count();
  8470. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8471. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8472. $listQuery = Db::table('purchase_order');
  8473. $applyFilters($listQuery);
  8474. $rows = $listQuery
  8475. ->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')
  8476. ->order($sortField, $orderDir)
  8477. ->limit($offset, $limit)
  8478. ->select();
  8479. if (!is_array($rows)) {
  8480. $rows = [];
  8481. }
  8482. $sidList = [];
  8483. foreach ($rows as $r) {
  8484. if (!is_array($r)) {
  8485. continue;
  8486. }
  8487. $sid = (int)($r['scydgy_id'] ?? 0);
  8488. if ($sid < 0) {
  8489. $sidList[$sid] = true;
  8490. }
  8491. }
  8492. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8493. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8494. $out = [];
  8495. foreach ($rows as $r) {
  8496. if (!is_array($r)) {
  8497. continue;
  8498. }
  8499. $sid = (int)($r['scydgy_id'] ?? 0);
  8500. if ($sid >= 0) {
  8501. continue;
  8502. }
  8503. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8504. if ($createdText === '') {
  8505. $createdText = trim((string)($r['dStamp'] ?? ''));
  8506. }
  8507. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8508. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8509. if ($supplier === '') {
  8510. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8511. }
  8512. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8513. || isset($issuedSidSet[$sid]);
  8514. $hasQuoted = isset($quotedSidSet[$sid]);
  8515. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8516. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8517. $out[] = [
  8518. 'id' => (int)($r['id'] ?? 0),
  8519. 'scydgy_id' => $sid,
  8520. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8521. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8522. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8523. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8524. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8525. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8526. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8527. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8528. 'supplier_name' => $supplier,
  8529. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8530. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8531. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8532. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8533. 'notify_time_text' => $notifyTimeText,
  8534. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8535. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8536. 'has_issued' => $hasIssued ? 1 : 0,
  8537. 'has_quoted' => $hasQuoted ? 1 : 0,
  8538. 'can_notify_salesman' => $canNotifySalesman,
  8539. 'createtime' => $r['createtime'] ?? null,
  8540. 'createtime_text' => $createdText,
  8541. ];
  8542. }
  8543. return json(['total' => $total, 'rows' => $out]);
  8544. } catch (\Throwable $e) {
  8545. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8546. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8547. }
  8548. }
  8549. $sidebar = $this->loadRfqSidebarYearMonths();
  8550. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8551. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8552. [, $adminName] = $this->GetUseName();
  8553. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8554. $this->view->assign('adminNickname', $adminName);
  8555. $this->view->assign('defaultYm', $defaultYm);
  8556. $this->view->assign('sidebarYearMonths', $sidebar);
  8557. return $this->view->fetch('procuremen/rfqlist');
  8558. }
  8559. /**
  8560. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8561. *
  8562. * @param array<int, array{year:string, months:array}> $sidebar
  8563. */
  8564. protected function resolveRfqListDefaultYm(array $sidebar): string
  8565. {
  8566. $current = date('Y-m');
  8567. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8568. if (in_array($current, $yms, true)) {
  8569. return $current;
  8570. }
  8571. if ($yms !== []) {
  8572. rsort($yms, SORT_STRING);
  8573. return (string)$yms[0];
  8574. }
  8575. return $current;
  8576. }
  8577. /**
  8578. * 手工询价列表左侧月份(按 createtime / dStamp)
  8579. *
  8580. * @return array<int, array{year:string, months:array}>
  8581. */
  8582. protected function loadRfqSidebarYearMonths(): array
  8583. {
  8584. $ymSet = [];
  8585. try {
  8586. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8587. $this->applyPurchaseOrderNotDeletedWhere($q);
  8588. $this->applyManualRfqViewerWhere($q);
  8589. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8590. } catch (\Throwable $e) {
  8591. $rows = [];
  8592. }
  8593. if (!is_array($rows)) {
  8594. $rows = [];
  8595. }
  8596. foreach ($rows as $r) {
  8597. if (!is_array($r)) {
  8598. continue;
  8599. }
  8600. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8601. if ($t === '') {
  8602. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8603. }
  8604. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8605. $ymSet[$m[1] . '-' . $m[2]] = true;
  8606. }
  8607. }
  8608. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8609. }
  8610. /**
  8611. * 手工询价可见范围:仅「需求发起人」或「通知业务员」与当前登录账号一致(超管看全部)
  8612. */
  8613. protected function applyManualRfqViewerWhere($query): void
  8614. {
  8615. if ($this->auth->isSuperAdmin()) {
  8616. return;
  8617. }
  8618. [, $adminName] = $this->GetUseName();
  8619. $adminName = trim((string)$adminName);
  8620. if ($adminName === '') {
  8621. $query->whereRaw('1 = 0');
  8622. return;
  8623. }
  8624. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8625. $query->where(function ($q) use ($adminName) {
  8626. $q->where('cywyxm', $adminName)
  8627. ->whereOr('notify_salesman', $adminName)
  8628. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8629. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8630. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8631. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8632. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8633. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8634. });
  8635. }
  8636. /**
  8637. * 当前用户是否可查看/操作该手工询价单(需求发起人或通知业务员;超管全部)
  8638. */
  8639. protected function canViewManualRfqOrder(array $po): bool
  8640. {
  8641. if ($this->auth->isSuperAdmin()) {
  8642. return true;
  8643. }
  8644. [, $adminName] = $this->GetUseName();
  8645. $adminName = trim((string)$adminName);
  8646. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8647. return true;
  8648. }
  8649. if ($adminName !== '') {
  8650. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8651. if ($n === $adminName) {
  8652. return true;
  8653. }
  8654. }
  8655. }
  8656. return false;
  8657. }
  8658. /**
  8659. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8660. */
  8661. protected function applyRfqListMonthFilter($query, string $ym): void
  8662. {
  8663. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8664. $ym = date('Y-m');
  8665. }
  8666. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8667. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8668. $query->whereRaw(
  8669. "("
  8670. . "CASE "
  8671. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8672. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8673. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8674. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8675. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8676. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8677. . "END"
  8678. . ") LIKE '{$ymEsc}-%'"
  8679. );
  8680. }
  8681. /**
  8682. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8683. */
  8684. public function rfqlistDetails()
  8685. {
  8686. return $this->details();
  8687. }
  8688. /**
  8689. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  8690. */
  8691. public function rfqnotifysalesmen()
  8692. {
  8693. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen'])) {
  8694. $this->error(__('You have no permission'));
  8695. }
  8696. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8697. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8698. $sid = (int)$this->request->param('scydgy_id', 0);
  8699. if ($sid >= 0) {
  8700. $this->error('仅支持手工新增询价单');
  8701. }
  8702. $po = $this->loadManualRfqOrderForNotify($sid);
  8703. $selectedMap = [];
  8704. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8705. $selectedMap[$n] = true;
  8706. }
  8707. $list = [];
  8708. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8709. $name = trim((string)($row['name'] ?? ''));
  8710. if ($name === '') {
  8711. continue;
  8712. }
  8713. $email = trim((string)($row['email'] ?? ''));
  8714. $mobile = trim((string)($row['mobile'] ?? ''));
  8715. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8716. $list[] = [
  8717. 'name' => $name,
  8718. 'email' => $email,
  8719. 'mobile' => $mobile,
  8720. 'can_select' => $hasEmail ? 1 : 0,
  8721. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  8722. ];
  8723. }
  8724. $canNotify = $this->canRfqNotifySalesman($po);
  8725. $this->success('', null, [
  8726. 'scydgy_id' => $sid,
  8727. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8728. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8729. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8730. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8731. 'list' => $list,
  8732. ]);
  8733. }
  8734. /**
  8735. * 查询询价 — 补加通知业务员可选名单
  8736. */
  8737. public function rfqsalesmanoptions()
  8738. {
  8739. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  8740. $this->error(__('You have no permission'));
  8741. }
  8742. $out = [];
  8743. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8744. $email = trim((string)($row['email'] ?? ''));
  8745. $mobile = trim((string)($row['mobile'] ?? ''));
  8746. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8747. $out[] = [
  8748. 'name' => (string)($row['name'] ?? ''),
  8749. 'email' => $email,
  8750. 'mobile' => $mobile,
  8751. 'can_select' => $hasEmail ? 1 : 0,
  8752. ];
  8753. }
  8754. $this->success('', null, ['list' => $out]);
  8755. }
  8756. /**
  8757. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  8758. */
  8759. public function rfqappendsalesmen()
  8760. {
  8761. if (!$this->request->isPost()) {
  8762. $this->error(__('Invalid parameters'));
  8763. }
  8764. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen'])) {
  8765. $this->error(__('You have no permission'));
  8766. }
  8767. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8768. $sid = (int)$this->request->post('scydgy_id', 0);
  8769. if ($sid >= 0) {
  8770. $this->error('仅支持手工新增询价单');
  8771. }
  8772. $po = $this->loadManualRfqOrderForNotify($sid);
  8773. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8774. $this->error('订单已完结,无法添加业务员');
  8775. }
  8776. $raw = $this->request->post('salesmen/a', []);
  8777. if (!is_array($raw) || $raw === []) {
  8778. $salesmenJson = $this->request->post('salesmen_json', '');
  8779. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8780. $decoded = json_decode($salesmenJson, true);
  8781. $raw = is_array($decoded) ? $decoded : [];
  8782. }
  8783. }
  8784. $addNames = [];
  8785. foreach ((array)$raw as $item) {
  8786. if (is_array($item)) {
  8787. $n = trim((string)($item['name'] ?? ''));
  8788. } else {
  8789. $n = trim((string)$item);
  8790. }
  8791. if ($n !== '') {
  8792. $addNames[] = $n;
  8793. }
  8794. }
  8795. $addNames = array_values(array_unique($addNames));
  8796. if ($addNames === []) {
  8797. $this->error('请选择要添加的业务员');
  8798. }
  8799. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  8800. $allowedMap = [];
  8801. foreach ($allowedOptions as $opt) {
  8802. $n = trim((string)($opt['name'] ?? ''));
  8803. if ($n === '') {
  8804. continue;
  8805. }
  8806. $email = trim((string)($opt['email'] ?? ''));
  8807. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  8808. }
  8809. foreach ($addNames as $n) {
  8810. if (!array_key_exists($n, $allowedMap)) {
  8811. $this->error('业务员不在可选名单中:' . $n);
  8812. }
  8813. if (!$allowedMap[$n]) {
  8814. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  8815. }
  8816. }
  8817. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  8818. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8819. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8820. try {
  8821. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  8822. } catch (\Throwable $e) {
  8823. $this->error('保存失败:' . $e->getMessage());
  8824. }
  8825. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8826. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8827. $this->success('已添加业务员', null, [
  8828. 'scydgy_id' => $sid,
  8829. 'notify_salesman' => $mergedStr,
  8830. 'added_count' => count($addNames),
  8831. ]);
  8832. }
  8833. /**
  8834. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  8835. */
  8836. public function rfqnotifysalesman()
  8837. {
  8838. if (!$this->request->isPost()) {
  8839. $this->error(__('Invalid parameters'));
  8840. }
  8841. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman'])) {
  8842. $this->error(__('You have no permission'));
  8843. }
  8844. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8845. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8846. $sid = (int)$this->request->post('scydgy_id', 0);
  8847. if ($sid >= 0) {
  8848. $this->error('仅支持手工新增询价单');
  8849. }
  8850. $po = $this->loadManualRfqOrderForNotify($sid);
  8851. $this->assertRfqCanNotifySalesman($po);
  8852. $raw = $this->request->post('salesmen/a', []);
  8853. if (!is_array($raw) || $raw === []) {
  8854. $salesmenJson = $this->request->post('salesmen_json', '');
  8855. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8856. $decoded = json_decode($salesmenJson, true);
  8857. $raw = is_array($decoded) ? $decoded : [];
  8858. }
  8859. }
  8860. // 兼容旧参数:notify_all / 单人 name
  8861. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  8862. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8863. }
  8864. if ((!is_array($raw) || $raw === [])) {
  8865. $oneName = trim((string)$this->request->post('name', ''));
  8866. if ($oneName !== '') {
  8867. $raw = [$oneName];
  8868. }
  8869. }
  8870. $selectedNames = [];
  8871. foreach ((array)$raw as $item) {
  8872. if (is_array($item)) {
  8873. $n = trim((string)($item['name'] ?? ''));
  8874. } else {
  8875. $n = trim((string)$item);
  8876. }
  8877. if ($n !== '') {
  8878. $selectedNames[] = $n;
  8879. }
  8880. }
  8881. $selectedNames = array_values(array_unique($selectedNames));
  8882. if ($selectedNames === []) {
  8883. $this->error('请选择要通知的业务员');
  8884. }
  8885. $optionMap = [];
  8886. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  8887. $n = trim((string)($opt['name'] ?? ''));
  8888. if ($n === '') {
  8889. continue;
  8890. }
  8891. $optionMap[$n] = $opt;
  8892. }
  8893. $targets = [];
  8894. foreach ($selectedNames as $n) {
  8895. if (!isset($optionMap[$n])) {
  8896. $this->error('业务员不在可选名单中:' . $n);
  8897. }
  8898. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  8899. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  8900. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  8901. }
  8902. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  8903. $targets[] = $resolved[0] ?? [
  8904. 'admin_id' => 0,
  8905. 'name' => $n,
  8906. 'email' => $email,
  8907. ];
  8908. }
  8909. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  8910. try {
  8911. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8912. 'notify_salesman' => $mergedStr,
  8913. ]);
  8914. } catch (\Throwable $e) {
  8915. $this->error('保存通知业务员失败:' . $e->getMessage());
  8916. }
  8917. $po['notify_salesman'] = $mergedStr;
  8918. $mailConfig = $this->loadMailerConfig();
  8919. if (empty($mailConfig['host'])) {
  8920. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8921. }
  8922. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8923. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8924. }
  8925. $this->ensureRfqSalesmanEmailTemplate();
  8926. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  8927. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  8928. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  8929. $qty = trim((string)($po['This_quantity'] ?? ''));
  8930. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  8931. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  8932. if ($supplier === '') {
  8933. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  8934. }
  8935. try {
  8936. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  8937. } catch (\Throwable $e) {
  8938. $this->error($e->getMessage());
  8939. }
  8940. $okNames = [];
  8941. $failMsgs = [];
  8942. foreach ($targets as $contact) {
  8943. $toEmail = trim((string)($contact['email'] ?? ''));
  8944. $toName = trim((string)($contact['name'] ?? ''));
  8945. $notifyVars = [
  8946. 'contact_name' => $toName,
  8947. 'salesman_name' => $toName,
  8948. 'company_name' => $toName,
  8949. 'email' => $toEmail,
  8950. 'ccydh' => $ccydh,
  8951. 'cyjmc' => $cyjmc,
  8952. 'cgymc' => $cgymc,
  8953. 'this_quantity' => $qty,
  8954. 'supplier_name' => $supplier,
  8955. 'cywyxm' => $cywyxm,
  8956. ];
  8957. try {
  8958. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  8959. $mailSubject = $mailSubjectTpl;
  8960. foreach ($notifyVars as $k => $v) {
  8961. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  8962. }
  8963. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  8964. $mailSubject = trim((string)$mailSubject);
  8965. if ($mailSubject === '') {
  8966. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  8967. }
  8968. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8969. $bundle = [
  8970. 'company_name' => $toName,
  8971. 'email' => $toEmail,
  8972. 'mail_plain' => $mailPlain,
  8973. 'mail_body' => $mailBody,
  8974. 'ccydh' => $ccydh,
  8975. 'email_log_scene' => 'rfq_salesman',
  8976. 'email_log_scydgy_id' => $sid,
  8977. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  8978. 'notify_vars' => $notifyVars,
  8979. ];
  8980. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  8981. $okNames[] = $toName . '(' . $toEmail . ')';
  8982. } catch (\Throwable $e) {
  8983. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  8984. }
  8985. }
  8986. if ($okNames === []) {
  8987. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  8988. }
  8989. $now = date('Y-m-d H:i:s');
  8990. try {
  8991. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8992. 'rfq_salesman_notified' => 1,
  8993. 'rfq_salesman_notify_time' => $now,
  8994. ]);
  8995. } catch (\Throwable $e) {
  8996. // ignore
  8997. }
  8998. $this->addOrderLog(
  8999. $sid,
  9000. 'rfq_notify_salesman',
  9001. '邮箱通知业务员:' . implode('、', $okNames),
  9002. (int)($po['id'] ?? 0)
  9003. );
  9004. $msg = '已通知 ' . count($okNames) . ' 人';
  9005. if ($failMsgs !== []) {
  9006. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9007. }
  9008. $this->success($msg, null, [
  9009. 'scydgy_id' => $sid,
  9010. 'notify_salesman' => $mergedStr,
  9011. 'rfq_salesman_notified' => 1,
  9012. 'rfq_salesman_notify_time' => $now,
  9013. 'notify_time_text' => $now,
  9014. 'ok_count' => count($okNames),
  9015. 'fail_count' => count($failMsgs),
  9016. ]);
  9017. }
  9018. /**
  9019. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9020. */
  9021. public function rfqissuesuppliers()
  9022. {
  9023. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers'])) {
  9024. $this->error(__('You have no permission'));
  9025. }
  9026. $sid = (int)$this->request->param('scydgy_id', 0);
  9027. if ($sid >= 0) {
  9028. $this->error('仅支持手工新增询价单');
  9029. }
  9030. $po = $this->loadManualRfqOrderForNotify($sid);
  9031. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9032. if ($supplierRaw === '') {
  9033. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9034. }
  9035. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9036. $list = [];
  9037. foreach ($names as $name) {
  9038. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9039. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9040. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9041. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9042. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9043. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9044. $list[] = [
  9045. 'name' => $name,
  9046. 'username' => $username,
  9047. 'email' => $email,
  9048. 'phone' => $phone,
  9049. 'can_notify' => $okEmail ? 1 : 0,
  9050. 'found' => is_array($contact) ? 1 : 0,
  9051. ];
  9052. }
  9053. $this->success('', null, [
  9054. 'scydgy_id' => $sid,
  9055. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9056. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9057. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9058. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9059. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9060. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9061. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9062. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9063. 'list' => $list,
  9064. ]);
  9065. }
  9066. /**
  9067. * 查询询价 — 补加供应商可选名单
  9068. */
  9069. public function rfqsupplieroptions()
  9070. {
  9071. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9072. $this->error(__('You have no permission'));
  9073. }
  9074. $names = array_values($this->loadRfqSupplierNameOptions());
  9075. $out = [];
  9076. foreach ($names as $name) {
  9077. $out[] = ['name' => $name];
  9078. }
  9079. $this->success('', null, ['list' => $out]);
  9080. }
  9081. /**
  9082. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9083. */
  9084. public function rfqappendsuppliers()
  9085. {
  9086. if (!$this->request->isPost()) {
  9087. $this->error(__('Invalid parameters'));
  9088. }
  9089. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers'])) {
  9090. $this->error(__('You have no permission'));
  9091. }
  9092. $sid = (int)$this->request->post('scydgy_id', 0);
  9093. if ($sid >= 0) {
  9094. $this->error('仅支持手工新增询价单');
  9095. }
  9096. $po = $this->loadManualRfqOrderForNotify($sid);
  9097. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9098. $this->error('订单已完结,无法补加供应商');
  9099. }
  9100. $raw = $this->request->post('suppliers/a', []);
  9101. if (!is_array($raw) || $raw === []) {
  9102. $suppliersJson = $this->request->post('suppliers_json', '');
  9103. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9104. $decoded = json_decode($suppliersJson, true);
  9105. $raw = is_array($decoded) ? $decoded : [];
  9106. }
  9107. }
  9108. $addNames = [];
  9109. foreach ((array)$raw as $item) {
  9110. if (is_array($item)) {
  9111. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9112. } else {
  9113. $n = trim((string)$item);
  9114. }
  9115. if ($n !== '') {
  9116. $addNames[] = $n;
  9117. }
  9118. }
  9119. $addNames = array_values(array_unique($addNames));
  9120. if ($addNames === []) {
  9121. $this->error('请选择要补加的供应商');
  9122. }
  9123. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9124. if ($existingRaw === '') {
  9125. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9126. }
  9127. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9128. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9129. try {
  9130. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9131. } catch (\Throwable $e) {
  9132. $this->error('保存失败:' . $e->getMessage());
  9133. }
  9134. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9135. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9136. $this->success('已补加供应商', null, [
  9137. 'scydgy_id' => $sid,
  9138. 'cGzzxMc' => $mergedStr,
  9139. 'added_count' => count($addNames),
  9140. ]);
  9141. }
  9142. /**
  9143. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9144. */
  9145. public function rfqissue()
  9146. {
  9147. if (!$this->request->isPost()) {
  9148. $this->error(__('Invalid parameters'));
  9149. }
  9150. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue'])) {
  9151. $this->error(__('You have no permission'));
  9152. }
  9153. $sid = (int)$this->request->post('scydgy_id', 0);
  9154. if ($sid >= 0) {
  9155. $this->error('仅支持手工新增询价单');
  9156. }
  9157. $po = $this->loadManualRfqOrderForNotify($sid);
  9158. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9159. $this->error('订单已完结,无法下发');
  9160. }
  9161. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9162. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9163. $this->error('订单已进入后续流程,无法再下发');
  9164. }
  9165. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9166. if ($supplierRaw === '') {
  9167. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9168. }
  9169. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9170. if ($supplierNames === []) {
  9171. $this->error('请先在新增询价时选择供应商');
  9172. }
  9173. $companies = [];
  9174. $missing = [];
  9175. $noEmail = [];
  9176. foreach ($supplierNames as $name) {
  9177. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9178. if ($contact === null) {
  9179. $missing[] = $name;
  9180. continue;
  9181. }
  9182. $em = trim((string)($contact['email'] ?? ''));
  9183. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9184. $noEmail[] = $name;
  9185. continue;
  9186. }
  9187. $companies[] = $contact;
  9188. }
  9189. if ($missing !== []) {
  9190. $this->error('未找到供应商档案:' . implode('、', $missing));
  9191. }
  9192. if ($noEmail !== []) {
  9193. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9194. }
  9195. if ($companies === []) {
  9196. $this->error('没有可通知的供应商');
  9197. }
  9198. $mailConfig = $this->loadMailerConfig();
  9199. if (empty($mailConfig['host'])) {
  9200. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9201. }
  9202. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9203. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9204. }
  9205. $mergeRow = $po;
  9206. $mergeRow['ID'] = $sid;
  9207. $mergeRow['id'] = $sid;
  9208. $mergeRows = [$mergeRow];
  9209. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9210. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9211. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9212. }
  9213. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9214. $issueTime = date('Y-m-d H:i:s');
  9215. $nameLabels = [];
  9216. foreach ($companies as $c) {
  9217. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9218. }
  9219. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9220. Db::startTrans();
  9221. try {
  9222. $this->upsertPurchaseOrderFromRow(
  9223. $mergeRow,
  9224. $sysRqDb,
  9225. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9226. $issueTime,
  9227. $po,
  9228. null,
  9229. $scoreRule
  9230. );
  9231. foreach ($companies as $c) {
  9232. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9233. }
  9234. Db::commit();
  9235. } catch (\Throwable $e) {
  9236. Db::rollback();
  9237. $this->error($e->getMessage());
  9238. }
  9239. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9240. if ($poId <= 0) {
  9241. try {
  9242. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9243. } catch (\Throwable $e) {
  9244. $poId = 0;
  9245. }
  9246. }
  9247. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9248. $posNotify = [];
  9249. try {
  9250. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9251. if (is_array($fresh)) {
  9252. $fresh['sys_rq'] = $sysRqDb;
  9253. $posNotify = [$fresh];
  9254. }
  9255. } catch (\Throwable $e) {
  9256. $posNotify = [$po];
  9257. $posNotify[0]['sys_rq'] = $sysRqDb;
  9258. }
  9259. $notifyBundle = [
  9260. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9261. 'pos' => $posNotify,
  9262. 'merge_rows' => $mergeRows,
  9263. ];
  9264. $notifyErrors = [];
  9265. foreach ($companies as $c) {
  9266. $cname = trim((string)($c['name'] ?? ''));
  9267. try {
  9268. // 询价下发:仅邮箱通知供应商
  9269. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9270. } catch (\Throwable $e) {
  9271. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9272. }
  9273. }
  9274. if ($notifyErrors !== []) {
  9275. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9276. }
  9277. $this->success('已询价并邮件通知供应商', null, [
  9278. 'scydgy_id' => $sid,
  9279. 'progress_text' => '待报价',
  9280. 'supplier_count' => count($companies),
  9281. ]);
  9282. }
  9283. /**
  9284. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9285. */
  9286. public function rfqissuesendmail()
  9287. {
  9288. if (!$this->request->isPost()) {
  9289. $this->error(__('Invalid parameters'));
  9290. }
  9291. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail'])) {
  9292. $this->error(__('You have no permission'));
  9293. }
  9294. $sid = (int)$this->request->post('scydgy_id', 0);
  9295. $companyName = trim((string)$this->request->post('company_name', ''));
  9296. if ($sid >= 0) {
  9297. $this->error('仅支持手工新增询价单');
  9298. }
  9299. if ($companyName === '') {
  9300. $this->error('请选择供应商');
  9301. }
  9302. $po = $this->loadManualRfqOrderForNotify($sid);
  9303. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9304. $this->error('订单已完结,无法发送');
  9305. }
  9306. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9307. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9308. $this->error('订单已进入后续流程,无法再发送');
  9309. }
  9310. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9311. if ($contact === null) {
  9312. $this->error('未找到供应商档案:' . $companyName);
  9313. }
  9314. $email = trim((string)($contact['email'] ?? ''));
  9315. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9316. $this->error('该供应商未填写有效邮箱');
  9317. }
  9318. $mailConfig = $this->loadMailerConfig();
  9319. if (empty($mailConfig['host'])) {
  9320. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9321. }
  9322. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9323. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9324. }
  9325. $mergeRow = $po;
  9326. $mergeRow['ID'] = $sid;
  9327. $mergeRow['id'] = $sid;
  9328. $mergeRows = [$mergeRow];
  9329. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9330. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9331. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9332. }
  9333. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9334. $issueTime = date('Y-m-d H:i:s');
  9335. Db::startTrans();
  9336. try {
  9337. $this->upsertPurchaseOrderFromRow(
  9338. $mergeRow,
  9339. $sysRqDb,
  9340. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9341. $issueTime,
  9342. $po,
  9343. null,
  9344. $scoreRule
  9345. );
  9346. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9347. Db::commit();
  9348. } catch (\Throwable $e) {
  9349. Db::rollback();
  9350. $this->error($e->getMessage());
  9351. }
  9352. $posNotify = [];
  9353. try {
  9354. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9355. if (is_array($fresh)) {
  9356. $fresh['sys_rq'] = $sysRqDb;
  9357. $posNotify = [$fresh];
  9358. }
  9359. } catch (\Throwable $e) {
  9360. $posNotify = [$po];
  9361. $posNotify[0]['sys_rq'] = $sysRqDb;
  9362. }
  9363. $notifyBundle = [
  9364. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9365. 'pos' => $posNotify,
  9366. 'merge_rows' => $mergeRows,
  9367. ];
  9368. try {
  9369. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9370. } catch (\Throwable $e) {
  9371. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9372. }
  9373. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9374. if ($poId <= 0) {
  9375. try {
  9376. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9377. } catch (\Throwable $e) {
  9378. $poId = 0;
  9379. }
  9380. }
  9381. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9382. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9383. 'scydgy_id' => $sid,
  9384. 'company_name' => $companyName,
  9385. ]);
  9386. }
  9387. /**
  9388. * 查询询价 — 查看各供应商报价(单价)
  9389. */
  9390. public function rfqquotes()
  9391. {
  9392. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue'])) {
  9393. $this->error(__('You have no permission'));
  9394. }
  9395. $sid = (int)$this->request->param('scydgy_id', 0);
  9396. if ($sid >= 0) {
  9397. $this->error('仅支持手工新增询价单');
  9398. }
  9399. $po = $this->loadManualRfqOrderForNotify($sid);
  9400. $rows = [];
  9401. try {
  9402. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9403. $q = Db::table('purchase_order_detail')
  9404. ->where('scydgy_id', $sid)
  9405. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9406. ->order('id', 'asc');
  9407. $this->applyActivePurchaseOrderDetailWhere($q);
  9408. $rows = $q->select();
  9409. } catch (\Throwable $e) {
  9410. try {
  9411. $q = Db::table('purchase_order_detail')
  9412. ->where('scydgy_id', $sid)
  9413. ->order('id', 'asc');
  9414. $this->applyActivePurchaseOrderDetailWhere($q);
  9415. $rows = $q->select();
  9416. } catch (\Throwable $e2) {
  9417. $rows = [];
  9418. }
  9419. }
  9420. if (!is_array($rows)) {
  9421. $rows = [];
  9422. }
  9423. $list = [];
  9424. foreach ($rows as $row) {
  9425. if (!is_array($row)) {
  9426. continue;
  9427. }
  9428. $amount = trim((string)($row['amount'] ?? ''));
  9429. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9430. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9431. $oper = '';
  9432. if ($isQuoted) {
  9433. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9434. if ($oper === '') {
  9435. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9436. }
  9437. }
  9438. $list[] = [
  9439. 'id' => (int)($row['id'] ?? 0),
  9440. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9441. 'amount' => $amount,
  9442. 'amount_text' => $isQuoted ? $amount : '',
  9443. 'is_quoted' => $isQuoted,
  9444. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9445. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9446. 'oper_time' => $oper,
  9447. ];
  9448. }
  9449. $this->success('', null, [
  9450. 'scydgy_id' => $sid,
  9451. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9452. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9453. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9454. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9455. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9456. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9457. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9458. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9459. 'list' => $list,
  9460. ]);
  9461. }
  9462. /**
  9463. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9464. */
  9465. protected function isRfqOrderIssued(array $po): bool
  9466. {
  9467. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9468. return true;
  9469. }
  9470. $sid = (int)($po['scydgy_id'] ?? 0);
  9471. if ($sid >= 0) {
  9472. return false;
  9473. }
  9474. try {
  9475. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9476. $this->applyActivePurchaseOrderDetailWhere($q);
  9477. return (int)$q->count() > 0;
  9478. } catch (\Throwable $e) {
  9479. return false;
  9480. }
  9481. }
  9482. /**
  9483. * 批量:已有下发明细的手工询价 scydgy_id
  9484. *
  9485. * @param int[] $scydgyIds
  9486. * @return array<int, bool>
  9487. */
  9488. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9489. {
  9490. $set = [];
  9491. $ids = [];
  9492. foreach ($scydgyIds as $sid) {
  9493. $sid = (int)$sid;
  9494. if ($sid < 0) {
  9495. $ids[$sid] = true;
  9496. }
  9497. }
  9498. if ($ids === []) {
  9499. return $set;
  9500. }
  9501. try {
  9502. $q = Db::table('purchase_order_detail')
  9503. ->where('scydgy_id', 'in', array_keys($ids))
  9504. ->field('scydgy_id');
  9505. $this->applyActivePurchaseOrderDetailWhere($q);
  9506. $rows = $q->select();
  9507. } catch (\Throwable $e) {
  9508. return $set;
  9509. }
  9510. if (!is_array($rows)) {
  9511. return $set;
  9512. }
  9513. foreach ($rows as $row) {
  9514. if (!is_array($row)) {
  9515. continue;
  9516. }
  9517. $sid = (int)($row['scydgy_id'] ?? 0);
  9518. if ($sid < 0) {
  9519. $set[$sid] = true;
  9520. }
  9521. }
  9522. return $set;
  9523. }
  9524. /**
  9525. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9526. *
  9527. * @param int[] $scydgyIds
  9528. * @return array<int, bool>
  9529. */
  9530. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9531. {
  9532. $set = [];
  9533. $ids = [];
  9534. foreach ($scydgyIds as $sid) {
  9535. $sid = (int)$sid;
  9536. if ($sid < 0) {
  9537. $ids[$sid] = true;
  9538. }
  9539. }
  9540. if ($ids === []) {
  9541. return $set;
  9542. }
  9543. try {
  9544. $q = Db::table('purchase_order_detail')
  9545. ->where('scydgy_id', 'in', array_keys($ids))
  9546. ->field('scydgy_id,amount');
  9547. $this->applyActivePurchaseOrderDetailWhere($q);
  9548. $rows = $q->select();
  9549. } catch (\Throwable $e) {
  9550. return $set;
  9551. }
  9552. if (!is_array($rows)) {
  9553. return $set;
  9554. }
  9555. foreach ($rows as $row) {
  9556. if (!is_array($row)) {
  9557. continue;
  9558. }
  9559. $amount = trim((string)($row['amount'] ?? ''));
  9560. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9561. continue;
  9562. }
  9563. $sid = (int)($row['scydgy_id'] ?? 0);
  9564. if ($sid < 0) {
  9565. $set[$sid] = true;
  9566. }
  9567. }
  9568. return $set;
  9569. }
  9570. /**
  9571. * 已下发且至少一家供应商已报价,才允许通知业务员
  9572. */
  9573. protected function canRfqNotifySalesman(array $po): bool
  9574. {
  9575. if (!$this->isRfqOrderIssued($po)) {
  9576. return false;
  9577. }
  9578. $sid = (int)($po['scydgy_id'] ?? 0);
  9579. if ($sid >= 0) {
  9580. return false;
  9581. }
  9582. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9583. return isset($quoted[$sid]);
  9584. }
  9585. protected function assertRfqCanNotifySalesman(array $po): void
  9586. {
  9587. if (!$this->isRfqOrderIssued($po)) {
  9588. $this->error('请先询价并等待供应商报价后再通知业务员');
  9589. }
  9590. if (!$this->canRfqNotifySalesman($po)) {
  9591. $this->error('供应商尚未报价,暂不能通知业务员');
  9592. }
  9593. }
  9594. /**
  9595. * 加载手工询价单(含可见性校验)
  9596. *
  9597. * @return array<string, mixed>
  9598. */
  9599. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9600. {
  9601. try {
  9602. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9603. } catch (\Throwable $e) {
  9604. $po = null;
  9605. }
  9606. if (!is_array($po)) {
  9607. $this->error('订单不存在');
  9608. }
  9609. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9610. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9611. $this->error('订单不存在');
  9612. }
  9613. if ($this->auth->isSuperAdmin()) {
  9614. return $po;
  9615. }
  9616. if ($this->canViewManualRfqOrder($po)) {
  9617. return $po;
  9618. }
  9619. $this->error('无权操作该订单');
  9620. }
  9621. /**
  9622. * @return string[]
  9623. */
  9624. protected function splitRfqSalesmanNames(string $raw): array
  9625. {
  9626. $parts = [];
  9627. $raw = trim($raw);
  9628. if ($raw === '') {
  9629. return [];
  9630. }
  9631. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9632. $v = trim((string)$piece);
  9633. if ($v !== '' && !in_array($v, $parts, true)) {
  9634. $parts[] = $v;
  9635. }
  9636. }
  9637. return $parts;
  9638. }
  9639. /**
  9640. * 按姓名匹配 fa_admin 邮箱
  9641. *
  9642. * @param string[] $names
  9643. * @return array<int, array{admin_id:int,name:string,email:string}>
  9644. */
  9645. protected function resolveRfqSalesmanContactRows(array $names): array
  9646. {
  9647. $out = [];
  9648. foreach ($names as $name) {
  9649. $name = trim((string)$name);
  9650. if ($name === '') {
  9651. continue;
  9652. }
  9653. $adminId = 0;
  9654. $email = '';
  9655. try {
  9656. $row = Db::name('admin')
  9657. ->where(function ($q) use ($name) {
  9658. $q->where('nickname', $name)->whereOr('username', $name);
  9659. })
  9660. ->where('status', 'normal')
  9661. ->order('id', 'asc')
  9662. ->field('id,nickname,username,email')
  9663. ->find();
  9664. } catch (\Throwable $e) {
  9665. $row = null;
  9666. }
  9667. if (is_array($row)) {
  9668. $adminId = (int)($row['id'] ?? 0);
  9669. $email = trim((string)($row['email'] ?? ''));
  9670. $disp = trim((string)($row['nickname'] ?? ''));
  9671. if ($disp === '') {
  9672. $disp = trim((string)($row['username'] ?? ''));
  9673. }
  9674. if ($disp !== '') {
  9675. $name = $disp;
  9676. }
  9677. }
  9678. $out[] = [
  9679. 'admin_id' => $adminId,
  9680. 'name' => $name,
  9681. 'email' => $email,
  9682. ];
  9683. }
  9684. return $out;
  9685. }
  9686. /**
  9687. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9688. */
  9689. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9690. {
  9691. if ($scydgyId >= 0) {
  9692. return;
  9693. }
  9694. try {
  9695. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9696. } catch (\Throwable $e) {
  9697. $po = null;
  9698. }
  9699. if (!is_array($po)) {
  9700. $this->error('订单不存在');
  9701. }
  9702. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9703. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9704. $this->error('订单不存在');
  9705. }
  9706. if ($this->auth->isSuperAdmin()) {
  9707. return;
  9708. }
  9709. [, $adminName] = $this->GetUseName();
  9710. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9711. if ($cywy !== '' && $cywy === $adminName) {
  9712. return;
  9713. }
  9714. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9715. try {
  9716. if ($this->auth->check($rule)) {
  9717. return;
  9718. }
  9719. } catch (\Throwable $e) {
  9720. }
  9721. }
  9722. $this->error('无权查看该订单');
  9723. }
  9724. /**
  9725. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9726. */
  9727. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9728. {
  9729. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9730. return ProcuremenStatus::PO_COMPLETED;
  9731. }
  9732. $sid = (int)($row['scydgy_id'] ?? 0);
  9733. if ($sid < 0) {
  9734. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9735. return '已通知业务员';
  9736. }
  9737. if ($hasQuoted) {
  9738. return '供应商已报价';
  9739. }
  9740. if ($hasIssued
  9741. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9742. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9743. return '待报价';
  9744. }
  9745. try {
  9746. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9747. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9748. if ((int)$detCntQuery->count() > 0) {
  9749. return '待报价';
  9750. }
  9751. } catch (\Throwable $e) {
  9752. }
  9753. return '待询价';
  9754. }
  9755. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9756. return '待入库评分';
  9757. }
  9758. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9759. return '待采购确认';
  9760. }
  9761. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9762. return '待确认供应商';
  9763. }
  9764. return '待协助下发';
  9765. }
  9766. /**
  9767. * 协助初选列表 — 批量软删除
  9768. */
  9769. public function pickDelete()
  9770. {
  9771. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9772. $this->error(__('Invalid parameters'));
  9773. }
  9774. if (!$this->procuremenCanPickDelete()) {
  9775. $this->error(__('You have no permission'));
  9776. }
  9777. $rowsRaw = $this->request->post('rows_json', '[]');
  9778. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9779. if (!is_array($rows) || $rows === []) {
  9780. $this->error('请至少勾选一条工序');
  9781. }
  9782. $done = 0;
  9783. Db::startTrans();
  9784. try {
  9785. foreach ($rows as $row) {
  9786. if (!is_array($row)) {
  9787. continue;
  9788. }
  9789. $this->softDeleteProcuremenPickRow($row);
  9790. $done++;
  9791. }
  9792. if ($done < 1) {
  9793. throw new \Exception('没有可删除的工序');
  9794. }
  9795. Db::commit();
  9796. } catch (\InvalidArgumentException $e) {
  9797. Db::rollback();
  9798. $this->error($e->getMessage());
  9799. } catch (\Throwable $e) {
  9800. Db::rollback();
  9801. $this->error($e->getMessage());
  9802. }
  9803. $this->pickHiddenScydgySetCache = null;
  9804. $this->success('已删除 ' . $done . ' 条工序');
  9805. }
  9806. /**
  9807. * 下发 — 手工新增工序(弹窗)
  9808. */
  9809. public function pickAdd()
  9810. {
  9811. if ($this->request->isPost()) {
  9812. $params = $this->request->post('row/a');
  9813. if (!is_array($params)) {
  9814. $this->error(__('Parameter %s can not be empty', ''));
  9815. }
  9816. try {
  9817. $sid = $this->saveManualPickOrder($params);
  9818. } catch (\InvalidArgumentException $e) {
  9819. $this->error($e->getMessage());
  9820. } catch (\Throwable $e) {
  9821. $this->error($e->getMessage());
  9822. }
  9823. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  9824. }
  9825. return $this->view->fetch('procuremen/pick_add');
  9826. }
  9827. /**
  9828. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  9829. */
  9830. public function pickSubmit()
  9831. {
  9832. if (!$this->request->isPost()) {
  9833. $this->error(__('Invalid parameters'));
  9834. }
  9835. // ---------- 接口订单数据 ----------
  9836. $rowJson = $this->request->post('row_json', '');
  9837. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  9838. $companiesJson = $this->request->post('companies_json', '[]');
  9839. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  9840. $companies = json_decode($companiesJson, true);
  9841. if (!is_array($companies)) {
  9842. $this->error('供应商数据无效');
  9843. }
  9844. $issueCompanies = $this->normalizePickCompanies($companies);
  9845. if ($issueCompanies === []) {
  9846. $this->error('请至少选择一家合作供应商');
  9847. }
  9848. $issueNameLabels = [];
  9849. foreach ($issueCompanies as $pc) {
  9850. $issueNameLabels[] = $pc['name'];
  9851. }
  9852. $issueNamesSummary = implode('、', $issueNameLabels);
  9853. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  9854. if ($sysRq === '') {
  9855. $this->error('请选择招标截止日期');
  9856. }
  9857. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  9858. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  9859. (string)$this->request->post('delivery_deadline', ''),
  9860. true
  9861. );
  9862. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  9863. if ($scoreRuleId <= 0) {
  9864. $this->error('请选择订单类型');
  9865. }
  9866. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  9867. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  9868. $this->error('订单类型无效,请刷新后重选');
  9869. }
  9870. $scoreRuleId = (int)$scoreRule['id'];
  9871. $this->ensurePurchaseOrderScoreRuleIdColumn();
  9872. $isMerge = count($mergeRows) > 1;
  9873. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  9874. $logMsg = '下发' . $procPart
  9875. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  9876. $issueTime = date('Y-m-d H:i:s');
  9877. $logSidList = [];
  9878. foreach ($mergeRows as $row) {
  9879. if (!is_array($row)) {
  9880. continue;
  9881. }
  9882. $sid = $this->extractScydgyRowId($row);
  9883. if ($this->isValidScydgyRowId($sid)) {
  9884. $logSidList[$sid] = true;
  9885. }
  9886. }
  9887. $existingBySid = [];
  9888. if ($logSidList !== []) {
  9889. try {
  9890. $existingRows = Db::table('purchase_order')
  9891. ->where('scydgy_id', 'in', array_keys($logSidList))
  9892. ->select();
  9893. if (is_array($existingRows)) {
  9894. foreach ($existingRows as $poRow) {
  9895. if (!is_array($poRow)) {
  9896. continue;
  9897. }
  9898. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9899. if ($this->isValidScydgyRowId($sid)) {
  9900. $existingBySid[$sid] = $poRow;
  9901. }
  9902. }
  9903. }
  9904. } catch (\Throwable $e) {
  9905. $existingBySid = [];
  9906. }
  9907. }
  9908. Db::startTrans();
  9909. try {
  9910. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  9911. foreach ($mergeRows as $row) {
  9912. if (!is_array($row)) {
  9913. continue;
  9914. }
  9915. $sid = $this->extractScydgyRowId($row);
  9916. $this->upsertPurchaseOrderFromRow(
  9917. $row,
  9918. $sysRqDb,
  9919. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9920. $issueTime,
  9921. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  9922. $deliveryDeadlineDb,
  9923. $scoreRule
  9924. );
  9925. }
  9926. foreach ($issueCompanies as $c) {
  9927. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  9928. }
  9929. Db::commit();
  9930. } catch (\Throwable $e) {
  9931. Db::rollback();
  9932. $this->error($e->getMessage());
  9933. }
  9934. $poIdBySid = [];
  9935. if ($logSidList !== []) {
  9936. try {
  9937. $poIdBySid = Db::table('purchase_order')
  9938. ->where('scydgy_id', 'in', array_keys($logSidList))
  9939. ->column('id', 'scydgy_id');
  9940. } catch (\Throwable $e) {
  9941. $poIdBySid = [];
  9942. }
  9943. }
  9944. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  9945. if ($logSidList !== []) {
  9946. list($adminId, $adminName) = $this->GetUseName();
  9947. $logRows = [];
  9948. $seenLogSid = [];
  9949. foreach ($mergeRows as $row) {
  9950. if (!is_array($row)) {
  9951. continue;
  9952. }
  9953. $ids = $this->extractScydgyRowId($row);
  9954. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  9955. continue;
  9956. }
  9957. $seenLogSid[$ids] = true;
  9958. $poIdLog = null;
  9959. if (isset($poIdBySid[$ids])) {
  9960. $tid = (int)$poIdBySid[$ids];
  9961. $poIdLog = $tid > 0 ? $tid : null;
  9962. }
  9963. $logRows[] = ProcuremenOperLog::buildInsertRow(
  9964. $ids,
  9965. 'issue_submit',
  9966. $logMsg,
  9967. $poIdLog,
  9968. (int)$adminId,
  9969. (string)$adminName
  9970. );
  9971. }
  9972. if ($logRows !== []) {
  9973. try {
  9974. Db::table('purchase_order_oper_log')->insertAll($logRows);
  9975. } catch (\Throwable $e) {
  9976. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  9977. }
  9978. }
  9979. }
  9980. $notifyErrors = [];
  9981. $posNotify = [];
  9982. if ($logSidList !== []) {
  9983. try {
  9984. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  9985. } catch (\Throwable $e) {
  9986. $posNotify = [];
  9987. }
  9988. }
  9989. if (!is_array($posNotify)) {
  9990. $posNotify = [];
  9991. }
  9992. foreach ($posNotify as $i => $prow) {
  9993. if (is_array($posNotify[$i])) {
  9994. $posNotify[$i]['sys_rq'] = $sysRqDb;
  9995. }
  9996. }
  9997. $ccydhPick = '';
  9998. foreach ($mergeRows as $row) {
  9999. if (!is_array($row)) {
  10000. continue;
  10001. }
  10002. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10003. if ($ccydhPick !== '') {
  10004. break;
  10005. }
  10006. }
  10007. $notifyBundleBase = [
  10008. 'ccydh' => $ccydhPick,
  10009. 'pos' => $posNotify,
  10010. 'merge_rows' => $mergeRows,
  10011. ];
  10012. try {
  10013. $this->notifyDryRunPreview = [];
  10014. foreach ($issueCompanies as $c) {
  10015. if (!is_array($c)) {
  10016. continue;
  10017. }
  10018. $cname = trim((string)($c['name'] ?? ''));
  10019. if ($cname === '') {
  10020. continue;
  10021. }
  10022. try {
  10023. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10024. } catch (\Throwable $e) {
  10025. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10026. }
  10027. }
  10028. } catch (\Throwable $e) {
  10029. $this->error('通知发送失败:' . $e->getMessage());
  10030. }
  10031. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10032. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10033. }
  10034. if ($this->isProcuremenNotifyDryRun()) {
  10035. $this->success('【演练模式】已保存并生成通知预览', '', [
  10036. 'notify_dry_run' => true,
  10037. 'notify_preview' => $this->notifyDryRunPreview,
  10038. ]);
  10039. }
  10040. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10041. }
  10042. /**
  10043. * 确认供应商弹窗
  10044. */
  10045. public function auditIssue()
  10046. {
  10047. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10048. if (is_array($ids)) {
  10049. $ids = isset($ids[0]) ? $ids[0] : '';
  10050. }
  10051. $ids = trim((string)$ids);
  10052. if ($ids === '') {
  10053. $this->error(__('Invalid parameters'));
  10054. }
  10055. if ($this->request->isPost()) {
  10056. $this->error('请使用弹窗内「确认」提交');
  10057. }
  10058. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10059. $pos = $bundle['pos'];
  10060. if ($pos === []) {
  10061. $this->error('该订单不在待确认供应商状态');
  10062. }
  10063. $po = $pos[0];
  10064. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10065. if ($quoteGroups === []) {
  10066. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10067. }
  10068. $pickedName = '';
  10069. foreach ($pos as $poRow) {
  10070. if (!is_array($poRow)) {
  10071. continue;
  10072. }
  10073. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10074. if ($pn !== '') {
  10075. $pickedName = $pn;
  10076. break;
  10077. }
  10078. }
  10079. $this->view->assign('po', $po);
  10080. $this->view->assign('scydgyId', $ids);
  10081. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10082. $mergeRows = $bundle['merge_rows'];
  10083. $this->view->assign('processRows', $mergeRows);
  10084. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10085. $this->view->assign('processCount', count($mergeRows));
  10086. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10087. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10088. $this->view->assign('pickedCompanyName', $pickedName);
  10089. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10090. if ($sysRqForView === '') {
  10091. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10092. }
  10093. $this->view->assign('sysRq', $sysRqForView);
  10094. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10095. if ($deliveryDeadlineForView === '') {
  10096. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10097. }
  10098. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10099. $this->ensurePurchaseOrderManualPickColumns();
  10100. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10101. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10102. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10103. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10104. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10105. $pickedName = $manualPickInfo['company'];
  10106. $this->view->assign('pickedCompanyName', $pickedName);
  10107. }
  10108. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10109. $this->view->assign('manualPicked', $manualPicked);
  10110. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10111. $this->view->assign('quoteVisible', $quoteVisible);
  10112. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10113. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10114. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10115. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10116. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10117. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10118. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10119. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10120. return $this->view->fetch('procuremen/audit_issue');
  10121. }
  10122. /**
  10123. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10124. *
  10125. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10126. */
  10127. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10128. {
  10129. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10130. return false;
  10131. }
  10132. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10133. return false;
  10134. }
  10135. return true;
  10136. }
  10137. /**
  10138. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10139. *
  10140. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10141. */
  10142. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10143. {
  10144. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10145. return false;
  10146. }
  10147. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10148. return false;
  10149. }
  10150. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10151. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10152. return true;
  10153. }
  10154. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10155. }
  10156. /**
  10157. * 确认页 — 补加供应商弹窗
  10158. */
  10159. public function auditAppend()
  10160. {
  10161. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10162. $this->error(__('You have no permission'));
  10163. }
  10164. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10165. if (is_array($ids)) {
  10166. $ids = isset($ids[0]) ? $ids[0] : '';
  10167. }
  10168. $ids = trim((string)$ids);
  10169. if ($ids === '') {
  10170. $this->error(__('Invalid parameters'));
  10171. }
  10172. if ($this->request->isPost()) {
  10173. $this->error('请使用弹窗内「确认」提交');
  10174. }
  10175. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10176. if (($bundle['pos'] ?? []) === []) {
  10177. $this->error('该订单不在待确认供应商状态');
  10178. }
  10179. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10180. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10181. $this->error('已开标验证,不能再补加供应商');
  10182. }
  10183. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10184. $this->error('已指定供应商,不能再补加供应商');
  10185. }
  10186. $this->error('已经超过了招标截止日期,不可操作');
  10187. }
  10188. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10189. $existingNames = [];
  10190. foreach ($quoteGroups as $g) {
  10191. if (!is_array($g)) {
  10192. continue;
  10193. }
  10194. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10195. if ($n !== '') {
  10196. $existingNames[$n] = true;
  10197. }
  10198. }
  10199. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10200. $mergeRows = $bundle['merge_rows'] ?? [];
  10201. $this->view->assign('scydgyId', $ids);
  10202. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10203. $this->view->assign('po', $po);
  10204. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10205. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10206. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10207. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10208. if ($sysRqForView === '') {
  10209. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10210. }
  10211. $this->view->assign('sysRq', $sysRqForView);
  10212. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10213. if ($deliveryDeadlineForView === '') {
  10214. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10215. }
  10216. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10217. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10218. }
  10219. /**
  10220. * 确认页 — 补加供应商提交
  10221. */
  10222. public function auditAppendSubmit()
  10223. {
  10224. if (!$this->request->isPost()) {
  10225. $this->error(__('Invalid parameters'));
  10226. }
  10227. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10228. $this->error(__('You have no permission'));
  10229. }
  10230. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10231. if ($ids === '') {
  10232. $this->error(__('Invalid parameters'));
  10233. }
  10234. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10235. if (($bundle['pos'] ?? []) === []) {
  10236. $this->error('该订单不在待确认供应商状态');
  10237. }
  10238. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10239. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10240. $this->error('已开标验证,不能再补加供应商');
  10241. }
  10242. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10243. $this->error('已指定供应商,不能再补加供应商');
  10244. }
  10245. $this->error('已经超过了招标截止日期,不可操作');
  10246. }
  10247. $companiesJson = $this->request->post('companies_json', '[]');
  10248. $companies = json_decode((string)$companiesJson, true);
  10249. if (!is_array($companies)) {
  10250. $this->error('供应商数据无效');
  10251. }
  10252. $issueCompanies = $this->normalizePickCompanies($companies);
  10253. if ($issueCompanies === []) {
  10254. $this->error('请至少选择一家合作供应商');
  10255. }
  10256. $mergeRows = $bundle['merge_rows'] ?? [];
  10257. if (!is_array($mergeRows) || $mergeRows === []) {
  10258. $this->error('未找到工序行,无法补加');
  10259. }
  10260. $existingNames = [];
  10261. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10262. if (!is_array($g)) {
  10263. continue;
  10264. }
  10265. $n = trim((string)($g['company_name'] ?? ''));
  10266. if ($n !== '') {
  10267. $existingNames[$n] = true;
  10268. }
  10269. }
  10270. $toAdd = [];
  10271. foreach ($issueCompanies as $c) {
  10272. if (!is_array($c)) {
  10273. continue;
  10274. }
  10275. $n = trim((string)($c['name'] ?? ''));
  10276. if ($n === '' || isset($existingNames[$n])) {
  10277. continue;
  10278. }
  10279. $toAdd[] = $c;
  10280. }
  10281. if ($toAdd === []) {
  10282. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10283. }
  10284. $addedNames = [];
  10285. Db::startTrans();
  10286. try {
  10287. foreach ($toAdd as $c) {
  10288. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10289. $addedNames[] = trim((string)($c['name'] ?? ''));
  10290. }
  10291. Db::commit();
  10292. } catch (\Throwable $e) {
  10293. Db::rollback();
  10294. $this->error($e->getMessage());
  10295. }
  10296. $notifyErrors = [];
  10297. $notifyBundleBase = [
  10298. 'ccydh' => $bundle['ccydh'] ?? '',
  10299. 'pos' => $bundle['pos'] ?? [],
  10300. 'merge_rows' => $mergeRows,
  10301. ];
  10302. foreach ($toAdd as $c) {
  10303. if (!is_array($c)) {
  10304. continue;
  10305. }
  10306. $cname = trim((string)($c['name'] ?? ''));
  10307. if ($cname === '') {
  10308. continue;
  10309. }
  10310. try {
  10311. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10312. } catch (\Throwable $e) {
  10313. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10314. }
  10315. }
  10316. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10317. $seenLogSid = [];
  10318. foreach ($bundle['pos'] ?? [] as $poRow) {
  10319. if (!is_array($poRow)) {
  10320. continue;
  10321. }
  10322. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10323. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10324. continue;
  10325. }
  10326. $seenLogSid[$sid] = true;
  10327. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10328. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10329. }
  10330. if ($seenLogSid === []) {
  10331. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10332. if ($this->isValidScydgyRowId($logSid)) {
  10333. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10334. }
  10335. }
  10336. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10337. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10338. }
  10339. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10340. }
  10341. /**
  10342. * 开标双重验证 — 可选验证人列表
  10343. */
  10344. public function bidOpenUsers()
  10345. {
  10346. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10347. $this->error('无权限');
  10348. }
  10349. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10350. if ($scydgyId !== '') {
  10351. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10352. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10353. $this->success('已完成开标验证', null, [
  10354. 'verified' => 1,
  10355. 'users' => [],
  10356. ]);
  10357. }
  10358. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10359. $this->error('本单已指定供应商,无需再开标');
  10360. }
  10361. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10362. }
  10363. $this->success('', null, [
  10364. 'verified' => 0,
  10365. 'users' => $this->listBidOpenVerifierCandidates(),
  10366. ]);
  10367. }
  10368. /**
  10369. * 开标双重验证 — 向指定管理员发送短信验证码
  10370. */
  10371. public function bidOpenSendCode()
  10372. {
  10373. if (!$this->request->isPost()) {
  10374. $this->error(__('Invalid parameters'));
  10375. }
  10376. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10377. $this->error('无权限');
  10378. }
  10379. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10380. $adminId = (int)$this->request->post('admin_id', 0);
  10381. if ($scydgyId === '' || $adminId <= 0) {
  10382. $this->error('参数无效');
  10383. }
  10384. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10385. if ($bundle['pos'] === []) {
  10386. $this->error('该订单不在待确认供应商状态');
  10387. }
  10388. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10389. $this->success('已完成开标验证,无需重复发送');
  10390. }
  10391. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10392. $this->error('本单已指定供应商,无需再开标');
  10393. }
  10394. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10395. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10396. if ($ccydh === '') {
  10397. $this->error('订单号无效');
  10398. }
  10399. $admin = $this->loadBidOpenAdminUser($adminId);
  10400. if ($admin === null) {
  10401. $this->error('验证人无效或未绑定手机号');
  10402. }
  10403. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10404. $cd = max(30, min(120, $cd));
  10405. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10406. $this->error('发送过于频繁,请稍后再试');
  10407. }
  10408. $code = (string)random_int(100000, 999999);
  10409. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10410. $ttl = max(60, min(600, $ttl));
  10411. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10412. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10413. try {
  10414. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10415. } catch (\Throwable $e) {
  10416. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10417. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10418. $this->error($e->getMessage());
  10419. }
  10420. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10421. }
  10422. /**
  10423. * 开标双重验证 — 两人验证码校验并记录
  10424. */
  10425. public function bidOpenVerify()
  10426. {
  10427. if (!$this->request->isPost()) {
  10428. $this->error(__('Invalid parameters'));
  10429. }
  10430. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10431. $this->error('无权限');
  10432. }
  10433. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10434. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10435. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10436. $code1 = trim((string)$this->request->post('code1', ''));
  10437. $code2 = trim((string)$this->request->post('code2', ''));
  10438. if ($scydgyId === '') {
  10439. $this->error('参数无效');
  10440. }
  10441. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10442. $this->error('请选择两位验证人');
  10443. }
  10444. if ($verifier1Id === $verifier2Id) {
  10445. $this->error('两位验证人不能相同');
  10446. }
  10447. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10448. $this->error('请输入6位短信验证码');
  10449. }
  10450. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10451. if ($bundle['pos'] === []) {
  10452. $this->error('该订单不在待确认供应商状态');
  10453. }
  10454. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10455. if ($ccydh === '') {
  10456. $this->error('订单号无效');
  10457. }
  10458. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10459. $this->success('已完成开标验证');
  10460. }
  10461. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10462. $this->error('本单已指定供应商,无需再开标');
  10463. }
  10464. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10465. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10466. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10467. if ($verifier1 === null || $verifier2 === null) {
  10468. $this->error('验证人无效或未绑定手机号');
  10469. }
  10470. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10471. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10472. }
  10473. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10474. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10475. }
  10476. try {
  10477. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10478. } catch (\Throwable $e) {
  10479. $this->error($e->getMessage());
  10480. }
  10481. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10482. }
  10483. /**
  10484. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10485. */
  10486. public function auditManualPick()
  10487. {
  10488. if (!$this->request->isPost()) {
  10489. $this->error(__('Invalid parameters'));
  10490. }
  10491. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10492. $this->error('无权限');
  10493. }
  10494. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10495. if ($scydgyId === '') {
  10496. $this->error('参数无效');
  10497. }
  10498. $companyName = trim((string)$this->request->post('selected_company', ''));
  10499. $reason = trim((string)$this->request->post('pick_reason', ''));
  10500. if ($companyName === '') {
  10501. $this->error('请选择一家供应商');
  10502. }
  10503. if ($reason === '') {
  10504. $this->error('请填写选择说明');
  10505. }
  10506. if (mb_strlen($reason) > 500) {
  10507. $this->error('选择说明不能超过500字');
  10508. }
  10509. $this->ensurePurchaseOrderManualPickColumns();
  10510. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10511. $pos = $bundle['pos'];
  10512. if ($pos === []) {
  10513. $this->error('该订单不在待确认供应商状态');
  10514. }
  10515. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10516. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10517. }
  10518. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10519. if ($quoteGroups === []) {
  10520. $this->error('暂无供应商,请确认已完成协助初选通知');
  10521. }
  10522. $matched = null;
  10523. foreach ($quoteGroups as $g) {
  10524. if (!is_array($g)) {
  10525. continue;
  10526. }
  10527. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10528. $matched = $g;
  10529. break;
  10530. }
  10531. }
  10532. if ($matched === null) {
  10533. $this->error('所选供应商不在本单报价列表中');
  10534. }
  10535. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10536. Db::startTrans();
  10537. try {
  10538. foreach ($pos as $poRow) {
  10539. if (!is_array($poRow)) {
  10540. continue;
  10541. }
  10542. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10543. if (!$this->isValidScydgyRowId($sid)) {
  10544. continue;
  10545. }
  10546. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10547. 'pick_company_name' => $companyName,
  10548. 'manual_pick' => 1,
  10549. 'manual_pick_reason' => $reason,
  10550. ]);
  10551. }
  10552. Db::commit();
  10553. } catch (\Throwable $e) {
  10554. Db::rollback();
  10555. $this->error($e->getMessage());
  10556. }
  10557. foreach ($pos as $poRow) {
  10558. if (!is_array($poRow)) {
  10559. continue;
  10560. }
  10561. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10562. if (!$this->isValidScydgyRowId($sid)) {
  10563. continue;
  10564. }
  10565. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10566. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10567. }
  10568. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10569. try {
  10570. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10571. if ($ccydh !== '') {
  10572. // 重新加载以拿到未掩码报价参与计分
  10573. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10574. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10575. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10576. }
  10577. } catch (\Throwable $e) {
  10578. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10579. }
  10580. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10581. }
  10582. /**
  10583. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10584. */
  10585. public function auditSubmit()
  10586. {
  10587. if (!$this->request->isPost()) {
  10588. $this->error(__('Invalid parameters'));
  10589. }
  10590. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10591. if ($scydgyId === '') {
  10592. $this->error('参数无效');
  10593. }
  10594. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10595. $pos = $bundle['pos'];
  10596. $mergeRows = $bundle['merge_rows'];
  10597. if ($pos === [] || $mergeRows === []) {
  10598. $this->error('该订单不在待确认供应商状态');
  10599. }
  10600. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10601. if ($quoteGroups === []) {
  10602. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10603. }
  10604. $companyName = trim((string)$this->request->post('selected_company', ''));
  10605. if ($companyName === '') {
  10606. $this->error('请选择一家供应商');
  10607. }
  10608. $matched = null;
  10609. foreach ($quoteGroups as $g) {
  10610. if (!is_array($g)) {
  10611. continue;
  10612. }
  10613. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10614. $matched = $g;
  10615. break;
  10616. }
  10617. }
  10618. if ($matched === null) {
  10619. $this->error('所选供应商不在本单报价列表中');
  10620. }
  10621. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10622. if ($sysRqDb === '') {
  10623. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10624. } else {
  10625. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10626. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10627. }
  10628. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10629. $this->error('未到招标截止日期,暂不可确认');
  10630. }
  10631. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10632. && !$this->isProcuremenManualPickedForBundle($bundle)
  10633. ) {
  10634. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10635. }
  10636. $procCnt = count($mergeRows);
  10637. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10638. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10639. Db::startTrans();
  10640. try {
  10641. foreach ($pos as $poRow) {
  10642. if (!is_array($poRow)) {
  10643. continue;
  10644. }
  10645. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10646. if (!$this->isValidScydgyRowId($sid)) {
  10647. continue;
  10648. }
  10649. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10650. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10651. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10652. 'pick_company_name' => $companyName,
  10653. 'sys_rq' => $sysRqDb,
  10654. ]);
  10655. }
  10656. Db::commit();
  10657. } catch (\Throwable $e) {
  10658. Db::rollback();
  10659. $this->error($e->getMessage());
  10660. }
  10661. foreach ($pos as $poRow) {
  10662. if (!is_array($poRow)) {
  10663. continue;
  10664. }
  10665. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10666. if (!$this->isValidScydgyRowId($sid)) {
  10667. continue;
  10668. }
  10669. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10670. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10671. }
  10672. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10673. }
  10674. /**
  10675. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10676. */
  10677. public function auditResendSms()
  10678. {
  10679. if (!$this->request->isPost()) {
  10680. $this->error(__('Invalid parameters'));
  10681. }
  10682. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10683. if ($scydgyId === '') {
  10684. $this->error('参数无效');
  10685. }
  10686. $loaded = $this->loadAuditResendBundle($scydgyId);
  10687. $mergeRows = $loaded['merge_rows'];
  10688. $bundle = $loaded['bundle'];
  10689. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10690. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10691. if ($quoteGroups === []) {
  10692. $this->error('暂无可通知的供应商');
  10693. }
  10694. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10695. $companiesJson = (string)$this->request->post('companies_json', '');
  10696. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10697. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10698. }
  10699. /**
  10700. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10701. */
  10702. public function auditResendEmail()
  10703. {
  10704. if (!$this->request->isPost()) {
  10705. $this->error(__('Invalid parameters'));
  10706. }
  10707. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10708. if ($scydgyId === '') {
  10709. $this->error('参数无效');
  10710. }
  10711. $loaded = $this->loadAuditResendBundle($scydgyId);
  10712. $mergeRows = $loaded['merge_rows'];
  10713. $bundle = $loaded['bundle'];
  10714. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10715. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10716. if ($quoteGroups === []) {
  10717. $this->error('暂无可通知的供应商');
  10718. }
  10719. $companiesJson = (string)$this->request->post('companies_json', '');
  10720. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10721. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10722. if ($companiesJson === '' && $selectedCompany === '') {
  10723. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10724. }
  10725. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10726. }
  10727. /**
  10728. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10729. *
  10730. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10731. * @return array<int, true> 已处理的 scydgy_id 集合
  10732. */
  10733. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10734. {
  10735. $pos = $bundle['pos'] ?? [];
  10736. if (!is_array($pos) || $pos === []) {
  10737. return [];
  10738. }
  10739. $sids = [];
  10740. $poIdBySid = [];
  10741. foreach ($pos as $poRow) {
  10742. if (!is_array($poRow)) {
  10743. continue;
  10744. }
  10745. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10746. if ($this->isValidScydgyRowId($sid)) {
  10747. $sids[$sid] = true;
  10748. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10749. if ($poId > 0) {
  10750. $poIdBySid[$sid] = $poId;
  10751. }
  10752. }
  10753. }
  10754. if ($sids === []) {
  10755. return [];
  10756. }
  10757. $logMsg = '重新下发';
  10758. $suffix = trim((string)$logSuffix, ',, ');
  10759. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10760. $logMsg .= ':从历史存证退回协助初选';
  10761. } else {
  10762. $logMsg .= ':退回协助初选';
  10763. }
  10764. Db::table('purchase_order')
  10765. ->where('scydgy_id', 'in', array_keys($sids))
  10766. ->update([
  10767. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10768. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10769. 'pick_company_name' => '',
  10770. 'pick_time' => null,
  10771. 'sys_rq' => null,
  10772. 'mod_rq' => null,
  10773. ]);
  10774. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10775. foreach (array_keys($sids) as $sid) {
  10776. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10777. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10778. }
  10779. return $sids;
  10780. }
  10781. /**
  10782. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  10783. *
  10784. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10785. */
  10786. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  10787. {
  10788. $scydgyId = trim($scydgyId);
  10789. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10790. if ($scydgyId === '') {
  10791. return $empty;
  10792. }
  10793. try {
  10794. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10795. } catch (\Throwable $e) {
  10796. $anchor = null;
  10797. }
  10798. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  10799. return $empty;
  10800. }
  10801. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10802. if ($ccydh === '') {
  10803. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10804. }
  10805. try {
  10806. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  10807. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  10808. $pos = $query->order('scydgy_id', 'asc')->select();
  10809. } catch (\Throwable $e) {
  10810. $pos = [$anchor];
  10811. }
  10812. if (!is_array($pos) || $pos === []) {
  10813. $pos = [$anchor];
  10814. }
  10815. return [
  10816. 'ccydh' => $ccydh,
  10817. 'pos' => $pos,
  10818. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10819. ];
  10820. }
  10821. protected function purchaseOrderRowIsCompleted(array $po): bool
  10822. {
  10823. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10824. }
  10825. /**
  10826. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  10827. *
  10828. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10829. */
  10830. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  10831. {
  10832. $scydgyId = trim($scydgyId);
  10833. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10834. if ($scydgyId === '') {
  10835. return $empty;
  10836. }
  10837. try {
  10838. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10839. } catch (\Throwable $e) {
  10840. $anchor = null;
  10841. }
  10842. if (!is_array($anchor)) {
  10843. return $empty;
  10844. }
  10845. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10846. if ($ccydh === '') {
  10847. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10848. }
  10849. try {
  10850. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  10851. } catch (\Throwable $e) {
  10852. $pos = [$anchor];
  10853. }
  10854. if (!is_array($pos) || $pos === []) {
  10855. $pos = [$anchor];
  10856. }
  10857. return [
  10858. 'ccydh' => $ccydh,
  10859. 'pos' => $pos,
  10860. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10861. ];
  10862. }
  10863. /**
  10864. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  10865. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  10866. */
  10867. public function auditAbandon()
  10868. {
  10869. if (!$this->request->isPost()) {
  10870. $this->error(__('Invalid parameters'));
  10871. }
  10872. $anchorIds = [];
  10873. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  10874. if ($batchRaw !== '') {
  10875. $decoded = json_decode($batchRaw, true);
  10876. if (is_array($decoded)) {
  10877. foreach ($decoded as $id) {
  10878. $s = trim((string)$id);
  10879. if ($s !== '') {
  10880. $anchorIds[] = $s;
  10881. }
  10882. }
  10883. }
  10884. }
  10885. if ($anchorIds === []) {
  10886. $single = trim((string)$this->request->post('scydgy_id', ''));
  10887. if ($single !== '') {
  10888. $anchorIds[] = $single;
  10889. }
  10890. }
  10891. if ($anchorIds === []) {
  10892. $this->error('请至少选择一条订单');
  10893. }
  10894. $processedCcydh = [];
  10895. $doneOrders = 0;
  10896. $allSids = [];
  10897. Db::startTrans();
  10898. try {
  10899. foreach ($anchorIds as $anchorId) {
  10900. $fromArchive = false;
  10901. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  10902. if (($bundle['pos'] ?? []) === []) {
  10903. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  10904. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10905. }
  10906. if (($bundle['pos'] ?? []) === []) {
  10907. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  10908. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10909. }
  10910. if (($bundle['pos'] ?? []) === []) {
  10911. continue;
  10912. }
  10913. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10914. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  10915. if (isset($processedCcydh[$dedupeKey])) {
  10916. continue;
  10917. }
  10918. $processedCcydh[$dedupeKey] = true;
  10919. $sids = $fromArchive
  10920. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  10921. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  10922. if ($sids === []) {
  10923. continue;
  10924. }
  10925. $doneOrders++;
  10926. foreach (array_keys($sids) as $sid) {
  10927. $allSids[(int)$sid] = true;
  10928. }
  10929. }
  10930. if ($doneOrders < 1) {
  10931. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  10932. }
  10933. Db::commit();
  10934. } catch (\Throwable $e) {
  10935. Db::rollback();
  10936. $this->error($e->getMessage());
  10937. }
  10938. $this->pickHiddenScydgySetCache = null;
  10939. $msg = $doneOrders > 1
  10940. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  10941. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  10942. $this->success($msg);
  10943. }
  10944. /**
  10945. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  10946. */
  10947. public function archiveAbandon()
  10948. {
  10949. return $this->auditAbandon();
  10950. }
  10951. /**
  10952. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  10953. */
  10954. public function purchaseApprovalReject()
  10955. {
  10956. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10957. $this->error(__('Invalid parameters'));
  10958. }
  10959. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  10960. $this->error(__('You have no permission'));
  10961. }
  10962. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  10963. $decoded = json_decode($batchRaw, true);
  10964. if (!is_array($decoded) || $decoded === []) {
  10965. $this->error('提交数据无效');
  10966. }
  10967. $done = 0;
  10968. Db::startTrans();
  10969. try {
  10970. foreach ($decoded as $item) {
  10971. if (!is_array($item)) {
  10972. continue;
  10973. }
  10974. $sid = (int)($item['scydgy_id'] ?? 0);
  10975. if (!$this->isValidScydgyRowId($sid)) {
  10976. continue;
  10977. }
  10978. $this->runPurchaseApprovalRejectForSid($sid);
  10979. $done++;
  10980. }
  10981. if ($done < 1) {
  10982. throw new \Exception('所选订单均不在待审批状态');
  10983. }
  10984. Db::commit();
  10985. } catch (\Throwable $e) {
  10986. Db::rollback();
  10987. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  10988. }
  10989. $this->pickHiddenScydgySetCache = null;
  10990. $this->success('已驳回并退回「协助审批下发」');
  10991. }
  10992. /**
  10993. * @throws \Exception
  10994. */
  10995. protected function runPurchaseApprovalRejectForSid(int $sid): void
  10996. {
  10997. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  10998. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  10999. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11000. $allIds = $this->purchaseOrderDetail($sid);
  11001. if ($allIds === []) {
  11002. throw new \Exception('未找到下发明细');
  11003. }
  11004. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11005. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11006. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11007. 'pick_company_name' => '',
  11008. ]);
  11009. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11010. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11011. $poId = 0;
  11012. try {
  11013. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11014. if (is_array($po)) {
  11015. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11016. }
  11017. } catch (\Throwable $e) {
  11018. }
  11019. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11020. }
  11021. /**
  11022. * 审核弹窗(旧入口,POST 已关闭)
  11023. */
  11024. public function review()
  11025. {
  11026. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11027. $this->error(__('You have no permission'));
  11028. }
  11029. if ($this->request->isPost()) {
  11030. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11031. }
  11032. $this->view->assign('pickMode', 0);
  11033. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11034. }
  11035. /**
  11036. * 审核弹窗获取公司列表
  11037. */
  11038. public function reviewCompanies()
  11039. {
  11040. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11041. $this->error(__('You have no permission'));
  11042. }
  11043. if (!$this->request->isAjax()) {
  11044. $this->error(__('Invalid parameters'));
  11045. }
  11046. $list = [];
  11047. try {
  11048. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11049. $rows = Db::table('customer')
  11050. ->where(function ($q) {
  11051. $q->where('status', 1)
  11052. ->whereOr('status', '1')
  11053. ->whereOr('status', '')
  11054. ->whereNull('status');
  11055. })
  11056. ->order('id', 'desc')
  11057. ->select();
  11058. } catch (\Throwable $e) {
  11059. $this->success('', '', []);
  11060. return;
  11061. }
  11062. if (!is_array($rows)) {
  11063. $this->success('', '', []);
  11064. return;
  11065. }
  11066. $detailColCandidates = [
  11067. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11068. 'company_detail', 'company_desc', 'address',
  11069. ];
  11070. foreach ($rows as $row) {
  11071. if (!is_array($row)) {
  11072. continue;
  11073. }
  11074. $norm = [];
  11075. foreach ($row as $k => $v) {
  11076. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11077. }
  11078. $row = $norm;
  11079. $st = $row['status'] ?? '';
  11080. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11081. continue;
  11082. }
  11083. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11084. if ($payload === null) {
  11085. continue;
  11086. }
  11087. $detail = '';
  11088. foreach ($detailColCandidates as $dk) {
  11089. if (!isset($row[$dk])) {
  11090. continue;
  11091. }
  11092. $dv = trim((string)$row[$dk]);
  11093. if ($dv !== '') {
  11094. $detail = $dv;
  11095. break;
  11096. }
  11097. }
  11098. $payload['detail'] = $detail;
  11099. $list[] = $this->maskSupplierContactFields($payload);
  11100. }
  11101. $this->success('', '', $list);
  11102. }
  11103. /**
  11104. * 采购确认-下发明细弹窗:
  11105. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11106. */
  11107. public function outward_detail()
  11108. {
  11109. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11110. if (is_array($ids)) {
  11111. $ids = isset($ids[0]) ? $ids[0] : '';
  11112. }
  11113. $ids = trim((string)$ids);
  11114. if ($ids === '') {
  11115. $this->error(__('Invalid parameters'));
  11116. }
  11117. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11118. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11119. $wffTab = 'all';
  11120. }
  11121. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11122. $purchaseOrderId = 0;
  11123. $po = null;
  11124. try {
  11125. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11126. if (is_array($po)) {
  11127. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11128. }
  11129. } catch (\Throwable $e) {
  11130. $purchaseOrderId = 0;
  11131. $po = null;
  11132. }
  11133. if (!$isPurchaseConfirm && is_array($po)) {
  11134. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11135. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11136. $isPurchaseConfirm = true;
  11137. }
  11138. }
  11139. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11140. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11141. $confirmProcessCount = 1;
  11142. $confirmPickGroups = [];
  11143. $processDisplayRows = [];
  11144. $allDetailsBySid = [];
  11145. $requiredSidList = [];
  11146. $sidList = [$ids];
  11147. if ($isPurchaseConfirm) {
  11148. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11149. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11150. if ($mergeRows !== []) {
  11151. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11152. }
  11153. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11154. if ($confirmBundle['pos'] !== []) {
  11155. $sidList = [];
  11156. foreach ($confirmBundle['pos'] as $poRow) {
  11157. if (!is_array($poRow)) {
  11158. continue;
  11159. }
  11160. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11161. if (!$this->isValidScydgyRowId($sid)) {
  11162. continue;
  11163. }
  11164. $sidList[] = (string)$sid;
  11165. $requiredSidList[] = $sid;
  11166. }
  11167. }
  11168. if ($sidList === []) {
  11169. $sidList = [$ids];
  11170. $requiredSidList = [(int)$ids];
  11171. }
  11172. $confirmProcessCount = max(1, count($requiredSidList));
  11173. if (is_array($po) && $purchaseOrderId <= 0) {
  11174. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11175. }
  11176. }
  11177. $rows = [];
  11178. try {
  11179. if (count($sidList) === 1) {
  11180. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11181. } else {
  11182. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11183. }
  11184. } catch (\Throwable $e) {
  11185. $rows = [];
  11186. }
  11187. if ($isPurchaseConfirm) {
  11188. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11189. }
  11190. foreach ($rows as &$r) {
  11191. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11192. $r['id'] = $r['ID'];
  11193. }
  11194. if (isset($r['createtime'])) {
  11195. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11196. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11197. } else {
  11198. $r['createtime_text'] = (string)$r['createtime'];
  11199. }
  11200. } else {
  11201. $r['createtime_text'] = '';
  11202. }
  11203. if (is_array($r)) {
  11204. $r = $this->maskSupplierContactFields($r);
  11205. }
  11206. }
  11207. unset($r);
  11208. $pickedCompanyName = '';
  11209. $manualPicked = 0;
  11210. $manualPickReason = '';
  11211. $quoteVisible = 0;
  11212. $bidOpenVerified = 0;
  11213. if ($isPurchaseConfirm) {
  11214. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11215. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11216. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11217. }
  11218. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11219. $confirmBundle['pos'] = [$po];
  11220. }
  11221. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11222. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11223. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11224. if ($manualPickInfo['company'] !== '') {
  11225. $pickedCompanyName = $manualPickInfo['company'];
  11226. }
  11227. if ($pickedCompanyName === '') {
  11228. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11229. if (!is_array($poRow)) {
  11230. continue;
  11231. }
  11232. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11233. if ($pn !== '') {
  11234. $pickedCompanyName = $pn;
  11235. break;
  11236. }
  11237. }
  11238. }
  11239. // 再兜底:直接读当前主单字段
  11240. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11241. $manualPicked = 1;
  11242. if ($manualPickReason === '') {
  11243. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11244. }
  11245. if ($pickedCompanyName === '') {
  11246. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11247. }
  11248. }
  11249. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11250. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11251. }
  11252. $this->view->assign('rows', $rows ?: []);
  11253. $this->view->assign('rowCount', count($rows ?: []));
  11254. $this->view->assign('scydgyId', $ids);
  11255. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11256. $this->view->assign('headTitle', $headTitle);
  11257. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11258. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11259. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11260. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11261. $this->view->assign('processDisplayRows', $processDisplayRows);
  11262. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11263. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11264. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11265. $this->view->assign('manualPicked', $manualPicked);
  11266. $this->view->assign('manualPickReason', $manualPickReason);
  11267. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11268. $this->view->assign('quoteVisible', $quoteVisible);
  11269. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11270. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11271. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11272. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11273. $sysRqDisplay = '—';
  11274. if ($isPurchaseConfirm) {
  11275. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11276. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11277. );
  11278. }
  11279. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11280. $this->view->assign('sysRq', $isPurchaseConfirm
  11281. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11282. : '');
  11283. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11284. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11285. : '');
  11286. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11287. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11288. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11289. if ($isPurchaseConfirm) {
  11290. return $this->view->fetch();
  11291. }
  11292. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11293. $this->view->engine->layout(false);
  11294. try {
  11295. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11296. $this->view->assign('dialogBody', $bodyHtml);
  11297. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11298. } finally {
  11299. if ($restoreLayout) {
  11300. $this->view->engine->layout($restoreLayout);
  11301. }
  11302. }
  11303. }
  11304. /**
  11305. * 月度导出记录表(不存在时自动创建)
  11306. */
  11307. protected function ensurePurchaseMonthExportLogTable(): void
  11308. {
  11309. try {
  11310. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11311. } catch (\Throwable $e) {
  11312. Db::execute(
  11313. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11314. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11315. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11316. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11317. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11318. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11319. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11320. `createtime` int(10) unsigned DEFAULT NULL,
  11321. PRIMARY KEY (`id`),
  11322. KEY `idx_ym` (`ym`),
  11323. KEY `idx_ct` (`createtime`)
  11324. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11325. );
  11326. }
  11327. }
  11328. /**
  11329. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11330. *
  11331. * @param array<int, mixed> $dbRows
  11332. * @return array<int, array<string, mixed>>
  11333. */
  11334. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11335. {
  11336. $keyword = trim((string)$this->request->get('search', ''));
  11337. if ($keyword === '') {
  11338. $keyword = trim((string)$this->request->request('search', ''));
  11339. }
  11340. $filter = $this->request->get('filter', '');
  11341. $op = $this->request->get('op', '');
  11342. if (is_string($filter) && $filter !== '') {
  11343. $filterArr = (array)json_decode($filter, true);
  11344. } else {
  11345. $filterArr = is_array($filter) ? $filter : [];
  11346. }
  11347. if (is_string($op) && $op !== '') {
  11348. $opArr = (array)json_decode($op, true);
  11349. } else {
  11350. $opArr = is_array($op) ? $op : [];
  11351. }
  11352. if ($keyword === '' && $filterArr === []) {
  11353. return array_values(array_filter($dbRows, 'is_array'));
  11354. }
  11355. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11356. $out = [];
  11357. foreach ($dbRows as $row) {
  11358. if (!is_array($row)) {
  11359. continue;
  11360. }
  11361. if ($keyword !== '') {
  11362. $hit = false;
  11363. foreach ($searchFields as $f) {
  11364. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11365. $hit = true;
  11366. break;
  11367. }
  11368. }
  11369. if (!$hit) {
  11370. continue;
  11371. }
  11372. }
  11373. $passFilter = true;
  11374. foreach ($filterArr as $field => $val) {
  11375. $field = (string)$field;
  11376. $val = trim((string)$val);
  11377. if ($field === '' || $val === '') {
  11378. continue;
  11379. }
  11380. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11381. continue;
  11382. }
  11383. $cell = (string)($row[$field] ?? '');
  11384. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11385. if ($mode === '=' || $mode === 'EQUAL') {
  11386. if (strcasecmp($cell, $val) !== 0) {
  11387. $passFilter = false;
  11388. break;
  11389. }
  11390. } elseif (mb_stripos($cell, $val) === false) {
  11391. $passFilter = false;
  11392. break;
  11393. }
  11394. }
  11395. if (!$passFilter) {
  11396. continue;
  11397. }
  11398. $out[] = $row;
  11399. }
  11400. return $out;
  11401. }
  11402. /**
  11403. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11404. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11405. */
  11406. public function export_month_outward()
  11407. {
  11408. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11409. $this->error(__('You have no permission'));
  11410. }
  11411. $bundle = $this->prepareMonthOutwardExportBundle();
  11412. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11413. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11414. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11415. $spreadsheet = new Spreadsheet();
  11416. $sheet = $spreadsheet->getActiveSheet();
  11417. $sheet->setTitle('外协加工明细');
  11418. $mon = (int)substr($ym, 5, 2);
  11419. $sheet->mergeCells('A1:H1');
  11420. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11421. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11422. $sheet->getStyle('A1')->getAlignment()
  11423. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11424. ->setVertical(Alignment::VERTICAL_CENTER);
  11425. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11426. $col = 'A';
  11427. foreach ($headers as $h) {
  11428. $sheet->setCellValue($col . '2', $h);
  11429. $col++;
  11430. }
  11431. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11432. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11433. $rowNum = 3;
  11434. $sumSubtotalCounts = 0;
  11435. $grandAmount = 0.0;
  11436. $globalSeq = 0;
  11437. if ($groups === []) {
  11438. $sheet->mergeCells('A3:H3');
  11439. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11440. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11441. $rowNum = 4;
  11442. } else {
  11443. foreach ($groups as $items) {
  11444. if ($items === []) {
  11445. continue;
  11446. }
  11447. $groupLineCount = count($items);
  11448. $subAmount = 0.0;
  11449. foreach ($items as $line) {
  11450. $globalSeq++;
  11451. $dr = $line['detail'];
  11452. $amt = $this->procuremenExportAmount($dr);
  11453. $subAmount += $amt;
  11454. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11455. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11456. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11457. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11458. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11459. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11460. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11461. $sheet->setCellValue('H' . $rowNum, $amt);
  11462. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11463. $rowNum++;
  11464. }
  11465. $sumSubtotalCounts += $groupLineCount;
  11466. $grandAmount += $subAmount;
  11467. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11468. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11469. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11470. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11471. ->setVertical(Alignment::VERTICAL_CENTER);
  11472. $rowNum++;
  11473. }
  11474. }
  11475. $sheet->setCellValue('A' . $rowNum, '总计');
  11476. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11477. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11478. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11479. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11480. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11481. $lastRow = $rowNum;
  11482. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11483. 'borders' => [
  11484. 'allBorders' => [
  11485. 'borderStyle' => Border::BORDER_THIN,
  11486. 'color' => ['rgb' => '000000'],
  11487. ],
  11488. ],
  11489. ]);
  11490. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11491. if ($lastRow >= 3) {
  11492. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11493. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11494. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11495. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11496. }
  11497. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11498. $sheet->getColumnDimension('A')->setWidth(7);
  11499. $sheet->getColumnDimension('B')->setWidth(16);
  11500. $sheet->getColumnDimension('C')->setWidth(52);
  11501. $sheet->getColumnDimension('D')->setWidth(32);
  11502. $sheet->getColumnDimension('E')->setWidth(12);
  11503. $sheet->getColumnDimension('F')->setWidth(44);
  11504. $sheet->getColumnDimension('G')->setWidth(26);
  11505. $sheet->getColumnDimension('H')->setWidth(13);
  11506. $sheet->getRowDimension(1)->setRowHeight(28);
  11507. $ymCompact = str_replace('-', '', $ym);
  11508. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11509. $filename = $fileBase . '.xlsx';
  11510. try {
  11511. $this->ensurePurchaseMonthExportLogTable();
  11512. list($adminId, $adminName) = $this->GetUseName();
  11513. Db::table('purchase_month_export_log')->insert([
  11514. 'ym' => $ym,
  11515. 'admin_id' => (int)$adminId,
  11516. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11517. 'row_count' => count($exportLines),
  11518. 'total_amount' => round($grandAmount, 2),
  11519. 'createtime' => time(),
  11520. ]);
  11521. } catch (\Throwable $e) {
  11522. Log::write('month export log: ' . $e->getMessage(), 'error');
  11523. }
  11524. if (ob_get_length()) {
  11525. ob_end_clean();
  11526. }
  11527. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11528. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11529. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11530. header('Cache-Control: max-age=0');
  11531. $writer = new Xlsx($spreadsheet);
  11532. $writer->save('php://output');
  11533. $spreadsheet->disconnectWorksheets();
  11534. unset($spreadsheet);
  11535. exit;
  11536. }
  11537. /**
  11538. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11539. */
  11540. public function export_month_quote()
  11541. {
  11542. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11543. $this->error(__('You have no permission'));
  11544. }
  11545. $bundle = $this->prepareMonthOutwardExportBundle();
  11546. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11547. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11548. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11549. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11550. $spreadsheet = new Spreadsheet();
  11551. $sheet = $spreadsheet->getActiveSheet();
  11552. $sheet->setTitle('供应商报价明细');
  11553. $mon = (int)substr($ym, 5, 2);
  11554. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11555. $sheet->getColumnDimension('A')->setWidth(7);
  11556. $sheet->getColumnDimension('B')->setWidth(16);
  11557. $sheet->getColumnDimension('C')->setWidth(52);
  11558. $sheet->getColumnDimension('D')->setWidth(26);
  11559. $sheet->getColumnDimension('E')->setWidth(32);
  11560. $sheet->getColumnDimension('F')->setWidth(12);
  11561. $sheet->getColumnDimension('G')->setWidth(14);
  11562. $sheet->getColumnDimension('H')->setWidth(12);
  11563. if ($quoteLastRow < 1) {
  11564. $quoteLastRow = 3;
  11565. }
  11566. $ymCompact = str_replace('-', '', $ym);
  11567. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11568. if (ob_get_length()) {
  11569. ob_end_clean();
  11570. }
  11571. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11572. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11573. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11574. header('Cache-Control: max-age=0');
  11575. $writer = new Xlsx($spreadsheet);
  11576. $writer->save('php://output');
  11577. $spreadsheet->disconnectWorksheets();
  11578. unset($spreadsheet);
  11579. exit;
  11580. }
  11581. /**
  11582. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11583. *
  11584. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11585. */
  11586. protected function prepareMonthOutwardExportBundle(): array
  11587. {
  11588. $this->request->filter(['strip_tags', 'trim']);
  11589. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11590. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11591. $ym = date('Y-m');
  11592. }
  11593. $dbRows = [];
  11594. try {
  11595. $query = Db::table('purchase_order');
  11596. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11597. $dbRows = $query->select();
  11598. } catch (\Throwable $e) {
  11599. $dbRows = [];
  11600. }
  11601. if (!is_array($dbRows)) {
  11602. $dbRows = [];
  11603. }
  11604. $completeTsMap = [];
  11605. $sidList = [];
  11606. foreach ($dbRows as $dbRow) {
  11607. if (!is_array($dbRow)) {
  11608. continue;
  11609. }
  11610. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11611. if ($sid > 0) {
  11612. $sidList[$sid] = true;
  11613. }
  11614. }
  11615. if ($sidList !== []) {
  11616. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11617. }
  11618. $searchKw = trim((string)$this->request->get('search', ''));
  11619. if ($searchKw === '') {
  11620. $searchKw = trim((string)$this->request->request('search', ''));
  11621. }
  11622. $filterRaw = $this->request->get('filter', '');
  11623. $filterArrTmp = [];
  11624. if (is_string($filterRaw) && $filterRaw !== '') {
  11625. $filterArrTmp = (array)json_decode($filterRaw, true);
  11626. } elseif (is_array($filterRaw)) {
  11627. $filterArrTmp = $filterRaw;
  11628. }
  11629. $hasSearch = ($searchKw !== '');
  11630. if (!$hasSearch) {
  11631. foreach ($filterArrTmp as $fv) {
  11632. if (trim((string)$fv) !== '') {
  11633. $hasSearch = true;
  11634. break;
  11635. }
  11636. }
  11637. }
  11638. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11639. if (!is_array($dbRow)) {
  11640. return false;
  11641. }
  11642. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11643. if ($done['ts'] <= 0) {
  11644. return false;
  11645. }
  11646. if ($hasSearch) {
  11647. return true;
  11648. }
  11649. return date('Y-m', $done['ts']) === $ym;
  11650. }));
  11651. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11652. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11653. $mainBySid = [];
  11654. foreach ($pool as $rw) {
  11655. if (!is_array($rw)) {
  11656. continue;
  11657. }
  11658. $rid = (int)($rw['ID'] ?? 0);
  11659. if ($rid > 0) {
  11660. $mainBySid[$rid] = $rw;
  11661. }
  11662. }
  11663. if ($mainBySid === []) {
  11664. $detailRows = [];
  11665. } else {
  11666. try {
  11667. $detailRows = Db::table('purchase_order_detail')
  11668. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11669. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11670. ->order('status', 'desc')
  11671. ->order('CCYDH', 'asc')
  11672. ->order('company_name', 'asc')
  11673. ->order('id', 'asc')
  11674. ->select();
  11675. } catch (\Throwable $e) {
  11676. try {
  11677. $detailRows = Db::table('purchase_order_detail')
  11678. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11679. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11680. ->order('status', 'desc')
  11681. ->order('CCYDH', 'asc')
  11682. ->order('company_name', 'asc')
  11683. ->order('ID', 'asc')
  11684. ->select();
  11685. } catch (\Throwable $e2) {
  11686. $detailRows = [];
  11687. }
  11688. }
  11689. }
  11690. if (!is_array($detailRows)) {
  11691. $detailRows = [];
  11692. }
  11693. $exportLines = [];
  11694. $detailSidSeen = [];
  11695. foreach ($detailRows as $dr) {
  11696. if (!is_array($dr)) {
  11697. continue;
  11698. }
  11699. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11700. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11701. continue;
  11702. }
  11703. if (isset($detailSidSeen[$sid])) {
  11704. continue;
  11705. }
  11706. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11707. continue;
  11708. }
  11709. $detailSidSeen[$sid] = true;
  11710. $m = $mainBySid[$sid];
  11711. $exportLines[] = [
  11712. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11713. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11714. 'company_name' => (string)($dr['company_name'] ?? ''),
  11715. 'CDF' => (string)($m['CDF'] ?? ''),
  11716. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11717. 'gx' => $this->procuremenExportGxText($m),
  11718. 'detail' => $dr,
  11719. ];
  11720. }
  11721. foreach ($detailRows as $dr) {
  11722. if (!is_array($dr)) {
  11723. continue;
  11724. }
  11725. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11726. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11727. continue;
  11728. }
  11729. $detailSidSeen[$sid] = true;
  11730. $m = $mainBySid[$sid];
  11731. $exportLines[] = [
  11732. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11733. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11734. 'company_name' => (string)($dr['company_name'] ?? ''),
  11735. 'CDF' => (string)($m['CDF'] ?? ''),
  11736. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11737. 'gx' => $this->procuremenExportGxText($m),
  11738. 'detail' => $dr,
  11739. ];
  11740. }
  11741. foreach ($mainBySid as $sid => $m) {
  11742. if (isset($detailSidSeen[$sid])) {
  11743. continue;
  11744. }
  11745. $company = trim((string)($m['pick_company_name'] ?? ''));
  11746. $exportLines[] = [
  11747. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11748. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11749. 'company_name' => $company,
  11750. 'CDF' => (string)($m['CDF'] ?? ''),
  11751. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11752. 'gx' => $this->procuremenExportGxText($m),
  11753. 'detail' => [],
  11754. ];
  11755. }
  11756. $groups = [];
  11757. foreach ($exportLines as $line) {
  11758. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11759. if (!isset($groups[$k])) {
  11760. $groups[$k] = [];
  11761. }
  11762. $groups[$k][] = $line;
  11763. }
  11764. ksort($groups, SORT_STRING);
  11765. return [
  11766. 'ym' => $ym,
  11767. 'mainBySid' => $mainBySid,
  11768. 'detailRows' => $detailRows,
  11769. 'exportLines' => $exportLines,
  11770. 'groups' => $groups,
  11771. ];
  11772. }
  11773. /**
  11774. * 导出用:工序列文案
  11775. */
  11776. protected function procuremenExportGxText(array $r)
  11777. {
  11778. $a = trim((string)($r['CDXMC'] ?? ''));
  11779. $b = trim((string)($r['CGYMC'] ?? ''));
  11780. if ($a !== '' && $b !== '') {
  11781. return $a . ':' . $b;
  11782. }
  11783. return $a !== '' ? $a : $b;
  11784. }
  11785. /**
  11786. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  11787. */
  11788. protected function procuremenExportAmount(array $r)
  11789. {
  11790. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  11791. if (!array_key_exists($k, $r)) {
  11792. continue;
  11793. }
  11794. $v = $r[$k];
  11795. if ($v === null || $v === '') {
  11796. continue;
  11797. }
  11798. if (is_numeric($v)) {
  11799. return (float)$v;
  11800. }
  11801. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  11802. if ($v !== '' && is_numeric($v)) {
  11803. return (float)$v;
  11804. }
  11805. }
  11806. return 0.0;
  11807. }
  11808. /**
  11809. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  11810. *
  11811. * @param array<int, array<string, mixed>> $detailRows
  11812. * @param array<int, array<string, mixed>> $mainBySid
  11813. * @return array<int, array<string, mixed>>
  11814. */
  11815. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  11816. {
  11817. $lines = [];
  11818. foreach ($detailRows as $dr) {
  11819. if (!is_array($dr)) {
  11820. continue;
  11821. }
  11822. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11823. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11824. continue;
  11825. }
  11826. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  11827. continue;
  11828. }
  11829. $cn = trim((string)($dr['company_name'] ?? ''));
  11830. if ($cn === '') {
  11831. continue;
  11832. }
  11833. $m = $mainBySid[$sid];
  11834. $am = trim((string)($dr['amount'] ?? ''));
  11835. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  11836. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  11837. $amountText = $amountFilled
  11838. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  11839. : '未填写';
  11840. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  11841. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  11842. if ($deliveryShow === '' && $deliveryRaw !== '') {
  11843. $deliveryShow = $deliveryRaw;
  11844. }
  11845. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  11846. ? $deliveryShow
  11847. : '未填写';
  11848. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  11849. $lines[] = [
  11850. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11851. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11852. 'gx' => $this->procuremenExportGxText($m),
  11853. 'company_name' => $cn,
  11854. 'amount_text' => $amountText,
  11855. 'amount_num' => $amountFilled ? $amountNum : null,
  11856. 'delivery_text' => $deliveryText,
  11857. 'picked_text' => $picked ? '中标' : '未中标',
  11858. 'picked' => $picked,
  11859. ];
  11860. }
  11861. $winnerSupplierByOrder = [];
  11862. foreach ($lines as $line) {
  11863. $dh = trim((string)($line['CCYDH'] ?? ''));
  11864. $cn = trim((string)($line['company_name'] ?? ''));
  11865. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  11866. $winnerSupplierByOrder[$dh][$cn] = true;
  11867. }
  11868. }
  11869. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  11870. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  11871. if ($c !== 0) {
  11872. return $c;
  11873. }
  11874. $dh = trim((string)($a['CCYDH'] ?? ''));
  11875. $aCn = trim((string)($a['company_name'] ?? ''));
  11876. $bCn = trim((string)($b['company_name'] ?? ''));
  11877. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  11878. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  11879. if ($aSupplierWin !== $bSupplierWin) {
  11880. return $aSupplierWin ? -1 : 1;
  11881. }
  11882. $c = strcmp($aCn, $bCn);
  11883. if ($c !== 0) {
  11884. return $c;
  11885. }
  11886. if (!empty($a['picked']) !== !empty($b['picked'])) {
  11887. return !empty($a['picked']) ? -1 : 1;
  11888. }
  11889. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  11890. if ($c !== 0) {
  11891. return $c;
  11892. }
  11893. return 0;
  11894. });
  11895. return $lines;
  11896. }
  11897. /**
  11898. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  11899. *
  11900. * @param array<int, array<string, mixed>> $quoteLines
  11901. */
  11902. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  11903. {
  11904. $mon = (int)substr($ym, 5, 2);
  11905. $titleRow = $startRow;
  11906. $headerRow = $startRow + 1;
  11907. $dataStartRow = $startRow + 2;
  11908. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  11909. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  11910. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  11911. $sheet->getStyle('A' . $titleRow)->getAlignment()
  11912. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11913. ->setVertical(Alignment::VERTICAL_CENTER);
  11914. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  11915. $col = 'A';
  11916. foreach ($headers as $h) {
  11917. $sheet->setCellValue($col . $headerRow, $h);
  11918. $col++;
  11919. }
  11920. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  11921. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11922. $rowNum = $dataStartRow;
  11923. if ($quoteLines === []) {
  11924. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  11925. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  11926. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11927. $rowNum = $dataStartRow + 1;
  11928. } else {
  11929. $i = 0;
  11930. foreach ($quoteLines as $line) {
  11931. $i++;
  11932. $sheet->setCellValue('A' . $rowNum, $i);
  11933. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  11934. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  11935. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  11936. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  11937. if ($line['amount_num'] !== null) {
  11938. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  11939. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  11940. } else {
  11941. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  11942. }
  11943. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  11944. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  11945. if (!empty($line['picked'])) {
  11946. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11947. }
  11948. $rowNum++;
  11949. }
  11950. }
  11951. $lastRow = $rowNum - 1;
  11952. if ($lastRow >= $headerRow) {
  11953. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  11954. 'borders' => [
  11955. 'allBorders' => [
  11956. 'borderStyle' => Border::BORDER_THIN,
  11957. 'color' => ['rgb' => '000000'],
  11958. ],
  11959. ],
  11960. ]);
  11961. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11962. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11963. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11964. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11965. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  11966. if ($lastRow >= $dataStartRow) {
  11967. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  11968. }
  11969. }
  11970. return $lastRow;
  11971. }
  11972. /**
  11973. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  11974. */
  11975. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  11976. {
  11977. if ($lastRow < $dataStartRow || $headerRow < 1) {
  11978. return;
  11979. }
  11980. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  11981. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11982. ->setVertical(Alignment::VERTICAL_CENTER);
  11983. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  11984. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11985. ->setVertical(Alignment::VERTICAL_CENTER);
  11986. if ($lastCol > 'B') {
  11987. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  11988. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11989. ->setVertical(Alignment::VERTICAL_CENTER);
  11990. }
  11991. }
  11992. /**
  11993. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  11994. */
  11995. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  11996. {
  11997. $s = trim($ccydh);
  11998. if ($s === '') {
  11999. return 'ORDER';
  12000. }
  12001. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12002. $s = trim($s, '._-');
  12003. if ($s === '') {
  12004. return 'ORDER';
  12005. }
  12006. if (function_exists('mb_substr')) {
  12007. return mb_substr($s, 0, 80, 'UTF-8');
  12008. }
  12009. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12010. }
  12011. /**
  12012. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12013. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12014. *
  12015. * @return array{objectKey: string, webPath: string}
  12016. */
  12017. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12018. {
  12019. $sid = (int)$scydgyId;
  12020. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12021. $y = date('Y');
  12022. $m = date('m');
  12023. $d = date('d');
  12024. $basename = $safeOrder . '_' . $sid . '.pdf';
  12025. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12026. return [
  12027. 'objectKey' => $objectKey,
  12028. 'webPath' => '/' . $objectKey,
  12029. ];
  12030. }
  12031. /**
  12032. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12033. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12034. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12035. *
  12036. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12037. */
  12038. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12039. {
  12040. if (!$this->isValidScydgyRowId($scydgyId)) {
  12041. return '';
  12042. }
  12043. $ids = trim((string)$scydgyId);
  12044. $prep = $this->prepareProcuremenDetailsView($ids);
  12045. if (!$prep['ok']) {
  12046. return '';
  12047. }
  12048. $ccydh = $prep['ccydh'];
  12049. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12050. $objectKey = $paths['objectKey'];
  12051. $webPath = $paths['webPath'];
  12052. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12053. $this->view->assign([
  12054. 'pdf_export' => 1,
  12055. 'pdfMetaLine' => $meta,
  12056. ]);
  12057. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12058. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12059. $this->view->engine->layout(false);
  12060. try {
  12061. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12062. } catch (\Throwable $e) {
  12063. if ($restoreLayout) {
  12064. $this->view->engine->layout($restoreLayout);
  12065. }
  12066. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12067. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12068. return '';
  12069. }
  12070. if ($restoreLayout) {
  12071. $this->view->engine->layout($restoreLayout);
  12072. }
  12073. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12074. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12075. if (!is_dir($tempDir)) {
  12076. @mkdir($tempDir, 0755, true);
  12077. }
  12078. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12079. try {
  12080. $mpdf = new \Mpdf\Mpdf([
  12081. 'mode' => 'utf-8',
  12082. 'format' => 'A4',
  12083. 'margin_left' => 12,
  12084. 'margin_right' => 12,
  12085. 'margin_top' => 14,
  12086. 'margin_bottom' => 14,
  12087. 'tempDir' => $tempDir,
  12088. 'autoScriptToLang' => true,
  12089. 'autoLangToFont' => true,
  12090. ]);
  12091. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12092. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12093. $mpdf->SetBasePath('http://127.0.0.1/');
  12094. $mpdf->WriteHTML($html);
  12095. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12096. } catch (\Throwable $e) {
  12097. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12098. if (is_file($tempPdf)) {
  12099. @unlink($tempPdf);
  12100. }
  12101. return '';
  12102. }
  12103. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12104. if ($ossUrl !== '') {
  12105. @unlink($tempPdf);
  12106. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12107. return $ossUrl;
  12108. }
  12109. $pi = pathinfo($objectKey);
  12110. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12111. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12112. if ($baseFile === '') {
  12113. @unlink($tempPdf);
  12114. return '';
  12115. }
  12116. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12117. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12118. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12119. @unlink($tempPdf);
  12120. return '';
  12121. }
  12122. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12123. if (!@copy($tempPdf, $fullPath)) {
  12124. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12125. @unlink($tempPdf);
  12126. return '';
  12127. }
  12128. @unlink($tempPdf);
  12129. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12130. return $webPath;
  12131. }
  12132. /**
  12133. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12134. */
  12135. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12136. {
  12137. if ($scydgyId <= 0 || $webPath === '') {
  12138. return;
  12139. }
  12140. try {
  12141. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12142. } catch (\Throwable $e) {
  12143. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12144. }
  12145. }
  12146. /**
  12147. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12148. *
  12149. * @param array<string, string> $vars
  12150. * @return array<string, string>
  12151. */
  12152. protected function normalizeSmsTemplateVars(array $vars): array
  12153. {
  12154. $out = [];
  12155. foreach ($vars as $k => $v) {
  12156. $out[(string)$k] = trim((string)$v);
  12157. }
  12158. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12159. $out['contact_name'] = $out['company_name'];
  12160. }
  12161. return $out;
  12162. }
  12163. /**
  12164. * 按手机号或公司名称查 customer 表联系人姓名
  12165. */
  12166. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12167. {
  12168. $phone = trim($phone);
  12169. $companyName = trim($companyName);
  12170. try {
  12171. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12172. $row = Db::table('customer')
  12173. ->where(function ($q) use ($phone) {
  12174. $q->where('phone', $phone)->whereOr('account', $phone);
  12175. })
  12176. ->order('id', 'asc')
  12177. ->find();
  12178. if (is_array($row)) {
  12179. $nm = trim((string)($row['username'] ?? ''));
  12180. if ($nm !== '') {
  12181. return $nm;
  12182. }
  12183. }
  12184. }
  12185. if ($companyName !== '') {
  12186. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12187. if (is_array($row)) {
  12188. return trim((string)($row['username'] ?? ''));
  12189. }
  12190. }
  12191. } catch (\Throwable $e) {
  12192. }
  12193. return '';
  12194. }
  12195. /**
  12196. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12197. */
  12198. protected function plainTextToHtmlEmailBody(string $text): string
  12199. {
  12200. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12201. $parts = explode("\n", $text);
  12202. $out = [];
  12203. foreach ($parts as $line) {
  12204. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12205. $out[] = $line;
  12206. } else {
  12207. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12208. }
  12209. }
  12210. return implode("<br>\n", $out);
  12211. }
  12212. /**
  12213. * 短信场景:去掉链接类变量,避免误填 URL
  12214. *
  12215. * @param array<string, string> $vars
  12216. * @return array<string, string>
  12217. */
  12218. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12219. {
  12220. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12221. return $vars;
  12222. }
  12223. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12224. $vars[$k] = '';
  12225. }
  12226. return $vars;
  12227. }
  12228. /**
  12229. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12230. *
  12231. * @param array<string, string> $vars
  12232. */
  12233. protected function renderNotifyTemplate(string $scene, array $vars): string
  12234. {
  12235. $vars = $this->normalizeSmsTemplateVars($vars);
  12236. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12237. $row = $this->loadNotifyTemplateRow($scene);
  12238. if ($row === null) {
  12239. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12240. }
  12241. $tpl = trim((string)($row['content'] ?? ''));
  12242. if ($tpl === '') {
  12243. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12244. }
  12245. foreach ($vars as $k => $v) {
  12246. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12247. }
  12248. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12249. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12250. return $tpl;
  12251. }
  12252. protected function resolveProcuremenEmailSubject(string $scene): string
  12253. {
  12254. // 询价通知业务员:模版名称即邮件主题(可含 {ccydh})
  12255. if ($scene === 'rfq_salesman_email') {
  12256. $row = $this->loadNotifyTemplateRow($scene);
  12257. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12258. if ($title !== '') {
  12259. return $title;
  12260. }
  12261. return '协助采购询价通知';
  12262. }
  12263. $map = [
  12264. 'review_email' => '您有新的协助加工订单',
  12265. ];
  12266. $subject = trim((string)($map[$scene] ?? ''));
  12267. if ($subject === '') {
  12268. $this->error('未配置邮件主题:' . $scene);
  12269. }
  12270. return $subject;
  12271. }
  12272. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12273. {
  12274. $map = [
  12275. 'review_email' => '协助下发-邮箱',
  12276. 'review_sms' => '协助下发-短信',
  12277. 'confirm_ok' => '采购确认-通过',
  12278. 'confirm_fail' => '采购确认-未通过',
  12279. 'bid_open' => '开标双重验证',
  12280. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12281. ];
  12282. $label = $map[$scene] ?? $scene;
  12283. if ($titleRequired) {
  12284. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12285. }
  12286. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12287. }
  12288. /**
  12289. * 是否开启协助通知演练(不发真实短信/邮件)
  12290. */
  12291. protected function isProcuremenNotifyDryRun(): bool
  12292. {
  12293. return (bool)Config::get('procuremen_notify_dry_run');
  12294. }
  12295. /**
  12296. * @param array<string, mixed> $payload
  12297. */
  12298. protected function recordNotifyDryRunPreview(array $payload): void
  12299. {
  12300. $this->notifyDryRunPreview[] = $payload;
  12301. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12302. }
  12303. /**
  12304. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12305. * @throws \Exception
  12306. */
  12307. protected function smsbao($phone, $content)
  12308. {
  12309. if ($this->isProcuremenNotifyDryRun()) {
  12310. $this->recordNotifyDryRunPreview([
  12311. 'scene' => 'sms_only',
  12312. 'phone' => $phone,
  12313. 'sms_content' => $content,
  12314. ]);
  12315. return;
  12316. }
  12317. $statusStr = [
  12318. '0' => '短信发送成功',
  12319. '-1' => '参数不全',
  12320. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12321. '30' => '密码错误',
  12322. '40' => '账号不存在',
  12323. '41' => '余额不足',
  12324. '42' => '帐户已过期',
  12325. '43' => 'IP地址限制',
  12326. '50' => '内容含有敏感词',
  12327. ];
  12328. $smsapi = 'http://api.smsbao.com/';
  12329. $user = 'zhuwei123';
  12330. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12331. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12332. $result = @file_get_contents($sendurl);
  12333. if ($result === false) {
  12334. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12335. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12336. }
  12337. $result = trim((string)$result);
  12338. if ($result !== '0') {
  12339. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12340. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12341. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12342. }
  12343. }
  12344. }