Procuremen.php 530 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986
  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\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  263. *
  264. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  265. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  266. */
  267. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  268. {
  269. static $mprocCfgLoaded = false;
  270. if (!$mprocCfgLoaded) {
  271. $mprocCfgLoaded = true;
  272. if (is_file(APP_PATH . 'extra/mproc.php')) {
  273. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  274. }
  275. }
  276. $eid = (int)$purchaseOrderDetailId;
  277. $base = $this->resolveMprocMobilePublicBaseUrl();
  278. if ($base === '') {
  279. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  280. }
  281. $path = trim((string)Config::get('mproc.mobile_index_path'));
  282. if ($path === '') {
  283. $path = '/index.php/index/index/index';
  284. } else {
  285. $path = '/' . ltrim($path, '/');
  286. }
  287. $tab = trim((string)$listTab);
  288. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  289. $tab = '';
  290. }
  291. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  292. if ($eid > 0) {
  293. $hash = 'mproc_fe=' . $eid;
  294. if ($tab !== '') {
  295. $hash .= '&mproc_tab=' . $tab;
  296. }
  297. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  298. }
  299. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  300. }
  301. /**
  302. * 业务员手机端「订单询价」直达链接(默认待询价)
  303. *
  304. * @param int $scydgyId 手工询价 scydgy_id(负数)
  305. * @param string $status pending|quoted
  306. */
  307. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  308. {
  309. static $mprocCfgLoaded = false;
  310. if (!$mprocCfgLoaded) {
  311. $mprocCfgLoaded = true;
  312. if (is_file(APP_PATH . 'extra/mproc.php')) {
  313. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  314. }
  315. }
  316. $base = $this->resolveMprocMobilePublicBaseUrl();
  317. if ($base === '') {
  318. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  319. }
  320. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  321. if ($indexPath === '') {
  322. $indexPath = '/index.php/index/index/index';
  323. } else {
  324. $indexPath = '/' . ltrim($indexPath, '/');
  325. }
  326. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  327. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  328. $path = '/index.php/index/index/rfqadd';
  329. }
  330. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  331. $sid = (int)$scydgyId;
  332. $q = 'status=' . $status;
  333. $hash = '';
  334. if ($sid < 0) {
  335. $q .= '&focus_sid=' . $sid;
  336. $hash = '#mproc_fs=' . $sid;
  337. }
  338. return $base . $path . '?' . $q . $hash;
  339. }
  340. /**
  341. * 邮件/短信外链:须为带点的公网域名
  342. */
  343. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  344. {
  345. $u = trim((string)$baseUrl);
  346. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  347. return false;
  348. }
  349. $host = parse_url($u, PHP_URL_HOST);
  350. if (!is_string($host) || $host === '') {
  351. return false;
  352. }
  353. if (strcasecmp($host, 'localhost') === 0) {
  354. return false;
  355. }
  356. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  357. return false;
  358. }
  359. if (strpos($host, '.') === false) {
  360. return false;
  361. }
  362. return true;
  363. }
  364. /**
  365. * 解析用于协助邮件/短信的手机端站点根
  366. */
  367. protected function resolveMprocMobilePublicBaseUrl()
  368. {
  369. $candidates = [];
  370. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  371. $candidates[] = trim((string)Config::get('site.indexurl'));
  372. $cdn = trim((string)Config::get('site.cdnurl'));
  373. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  374. $candidates[] = rtrim($cdn, '/');
  375. }
  376. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  377. $candidates[] = $reqBase;
  378. foreach ($candidates as $c) {
  379. if ($c === '') {
  380. continue;
  381. }
  382. $c = rtrim($c, '/');
  383. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  384. return $c;
  385. }
  386. }
  387. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  388. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  389. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  390. return $reqBase;
  391. }
  392. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  393. return '';
  394. }
  395. /**
  396. * 获取 Redis 中 procuremen_redis
  397. */
  398. protected function ProcuremenRedis(): array
  399. {
  400. if ($this->procuremenRedisCache !== null) {
  401. return $this->procuremenRedisCache;
  402. }
  403. try {
  404. $redis = redis();
  405. $raw = $redis->get('procuremen_redis');
  406. if ($raw === false || $raw === '') {
  407. $this->procuremenRedisCache = [];
  408. return $this->procuremenRedisCache;
  409. }
  410. $decoded = json_decode($raw, true);
  411. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  412. $this->procuremenRedisCache = [];
  413. return $this->procuremenRedisCache;
  414. }
  415. $this->procuremenRedisCache = $decoded['data'];
  416. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  417. if ($this->loadProcuremenSidebarYmList() === []) {
  418. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  419. }
  420. return $this->procuremenRedisCache;
  421. } catch (\Throwable $e) {
  422. $this->procuremenRedisCache = [];
  423. return $this->procuremenRedisCache;
  424. }
  425. }
  426. /**
  427. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  428. *
  429. * @return array<int, array<string, mixed>>
  430. */
  431. protected function procuremenFetchErpPoolFromDb(): array
  432. {
  433. try {
  434. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  435. $endTime = date('Y-m-d 23:59:59');
  436. $list = Db::table('scydgy')
  437. ->alias('a')
  438. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  439. ->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')
  440. ->where([
  441. 'a.bwjg' => 1,
  442. 'a.iEndBz' => 0,
  443. 'a.iType' => 0,
  444. 'a.iStatus' => 10,
  445. ])
  446. ->where('a.dStamp', '>=', $startTime)
  447. ->where('a.dStamp', '<=', $endTime)
  448. ->order('a.dStamp', 'desc')
  449. ->select();
  450. if (!is_array($list)) {
  451. return [];
  452. }
  453. try {
  454. $redis = redis();
  455. $payload = [
  456. 'code' => 200,
  457. 'msg' => 'success',
  458. 'data' => $list,
  459. ];
  460. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  461. $this->procuremenRedisCache = $list;
  462. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  463. $this->clearPickMonthPoolCaches();
  464. $this->warmPickMonthPoolCachesFromPool($list);
  465. } catch (\Throwable $e) {
  466. }
  467. return $list;
  468. } catch (\Throwable $e) {
  469. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  470. return [];
  471. }
  472. }
  473. /**
  474. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  475. *
  476. * @return array<int, array<string, mixed>>
  477. */
  478. protected function procuremenEnsureRedisPool(): array
  479. {
  480. $pool = $this->ProcuremenRedis();
  481. if (is_array($pool) && $pool !== []) {
  482. return $pool;
  483. }
  484. static $warmed = false;
  485. if ($warmed) {
  486. return is_array($pool) ? $pool : [];
  487. }
  488. $warmed = true;
  489. return $this->procuremenFetchErpPoolFromDb();
  490. }
  491. /**
  492. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  493. *
  494. * @param array<string, mixed> $row
  495. */
  496. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  497. {
  498. $t = $this->procuremenRowListSortTime($row, $primary);
  499. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  500. return null;
  501. }
  502. $mo = (int)$m[2];
  503. if ($mo < 1 || $mo > 12) {
  504. return null;
  505. }
  506. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  507. }
  508. /**
  509. * @param array<int, array{year:string, months:array}> $sidebar
  510. * @return array<int, array{year:string, months:array}>
  511. */
  512. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  513. {
  514. $ym = trim($ym);
  515. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  516. return $sidebar;
  517. }
  518. foreach ($sidebar as $block) {
  519. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  520. continue;
  521. }
  522. foreach ($block['months'] as $item) {
  523. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  524. return $sidebar;
  525. }
  526. }
  527. }
  528. $y = substr($ym, 0, 4);
  529. $mo = (int)substr($ym, 5, 2);
  530. $sidebar[] = [
  531. 'year' => $y,
  532. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  533. ];
  534. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  535. }
  536. /**
  537. * @param array<int, array{year:string, months:array}> $sidebar
  538. * @return string[]
  539. */
  540. protected function flattenProcuremenSidebarYms(array $sidebar): array
  541. {
  542. $yms = [];
  543. foreach ($sidebar as $block) {
  544. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  545. continue;
  546. }
  547. foreach ($block['months'] as $item) {
  548. if (!is_array($item)) {
  549. continue;
  550. }
  551. $ym = trim((string)($item['ym'] ?? ''));
  552. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  553. $yms[$ym] = true;
  554. }
  555. }
  556. }
  557. return array_keys($yms);
  558. }
  559. /**
  560. * 左侧菜单(协助初选)
  561. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  562. */
  563. protected function GetIndexYearMonths()
  564. {
  565. $ymList = $this->ensureProcuremenPickSidebarYmList();
  566. if ($ymList === []) {
  567. $def = date('Y-m');
  568. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  569. }
  570. return $this->buildYearMonthSidebar($ymList);
  571. }
  572. /**
  573. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  574. *
  575. * @return string[]
  576. */
  577. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  578. {
  579. static $memo = null;
  580. if (!$forceRefresh && is_array($memo)) {
  581. return $memo;
  582. }
  583. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  584. if ($fromDb !== []) {
  585. $this->saveProcuremenSidebarYmList($fromDb);
  586. $memo = $fromDb;
  587. return $memo;
  588. }
  589. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  590. $cached = $this->loadProcuremenSidebarYmList();
  591. if ($cached !== []) {
  592. $memo = $cached;
  593. return $memo;
  594. }
  595. $memo = [date('Y-m')];
  596. return $memo;
  597. }
  598. /**
  599. * @return string[] 形如 2026-07
  600. */
  601. protected function loadProcuremenSidebarYmList(): array
  602. {
  603. try {
  604. $raw = redis()->get('procuremen_redis_yms');
  605. if ($raw === false || $raw === null || $raw === '') {
  606. return [];
  607. }
  608. $decoded = json_decode((string)$raw, true);
  609. if (!is_array($decoded)) {
  610. return [];
  611. }
  612. $out = [];
  613. foreach ($decoded as $ym) {
  614. $ym = trim((string)$ym);
  615. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  616. $out[$ym] = true;
  617. }
  618. }
  619. return array_keys($out);
  620. } catch (\Throwable $e) {
  621. return [];
  622. }
  623. }
  624. /**
  625. * @param string[] $ymList
  626. */
  627. protected function saveProcuremenSidebarYmList(array $ymList): void
  628. {
  629. $out = [];
  630. foreach ($ymList as $ym) {
  631. $ym = trim((string)$ym);
  632. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  633. $out[$ym] = true;
  634. }
  635. }
  636. if ($out === []) {
  637. return;
  638. }
  639. try {
  640. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  641. } catch (\Throwable $e) {
  642. }
  643. }
  644. /**
  645. * @param array<int, array<string, mixed>> $pool
  646. * @return string[]
  647. */
  648. protected function extractYearMonthsFromPoolRows(array $pool): array
  649. {
  650. $ymSet = [];
  651. foreach ($pool as $r) {
  652. if (!is_array($r)) {
  653. continue;
  654. }
  655. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  656. continue;
  657. }
  658. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  659. if ($ym !== null) {
  660. $ymSet[$ym] = true;
  661. }
  662. }
  663. return array_keys($ymSet);
  664. }
  665. /**
  666. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  667. *
  668. * @return string[]
  669. */
  670. protected function queryProcuremenPickSidebarYmListLight(): array
  671. {
  672. try {
  673. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  674. $endTime = date('Y-m-d 23:59:59');
  675. $sql = 'SELECT DISTINCT DATE_FORMAT('
  676. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  677. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  678. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  679. . ' FROM scydgy a'
  680. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  681. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  682. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  683. $rows = Db::query($sql, [$startTime, $endTime]);
  684. if (!is_array($rows)) {
  685. return [];
  686. }
  687. $out = [];
  688. foreach ($rows as $r) {
  689. $ym = trim((string)($r['ym'] ?? ''));
  690. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  691. $out[$ym] = true;
  692. }
  693. }
  694. return array_keys($out);
  695. } catch (\Throwable $e) {
  696. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  697. return [];
  698. }
  699. }
  700. /**
  701. * @return string[] 含当月在内的近 N 个自然月
  702. */
  703. protected function buildRecentCalendarYmList(int $months = 12): array
  704. {
  705. $months = max(1, min(24, $months));
  706. $out = [];
  707. $base = strtotime(date('Y-m-01'));
  708. for ($i = 0; $i < $months; $i++) {
  709. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  710. }
  711. return $out;
  712. }
  713. /**
  714. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  715. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  716. *
  717. * @return array<int, array<string, mixed>>
  718. */
  719. protected function loadPickPoolForYm(string $ym): array
  720. {
  721. $ym = trim($ym);
  722. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  723. return [];
  724. }
  725. $hit = $this->readPickMonthPoolCache($ym);
  726. if ($hit !== null) {
  727. return $hit;
  728. }
  729. return $this->queryPickPoolForYmFromDb($ym);
  730. }
  731. /**
  732. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  733. */
  734. protected function readPickMonthPoolCache(string $ym): ?array
  735. {
  736. try {
  737. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  738. if ($raw === false || $raw === null || $raw === '') {
  739. return null;
  740. }
  741. $decoded = json_decode((string)$raw, true);
  742. if (!is_array($decoded)) {
  743. return null;
  744. }
  745. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  746. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  747. return $decoded['rows'];
  748. }
  749. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  750. if ($decoded === []) {
  751. try {
  752. redis()->del('procuremen_pick_pool:' . $ym);
  753. } catch (\Throwable $e) {
  754. }
  755. return null;
  756. }
  757. if (isset($decoded[0]) && is_array($decoded[0])) {
  758. return $decoded;
  759. }
  760. return null;
  761. } catch (\Throwable $e) {
  762. return null;
  763. }
  764. }
  765. /**
  766. * @param array<int, array<string, mixed>> $rows
  767. */
  768. protected function writePickMonthPoolCache(string $ym, array $rows): void
  769. {
  770. try {
  771. redis()->setex(
  772. 'procuremen_pick_pool:' . $ym,
  773. 600,
  774. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  775. );
  776. } catch (\Throwable $e) {
  777. }
  778. }
  779. /**
  780. * @param array<int, array<string, mixed>> $pool
  781. * @return array<int, array<string, mixed>>
  782. */
  783. protected function filterPoolRowsByYm(array $pool, string $ym): array
  784. {
  785. $out = [];
  786. foreach ($pool as $r) {
  787. if (!is_array($r)) {
  788. continue;
  789. }
  790. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  791. continue;
  792. }
  793. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  794. $out[] = $r;
  795. }
  796. }
  797. return $out;
  798. }
  799. /**
  800. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  801. *
  802. * @return array<int, array<string, mixed>>
  803. */
  804. protected function queryPickPoolForYmFromDb(string $ym): array
  805. {
  806. $monthStart = $ym . '-01 00:00:00';
  807. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  808. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  809. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  810. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  811. try {
  812. $list = Db::table('scydgy')
  813. ->alias('a')
  814. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  815. ->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')
  816. ->where([
  817. 'a.bwjg' => 1,
  818. 'a.iEndBz' => 0,
  819. 'a.iType' => 0,
  820. 'a.iStatus' => 10,
  821. ])
  822. ->where('a.dStamp', '>=', $queryStart)
  823. ->where('a.dStamp', '<=', $queryEnd)
  824. ->order('a.dStamp', 'desc')
  825. ->select();
  826. } catch (\Throwable $e) {
  827. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  828. return [];
  829. }
  830. if (!is_array($list)) {
  831. $list = [];
  832. }
  833. $out = $this->filterPoolRowsByYm($list, $ym);
  834. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  835. $this->writePickMonthPoolCache($ym, $out);
  836. try {
  837. $yms = $this->loadProcuremenSidebarYmList();
  838. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  839. $yms[] = $ym;
  840. $this->saveProcuremenSidebarYmList($yms);
  841. }
  842. } catch (\Throwable $e) {
  843. }
  844. return $out;
  845. }
  846. /**
  847. * 整包写入后拆成按月小缓存,供初选列表秒开
  848. *
  849. * @param array<int, array<string, mixed>> $pool
  850. */
  851. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  852. {
  853. if ($pool === []) {
  854. return;
  855. }
  856. $byYm = [];
  857. foreach ($pool as $r) {
  858. if (!is_array($r)) {
  859. continue;
  860. }
  861. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  862. continue;
  863. }
  864. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  865. if ($rowYm === null) {
  866. continue;
  867. }
  868. $byYm[$rowYm][] = $r;
  869. }
  870. if ($byYm === []) {
  871. return;
  872. }
  873. try {
  874. $redis = redis();
  875. foreach ($byYm as $rowYm => $rows) {
  876. $redis->setex(
  877. 'procuremen_pick_pool:' . $rowYm,
  878. 600,
  879. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  880. );
  881. }
  882. try {
  883. $redis->del('procuremen_pick_hidden_scydgy_v1');
  884. } catch (\Throwable $e) {
  885. }
  886. } catch (\Throwable $e) {
  887. }
  888. }
  889. /**
  890. * 刷新整包后清理近月缓存,避免脏读
  891. */
  892. protected function clearPickMonthPoolCaches(int $months = 24): void
  893. {
  894. try {
  895. $redis = redis();
  896. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  897. try {
  898. $redis->del('procuremen_pick_pool:' . $ym);
  899. } catch (\Throwable $e) {
  900. }
  901. }
  902. } catch (\Throwable $e) {
  903. }
  904. $this->invalidatePickHiddenScydgyCache();
  905. }
  906. /**
  907. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  908. */
  909. protected function invalidatePickHiddenScydgyCache(): void
  910. {
  911. $this->pickHiddenScydgySetCache = null;
  912. try {
  913. redis()->del('procuremen_pick_hidden_scydgy_v1');
  914. } catch (\Throwable $e) {
  915. }
  916. }
  917. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  918. protected function procuremenReleaseSessionLock(): void
  919. {
  920. if (session_status() === PHP_SESSION_ACTIVE) {
  921. @session_write_close();
  922. }
  923. }
  924. /**
  925. * @param string[] $ymList 形如 2026-06
  926. * @return array<int, array{year:string, months:array}>
  927. */
  928. protected function buildYearMonthSidebar(array $ymList): array
  929. {
  930. rsort($ymList, SORT_STRING);
  931. $byYear = [];
  932. foreach ($ymList as $ym) {
  933. $y = substr($ym, 0, 4);
  934. $mo = (int)substr($ym, 5, 2);
  935. if (!isset($byYear[$y])) {
  936. $byYear[$y] = [];
  937. }
  938. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  939. }
  940. krsort($byYear, SORT_NUMERIC);
  941. foreach ($byYear as $y => $items) {
  942. usort($byYear[$y], function ($a, $b) {
  943. return strcmp($b['ym'], $a['ym']);
  944. });
  945. }
  946. $sidebar = [];
  947. foreach ($byYear as $y => $months) {
  948. $sidebar[] = ['year' => $y, 'months' => $months];
  949. }
  950. return $sidebar;
  951. }
  952. /**
  953. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  954. */
  955. protected function GetIssuedOrderYearMonths(string $stage): array
  956. {
  957. $ymSet = [];
  958. try {
  959. $query = Db::table('purchase_order');
  960. $this->applyPurchaseOrderNotDeletedWhere($query);
  961. if ($stage === 'audit') {
  962. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  963. } elseif ($stage === 'confirm') {
  964. $this->applyPurchaseOrderConfirmStageWhere($query);
  965. } else {
  966. return $this->GetIndexYearMonths();
  967. }
  968. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  969. if (is_array($rows)) {
  970. foreach ($rows as $r) {
  971. if (!is_array($r)) {
  972. continue;
  973. }
  974. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  975. if ($ym !== null) {
  976. $ymSet[$ym] = true;
  977. }
  978. }
  979. }
  980. } catch (\Throwable $e) {
  981. $ymSet = [];
  982. }
  983. $ymList = array_keys($ymSet);
  984. if ($ymList === []) {
  985. $def = $this->resolveProcuremenDefaultYm($stage);
  986. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  987. }
  988. return $this->buildYearMonthSidebar($ymList);
  989. }
  990. /**
  991. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  992. */
  993. protected function resolveProcuremenDefaultYm(string $stage): string
  994. {
  995. if ($stage === 'pick') {
  996. $yms = $this->ensureProcuremenPickSidebarYmList();
  997. if ($yms !== []) {
  998. rsort($yms, SORT_STRING);
  999. return $yms[0];
  1000. }
  1001. return date('Y-m');
  1002. }
  1003. try {
  1004. $query = Db::table('purchase_order');
  1005. $this->applyPurchaseOrderNotDeletedWhere($query);
  1006. if ($stage === 'audit') {
  1007. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1008. } elseif ($stage === 'confirm') {
  1009. $this->applyPurchaseOrderConfirmStageWhere($query);
  1010. } else {
  1011. return date('Y-m');
  1012. }
  1013. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1014. if ($latest === null || $latest === '') {
  1015. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1016. }
  1017. $t = $this->formatProcuremenDetailTime($latest);
  1018. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1019. return $m[1] . '-' . $m[2];
  1020. }
  1021. } catch (\Throwable $e) {
  1022. }
  1023. return date('Y-m');
  1024. }
  1025. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1026. {
  1027. $query->whereRaw(
  1028. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  1029. );
  1030. }
  1031. /**
  1032. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1033. */
  1034. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1035. {
  1036. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  1037. $quoted = [];
  1038. foreach ($vals as $v) {
  1039. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1040. }
  1041. if ($quoted === []) {
  1042. $query->whereRaw('1 = 0');
  1043. return;
  1044. }
  1045. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1046. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  1047. }
  1048. /**
  1049. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1050. *
  1051. * @param array<string, mixed> $row
  1052. * @return array<string, mixed>
  1053. */
  1054. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1055. {
  1056. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1057. $pick = trim((string)($row['pick_time'] ?? ''));
  1058. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1059. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1060. $t = trim((string)($row[$key] ?? ''));
  1061. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1062. $row['pick_time'] = $t;
  1063. break;
  1064. }
  1065. }
  1066. }
  1067. return $row;
  1068. }
  1069. /**
  1070. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1071. */
  1072. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1073. {
  1074. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1075. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1076. }
  1077. if ($pool === []) {
  1078. $def = $this->resolveProcuremenDefaultYm($stage);
  1079. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1080. }
  1081. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1082. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1083. return false;
  1084. }
  1085. $monthStart = $ym . '-01 00:00:00';
  1086. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1087. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1088. return $probe !== [];
  1089. };
  1090. if ($tryYm($requestedYm)) {
  1091. return $requestedYm;
  1092. }
  1093. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1094. if ($tryYm($fallback)) {
  1095. return $fallback;
  1096. }
  1097. $bestYm = '';
  1098. $bestTime = '';
  1099. foreach ($pool as $row) {
  1100. if (!is_array($row)) {
  1101. continue;
  1102. }
  1103. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1104. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1105. continue;
  1106. }
  1107. $ymRow = $m[1];
  1108. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1109. $bestTime = $t;
  1110. $bestYm = $ymRow;
  1111. }
  1112. }
  1113. if ($bestYm !== '') {
  1114. return $bestYm;
  1115. }
  1116. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1117. }
  1118. protected function isPurchaseOrderDetailVoid(array $row): bool
  1119. {
  1120. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1121. return true;
  1122. }
  1123. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1124. }
  1125. /**
  1126. * 仅当前有效下发明细(排除废弃归档)
  1127. */
  1128. protected function applyActivePurchaseOrderDetailWhere($query): void
  1129. {
  1130. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1131. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1132. }
  1133. /**
  1134. * @param array<string, mixed> $detailRow
  1135. */
  1136. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1137. {
  1138. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1139. return false;
  1140. }
  1141. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1142. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1143. }
  1144. /**
  1145. * 废弃退回初选:下发明细标记归档,不物理删除
  1146. *
  1147. * @param array<int, int|string> $scydgyIds
  1148. */
  1149. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1150. {
  1151. $ids = [];
  1152. foreach ($scydgyIds as $sid) {
  1153. $n = (int)$sid;
  1154. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1155. $ids[$n] = true;
  1156. }
  1157. }
  1158. if ($ids === []) {
  1159. return;
  1160. }
  1161. $void = ProcuremenStatus::POD_VOID;
  1162. Db::table('purchase_order_detail')
  1163. ->where('scydgy_id', 'in', array_keys($ids))
  1164. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1165. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1166. ->update([
  1167. 'status' => $void,
  1168. 'status_name' => $void,
  1169. ]);
  1170. }
  1171. /**
  1172. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1173. */
  1174. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1175. {
  1176. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1177. $norm = function (string $col) use ($p): string {
  1178. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1179. };
  1180. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1181. $parts = [];
  1182. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1183. if ($key === 'createtime') {
  1184. $parts[] = $createtime;
  1185. } else {
  1186. $parts[] = $norm($key);
  1187. }
  1188. }
  1189. return 'COALESCE(' . implode(', ', $parts) . ')';
  1190. }
  1191. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1192. {
  1193. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1194. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1195. }
  1196. /**
  1197. * @return array<int, array<string, mixed>>
  1198. */
  1199. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1200. {
  1201. $this->ensurePurchaseOrderCzlyqColumn();
  1202. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1203. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1204. try {
  1205. $query = Db::table('purchase_order')->field($fields);
  1206. $this->applyPurchaseOrderNotDeletedWhere($query);
  1207. if ($stage === 'audit') {
  1208. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1209. } elseif ($stage === 'confirm') {
  1210. $this->applyPurchaseOrderConfirmStageWhere($query);
  1211. } else {
  1212. return [];
  1213. }
  1214. $query->order('pick_time', 'desc')->order('id', 'desc');
  1215. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1216. $monthStart = $ym . '-01 00:00:00';
  1217. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1218. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1219. }
  1220. $rows = $query->select();
  1221. } catch (\Throwable $e) {
  1222. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1223. $rows = [];
  1224. }
  1225. return is_array($rows) ? $rows : [];
  1226. }
  1227. /**
  1228. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1229. */
  1230. protected function resolveProcuremenListStage(): string
  1231. {
  1232. $tab = trim((string)$this->request->request('wff_tab', ''));
  1233. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1234. return $tab;
  1235. }
  1236. $action = strtolower((string)$this->request->action());
  1237. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1238. return $action;
  1239. }
  1240. return 'pick';
  1241. }
  1242. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1243. {
  1244. $this->procuremenReleaseSessionLock();
  1245. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1246. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1247. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1248. $indexPhpRoot = $rootTrue . '/index.php';
  1249. }
  1250. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1251. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1252. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1253. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1254. $this->view->assign('defaultYm', $defaultYm);
  1255. $this->view->assign('sidebarYearMonths', $sidebar);
  1256. $this->view->assign('procuremenStage', $stage);
  1257. $this->view->assign('procuremenPageTitle', $pageTitle);
  1258. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1259. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1260. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1261. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1262. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1263. }
  1264. /**
  1265. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1266. *
  1267. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1268. */
  1269. protected function buildProcuremenFilterOptions(string $stage): array
  1270. {
  1271. $buckets = [
  1272. 'czlyq' => [],
  1273. 'CCLBMMC' => [],
  1274. 'cywyxm' => [],
  1275. 'CGYMC' => [],
  1276. ];
  1277. $maxPerField = 300;
  1278. try {
  1279. if ($stage === 'pick') {
  1280. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1281. return $buckets;
  1282. }
  1283. if (in_array($stage, ['audit', 'confirm'], true)) {
  1284. $this->ensurePurchaseOrderCzlyqColumn();
  1285. foreach (array_keys($buckets) as $field) {
  1286. try {
  1287. $query = Db::table('purchase_order')->field($field);
  1288. $this->applyPurchaseOrderNotDeletedWhere($query);
  1289. if ($stage === 'audit') {
  1290. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1291. } else {
  1292. $this->applyPurchaseOrderConfirmStageWhere($query);
  1293. }
  1294. $query->where($field, '<>', '')->whereNotNull($field);
  1295. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1296. if (!is_array($vals)) {
  1297. continue;
  1298. }
  1299. foreach ($vals as $v) {
  1300. $v = trim((string)$v);
  1301. if ($v !== '') {
  1302. $buckets[$field][$v] = $v;
  1303. }
  1304. }
  1305. } catch (\Throwable $e) {
  1306. // 单字段失败不影响其它
  1307. }
  1308. }
  1309. }
  1310. } catch (\Throwable $e) {
  1311. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1312. }
  1313. foreach ($buckets as &$set) {
  1314. if ($set !== []) {
  1315. ksort($set, SORT_STRING);
  1316. }
  1317. }
  1318. unset($set);
  1319. return $buckets;
  1320. }
  1321. /**
  1322. * filter JSON 是否含有效条件
  1323. *
  1324. * @param array<string, mixed> $filterArr
  1325. */
  1326. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1327. {
  1328. foreach ($filterArr as $v) {
  1329. if (is_array($v)) {
  1330. if (array_filter($v, function ($x) {
  1331. return $x !== '' && $x !== null;
  1332. })) {
  1333. return true;
  1334. }
  1335. } elseif ($v !== '' && $v !== null) {
  1336. return true;
  1337. }
  1338. }
  1339. return false;
  1340. }
  1341. /**
  1342. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1343. *
  1344. * @param array<string, mixed> $filterArr
  1345. * @param array<string, mixed> $opArr
  1346. */
  1347. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1348. {
  1349. if ($search !== '') {
  1350. return false;
  1351. }
  1352. foreach ($filterArr as $fk => $fv) {
  1353. if (is_array($fv)) {
  1354. continue;
  1355. }
  1356. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1357. continue;
  1358. }
  1359. if ($fv === null) {
  1360. continue;
  1361. }
  1362. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1363. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1364. if ($sym === '' || $sym === '=') {
  1365. continue;
  1366. }
  1367. return false;
  1368. }
  1369. return true;
  1370. }
  1371. /**
  1372. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1373. *
  1374. * @param array<int, mixed> $rows
  1375. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1376. */
  1377. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1378. {
  1379. $buckets = [
  1380. 'czlyq' => [],
  1381. 'CCLBMMC' => [],
  1382. 'cywyxm' => [],
  1383. 'CGYMC' => [],
  1384. ];
  1385. foreach ($rows as $r) {
  1386. if (!is_array($r)) {
  1387. continue;
  1388. }
  1389. foreach ($buckets as $field => &$set) {
  1390. if (count($set) >= $maxPerField) {
  1391. continue;
  1392. }
  1393. $v = trim((string)($r[$field] ?? ''));
  1394. if ($v !== '') {
  1395. $set[$v] = $v;
  1396. }
  1397. }
  1398. unset($set);
  1399. $full = true;
  1400. foreach ($buckets as $set) {
  1401. if (count($set) < $maxPerField) {
  1402. $full = false;
  1403. break;
  1404. }
  1405. }
  1406. if ($full) {
  1407. break;
  1408. }
  1409. }
  1410. foreach ($buckets as &$set) {
  1411. if ($set !== []) {
  1412. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1413. $normalized = [];
  1414. foreach ($set as $k => $v) {
  1415. $s = trim((string)(is_scalar($v) ? $v : $k));
  1416. if ($s === '') {
  1417. continue;
  1418. }
  1419. $normalized[$s] = $s;
  1420. }
  1421. ksort($normalized, SORT_STRING);
  1422. $set = $normalized;
  1423. }
  1424. }
  1425. unset($set);
  1426. return $buckets;
  1427. }
  1428. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1429. public function pick()
  1430. {
  1431. $this->request->filter(['strip_tags', 'trim']);
  1432. if (!$this->request->isAjax()) {
  1433. $this->assignProcuremenListPage('pick', '协助下发');
  1434. return $this->view->fetch('procuremen/index');
  1435. }
  1436. return $this->index();
  1437. }
  1438. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1439. public function audit()
  1440. {
  1441. $this->request->filter(['strip_tags', 'trim']);
  1442. if (!$this->request->isAjax()) {
  1443. $this->assignProcuremenListPage('audit', '确认供应商');
  1444. return $this->view->fetch('procuremen/index');
  1445. }
  1446. return $this->index();
  1447. }
  1448. /** 采购确认(定标) */
  1449. public function confirm()
  1450. {
  1451. $this->request->filter(['strip_tags', 'trim']);
  1452. if (!$this->request->isAjax()) {
  1453. $this->assignProcuremenListPage('confirm', '采购确认');
  1454. return $this->view->fetch('procuremen/index');
  1455. }
  1456. return $this->index();
  1457. }
  1458. /**
  1459. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1460. */
  1461. public function index()
  1462. {
  1463. $this->request->filter(['strip_tags', 'trim']);
  1464. if (!$this->request->isAjax()) {
  1465. $this->assignProcuremenListPage('pick', '协助下发');
  1466. return $this->view->fetch('procuremen/index');
  1467. }
  1468. if ($this->request->request('keyField')) {
  1469. return $this->selectpage();
  1470. }
  1471. $this->procuremenReleaseSessionLock();
  1472. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1473. $limit = max(10, min(500, (int)$limit));
  1474. $ym = $this->request->request('ym', '');
  1475. $ym = is_string($ym) ? trim($ym) : '';
  1476. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1477. $wffTab = $this->resolveProcuremenListStage();
  1478. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1479. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1480. ? $this->resolveProcuremenDefaultYm($wffTab)
  1481. : date('Y-m');
  1482. }
  1483. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1484. $ym = date('Y-m');
  1485. }
  1486. $monthStart = $ym . '-01 00:00:00';
  1487. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1488. $search = trim((string)$this->request->get('search', ''));
  1489. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1490. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1491. if (!is_array($filterArr)) {
  1492. $filterArr = [];
  1493. }
  1494. if (!is_array($opArr)) {
  1495. $opArr = [];
  1496. }
  1497. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1498. $bidOpenStatusFilter = '';
  1499. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1500. if (!array_key_exists($bidFk, $filterArr)) {
  1501. continue;
  1502. }
  1503. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1504. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1505. }
  1506. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1507. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1508. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1509. try {
  1510. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1511. if ($wffTab === 'audit') {
  1512. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1513. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1514. );
  1515. } elseif ($wffTab === 'confirm') {
  1516. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1517. if ($dbRows === []) {
  1518. try {
  1519. $dbRows = Db::table('purchase_order')
  1520. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1521. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1522. ->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%\')')
  1523. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1524. ->order('pick_time', 'desc')->order('id', 'desc')
  1525. ->select();
  1526. } catch (\Throwable $e) {
  1527. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1528. $dbRows = [];
  1529. }
  1530. }
  1531. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1532. if ($pool === []) {
  1533. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1534. }
  1535. } else {
  1536. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1537. if ($applyMonthRange) {
  1538. $pool = $this->loadPickPoolForYm($ym);
  1539. } else {
  1540. $pool = $this->procuremenEnsureRedisPool();
  1541. }
  1542. if (!is_array($pool)) {
  1543. $pool = [];
  1544. }
  1545. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1546. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1547. if ($pool !== [] && $hideSet !== []) {
  1548. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1549. if (!is_array($r)) {
  1550. return false;
  1551. }
  1552. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1553. return $id <= 0 || !isset($hideSet[$id]);
  1554. }));
  1555. }
  1556. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1557. if ($pool === []) {
  1558. return json([
  1559. 'total' => 0,
  1560. 'rows' => [],
  1561. 'activeYm' => $ym,
  1562. 'filterOptions' => (
  1563. (int)$offset === 0
  1564. && !$hasActiveSearch
  1565. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1566. )
  1567. ? $this->extractProcuremenFilterOptionsFromRows([])
  1568. : new \stdClass(),
  1569. ]);
  1570. }
  1571. }
  1572. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1573. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1574. $monthStart = $ym . '-01 00:00:00';
  1575. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1576. }
  1577. $filtered = $this->filterProcuremenIndexPool(
  1578. $pool,
  1579. $monthStart,
  1580. $monthEnd,
  1581. $applyMonthRange,
  1582. $search,
  1583. $filterArr,
  1584. $opArr,
  1585. $listTimePrimary
  1586. );
  1587. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1588. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1589. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1590. }
  1591. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1592. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1593. }
  1594. $sortField = 'ID';
  1595. if (is_string($sort) && $sort !== '') {
  1596. $parts = explode(',', $sort);
  1597. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1598. if ($sortField === '') {
  1599. $sortField = 'ID';
  1600. }
  1601. }
  1602. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1603. $nFiltered = count($filtered);
  1604. if ($nFiltered > 1) {
  1605. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1606. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1607. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1608. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1609. if ($ta === $tb) {
  1610. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1611. }
  1612. if ($ta === '') {
  1613. return 1;
  1614. }
  1615. if ($tb === '') {
  1616. return -1;
  1617. }
  1618. return strcmp($ta, $tb) * $ord;
  1619. });
  1620. } elseif ($sortField === 'ID') {
  1621. $sortKeys = [];
  1622. foreach ($filtered as $i => $row) {
  1623. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1624. }
  1625. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1626. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1627. } elseif ($sortField === 'CCYDH') {
  1628. usort($filtered, function ($a, $b) use ($ord) {
  1629. $sa = trim((string)($a['CCYDH'] ?? ''));
  1630. $sb = trim((string)($b['CCYDH'] ?? ''));
  1631. if ($sa === $sb) {
  1632. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1633. }
  1634. if ($sa === '') {
  1635. return 1;
  1636. }
  1637. if ($sb === '') {
  1638. return -1;
  1639. }
  1640. return strcmp($sa, $sb) * $ord;
  1641. });
  1642. } else {
  1643. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1644. $va = $a[$sortField] ?? null;
  1645. $vb = $b[$sortField] ?? null;
  1646. $sa = (string)$va;
  1647. $sb = (string)$vb;
  1648. if ($sa === $sb) {
  1649. return 0;
  1650. }
  1651. return strcmp($sa, $sb) * $ord;
  1652. });
  1653. }
  1654. }
  1655. $offset = max(0, (int)$offset);
  1656. $limit = max(1, (int)$limit);
  1657. $rows = array_slice($filtered, $offset, $limit);
  1658. foreach ($rows as &$rw) {
  1659. if (!is_array($rw)) {
  1660. continue;
  1661. }
  1662. $rid = (int)($rw['ID'] ?? 0);
  1663. $rw['_iss_out'] = ($wffTab !== 'pick');
  1664. }
  1665. unset($rw);
  1666. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1667. $idList = [];
  1668. foreach ($rows as $rw) {
  1669. if (!is_array($rw)) {
  1670. continue;
  1671. }
  1672. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1673. foreach ($rw['_order_merge_rows'] as $mr) {
  1674. $mid = (int)($mr['ID'] ?? 0);
  1675. if ($this->isValidScydgyRowId($mid)) {
  1676. $idList[$mid] = true;
  1677. }
  1678. }
  1679. }
  1680. $id = (int)($rw['ID'] ?? 0);
  1681. if ($this->isValidScydgyRowId($id)) {
  1682. $idList[$id] = true;
  1683. }
  1684. }
  1685. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1686. foreach ($rows as &$rw) {
  1687. if (!is_array($rw)) {
  1688. continue;
  1689. }
  1690. $mergeIds = [];
  1691. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1692. foreach ($rw['_order_merge_rows'] as $mr) {
  1693. $mid = (int)($mr['ID'] ?? 0);
  1694. if ($this->isValidScydgyRowId($mid)) {
  1695. $mergeIds[$mid] = true;
  1696. }
  1697. }
  1698. }
  1699. $rid = (int)($rw['ID'] ?? 0);
  1700. if ($this->isValidScydgyRowId($rid)) {
  1701. $mergeIds[$rid] = true;
  1702. }
  1703. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1704. $rw['po_detail_count'] = $s['cnt'];
  1705. $rw['po_amount_fill_cnt'] = $s['amt'];
  1706. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1707. }
  1708. unset($rw);
  1709. }
  1710. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1711. $idList = [];
  1712. foreach ($rows as $rw) {
  1713. if (!is_array($rw)) {
  1714. continue;
  1715. }
  1716. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1717. foreach ($rw['_order_merge_rows'] as $mr) {
  1718. $mid = (int)($mr['ID'] ?? 0);
  1719. if ($this->isValidScydgyRowId($mid)) {
  1720. $idList[$mid] = true;
  1721. }
  1722. }
  1723. }
  1724. $id = (int)($rw['ID'] ?? 0);
  1725. if ($this->isValidScydgyRowId($id)) {
  1726. $idList[$id] = true;
  1727. }
  1728. }
  1729. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1730. $bidOpenSet = [];
  1731. $manualPickSet = [];
  1732. if ($wffTab === 'audit') {
  1733. $ccydhList = [];
  1734. foreach ($rows as $rw0) {
  1735. if (!is_array($rw0)) {
  1736. continue;
  1737. }
  1738. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1739. if ($c0 !== '') {
  1740. $ccydhList[] = $c0;
  1741. }
  1742. }
  1743. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1744. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1745. }
  1746. foreach ($rows as &$rw) {
  1747. if (!is_array($rw)) {
  1748. continue;
  1749. }
  1750. $mergeIds = [];
  1751. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1752. foreach ($rw['_order_merge_rows'] as $mr) {
  1753. $mid = (int)($mr['ID'] ?? 0);
  1754. if ($this->isValidScydgyRowId($mid)) {
  1755. $mergeIds[$mid] = true;
  1756. }
  1757. }
  1758. }
  1759. $rid = (int)($rw['ID'] ?? 0);
  1760. if ($this->isValidScydgyRowId($rid)) {
  1761. $mergeIds[$rid] = true;
  1762. }
  1763. $buckets = [];
  1764. foreach (array_keys($mergeIds) as $mid) {
  1765. if (isset($quoteBucket[$mid])) {
  1766. $buckets[] = $quoteBucket[$mid];
  1767. }
  1768. }
  1769. $supplierText = $buckets !== []
  1770. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1771. : '';
  1772. if ($wffTab === 'confirm') {
  1773. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1774. if ($picked === '') {
  1775. // 兜底:从合并工序行取
  1776. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1777. foreach ($rw['_order_merge_rows'] as $mr) {
  1778. if (!is_array($mr)) {
  1779. continue;
  1780. }
  1781. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1782. if ($pn !== '') {
  1783. $picked = $pn;
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. }
  1789. $rw['picked_supplier_name'] = $picked;
  1790. } else {
  1791. $rw['notify_supplier_text'] = $supplierText;
  1792. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1793. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1794. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1795. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1796. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1797. if ($verified) {
  1798. $rw['bid_open_status_text'] = '已开标';
  1799. } elseif ($manualPicked) {
  1800. $rw['bid_open_status_text'] = '已指定供应商';
  1801. } else {
  1802. $rw['bid_open_status_text'] = '待开标';
  1803. }
  1804. }
  1805. }
  1806. unset($rw);
  1807. }
  1808. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1809. $this->enrichProcuremenListMilestoneTimes($rows);
  1810. $this->syncCollapsedOrderQtyPriceForList($rows);
  1811. }
  1812. if ($wffTab === 'all' && count($rows) > 0) {
  1813. $this->mergePurchaseOrder($rows);
  1814. }
  1815. if ($wffTab === 'pick' && count($rows) > 0) {
  1816. $this->mergePurchaseOrder($rows);
  1817. }
  1818. foreach ($rows as &$rwClean) {
  1819. if (is_array($rwClean)) {
  1820. unset($rwClean['_order_merge_rows']);
  1821. if (array_key_exists('NGZL', $rwClean)) {
  1822. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1823. }
  1824. }
  1825. }
  1826. unset($rwClean);
  1827. return json([
  1828. 'total' => count($filtered),
  1829. 'rows' => $rows,
  1830. 'activeYm' => $ym,
  1831. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1832. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1833. ? $this->ensureProcuremenPickSidebarYmList()
  1834. : [],
  1835. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1836. 'filterOptions' => (
  1837. (int)$offset === 0
  1838. && !$hasActiveSearch
  1839. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1840. )
  1841. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1842. : new \stdClass(),
  1843. ]);
  1844. } catch (\Throwable $e) {
  1845. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1846. return json([
  1847. 'total' => 0,
  1848. 'rows' => [],
  1849. ]);
  1850. }
  1851. }
  1852. /**
  1853. * @param array<int, array<string, mixed>> $pool
  1854. * @return int[]
  1855. */
  1856. protected function extractScydgyIdsFromPool(array $pool): array
  1857. {
  1858. $ids = [];
  1859. foreach ($pool as $r) {
  1860. if (!is_array($r)) {
  1861. continue;
  1862. }
  1863. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1864. if ($id > 0) {
  1865. $ids[$id] = $id;
  1866. }
  1867. }
  1868. return array_values($ids);
  1869. }
  1870. /**
  1871. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1872. *
  1873. * @param int[] $scydgyIds
  1874. * @return array<int, true>
  1875. */
  1876. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1877. {
  1878. $hideSet = [];
  1879. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1880. return $id > 0;
  1881. }));
  1882. if ($scydgyIds === []) {
  1883. return $hideSet;
  1884. }
  1885. // 分批,避免 whereIn 过长
  1886. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1887. try {
  1888. $poIds = Db::table('purchase_order')
  1889. ->where('scydgy_id', 'in', $chunk)
  1890. ->where(function ($q) {
  1891. $q->whereIn('wflow_status', array_merge(
  1892. ProcuremenStatus::wflowPendingConfirmValues(),
  1893. ProcuremenStatus::wflowPendingApprovalValues()
  1894. ))
  1895. ->whereOr(function ($q1) {
  1896. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1897. })
  1898. ->whereOr(function ($q2) {
  1899. $q2->whereNotNull('pick_time')
  1900. ->where('pick_time', '<>', '')
  1901. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1902. })
  1903. ->whereOr(function ($q3) {
  1904. $q3->whereNotNull('mod_rq')
  1905. ->where('mod_rq', '<>', '')
  1906. ->where('mod_rq', 'not like', '0000-00-00%');
  1907. });
  1908. })
  1909. ->column('scydgy_id');
  1910. if (is_array($poIds)) {
  1911. foreach ($poIds as $pid) {
  1912. $k = (int)$pid;
  1913. if ($k !== 0) {
  1914. $hideSet[$k] = true;
  1915. }
  1916. }
  1917. }
  1918. } catch (\Throwable $e) {
  1919. }
  1920. try {
  1921. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1922. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1923. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1924. if (is_array($detIds)) {
  1925. foreach ($detIds as $pid) {
  1926. $k = (int)$pid;
  1927. if ($this->isValidScydgyRowId($k)) {
  1928. $hideSet[$k] = true;
  1929. }
  1930. }
  1931. }
  1932. } catch (\Throwable $e) {
  1933. }
  1934. }
  1935. return $hideSet;
  1936. }
  1937. /**
  1938. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1939. *
  1940. * @return array<int, true>
  1941. */
  1942. protected function loadPickHiddenScydgySet(): array
  1943. {
  1944. if ($this->pickHiddenScydgySetCache !== null) {
  1945. return $this->pickHiddenScydgySetCache;
  1946. }
  1947. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1948. try {
  1949. $raw = redis()->get($cacheKey);
  1950. if ($raw !== false && $raw !== null && $raw !== '') {
  1951. $ids = json_decode((string)$raw, true);
  1952. if (is_array($ids)) {
  1953. $hideSet = [];
  1954. foreach ($ids as $pid) {
  1955. $k = (int)$pid;
  1956. if ($k !== 0) {
  1957. $hideSet[$k] = true;
  1958. }
  1959. }
  1960. $this->pickHiddenScydgySetCache = $hideSet;
  1961. return $hideSet;
  1962. }
  1963. }
  1964. } catch (\Throwable $e) {
  1965. }
  1966. $hideSet = [];
  1967. try {
  1968. $poIds = Db::table('purchase_order')
  1969. ->where(function ($q) {
  1970. $q->whereIn('wflow_status', array_merge(
  1971. ProcuremenStatus::wflowPendingConfirmValues(),
  1972. ProcuremenStatus::wflowPendingApprovalValues()
  1973. ))
  1974. ->whereOr(function ($q1) {
  1975. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1976. })
  1977. ->whereOr(function ($q2) {
  1978. $q2->whereNotNull('pick_time')
  1979. ->where('pick_time', '<>', '')
  1980. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1981. })
  1982. ->whereOr(function ($q3) {
  1983. $q3->whereNotNull('mod_rq')
  1984. ->where('mod_rq', '<>', '')
  1985. ->where('mod_rq', 'not like', '0000-00-00%');
  1986. });
  1987. })
  1988. ->column('scydgy_id');
  1989. if (is_array($poIds)) {
  1990. foreach ($poIds as $pid) {
  1991. $k = (int)$pid;
  1992. if ($k !== 0) {
  1993. $hideSet[$k] = true;
  1994. }
  1995. }
  1996. }
  1997. } catch (\Throwable $e) {
  1998. }
  1999. try {
  2000. $detIdsQuery = Db::table('purchase_order_detail');
  2001. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2002. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2003. if (is_array($detIds)) {
  2004. foreach ($detIds as $pid) {
  2005. $k = (int)$pid;
  2006. if ($this->isValidScydgyRowId($k)) {
  2007. $hideSet[$k] = true;
  2008. }
  2009. }
  2010. }
  2011. } catch (\Throwable $e) {
  2012. }
  2013. $this->pickHiddenScydgySetCache = $hideSet;
  2014. try {
  2015. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2016. } catch (\Throwable $e) {
  2017. }
  2018. return $hideSet;
  2019. }
  2020. /**
  2021. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2022. *
  2023. * @return array<int, array<string, mixed>>
  2024. */
  2025. protected function loadPickManualOrderRows(): array
  2026. {
  2027. try {
  2028. $dbRows = Db::table('purchase_order')
  2029. ->where('scydgy_id', '<', 0)
  2030. ->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%\')')
  2031. ->order('scydgy_id', 'asc')
  2032. ->select();
  2033. } catch (\Throwable $e) {
  2034. try {
  2035. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2036. } catch (\Throwable $e2) {
  2037. return [];
  2038. }
  2039. }
  2040. if (!is_array($dbRows) || $dbRows === []) {
  2041. return [];
  2042. }
  2043. $detailSidSet = [];
  2044. try {
  2045. $negIds = [];
  2046. foreach ($dbRows as $dbRow) {
  2047. if (!is_array($dbRow)) {
  2048. continue;
  2049. }
  2050. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2051. if ($sid < 0) {
  2052. $negIds[$sid] = true;
  2053. }
  2054. }
  2055. if ($negIds !== []) {
  2056. $detQuery = Db::table('purchase_order_detail')
  2057. ->where('scydgy_id', 'in', array_keys($negIds));
  2058. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2059. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2060. if (is_array($detRows)) {
  2061. foreach ($detRows as $did) {
  2062. $detailSidSet[(int)$did] = true;
  2063. }
  2064. }
  2065. }
  2066. } catch (\Throwable $e) {
  2067. }
  2068. $pool = [];
  2069. foreach ($dbRows as $dbRow) {
  2070. if (!is_array($dbRow)) {
  2071. continue;
  2072. }
  2073. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2074. if ($sid >= 0) {
  2075. continue;
  2076. }
  2077. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2078. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2079. continue;
  2080. }
  2081. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2082. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2083. continue;
  2084. }
  2085. if (isset($detailSidSet[$sid])) {
  2086. continue;
  2087. }
  2088. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2089. $r['_is_manual'] = 1;
  2090. $pool[] = $r;
  2091. }
  2092. return $pool;
  2093. }
  2094. /**
  2095. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2096. */
  2097. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2098. {
  2099. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2100. foreach ($keys as $k) {
  2101. $t = trim((string)($row[$k] ?? ''));
  2102. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2103. return $t;
  2104. }
  2105. }
  2106. return '';
  2107. }
  2108. /**
  2109. * 分配手工新增工序行 ID(负数递减)
  2110. * 调用方须在命名锁内执行,避免并发重复
  2111. */
  2112. protected function allocateManualScydgyId(): int
  2113. {
  2114. try {
  2115. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2116. $min = (int)$min;
  2117. return $min < 0 ? $min - 1 : -1;
  2118. } catch (\Throwable $e) {
  2119. return -1;
  2120. }
  2121. }
  2122. /**
  2123. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2124. * 调用方须在命名锁内执行,避免并发重复
  2125. */
  2126. protected function allocateManualOrderCcydh(): string
  2127. {
  2128. $prefix = 'YW' . date('Ymd');
  2129. $maxSeq = 0;
  2130. try {
  2131. $rows = Db::table('purchase_order')
  2132. ->where('CCYDH', 'like', $prefix . '%')
  2133. ->column('CCYDH');
  2134. if (is_array($rows)) {
  2135. foreach ($rows as $ccydh) {
  2136. $ccydh = trim((string)$ccydh);
  2137. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2138. $maxSeq = max($maxSeq, (int)$m[1]);
  2139. }
  2140. }
  2141. }
  2142. } catch (\Throwable $e) {
  2143. }
  2144. $next = $maxSeq + 1;
  2145. $width = $next > 999 ? strlen((string)$next) : 3;
  2146. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2147. }
  2148. /**
  2149. * MySQL 命名锁(跨连接防并发撞号)
  2150. */
  2151. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2152. {
  2153. $name = trim($name);
  2154. if ($name === '') {
  2155. return false;
  2156. }
  2157. try {
  2158. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2159. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2160. if (!is_array($rows) || $rows === []) {
  2161. return false;
  2162. }
  2163. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2164. return (int)$v === 1;
  2165. } catch (\Throwable $e) {
  2166. return false;
  2167. }
  2168. }
  2169. protected function releaseProcuremenNamedLock(string $name): void
  2170. {
  2171. $name = trim($name);
  2172. if ($name === '') {
  2173. return;
  2174. }
  2175. try {
  2176. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2177. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2178. } catch (\Throwable $e) {
  2179. }
  2180. }
  2181. /**
  2182. * purchase_order.mod_rq 是否有有效软删除时间
  2183. */
  2184. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2185. {
  2186. $t = trim((string)$modRq);
  2187. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2188. }
  2189. /**
  2190. * 列表行 → purchase_order 写入字段
  2191. *
  2192. * @return array<string, mixed>
  2193. */
  2194. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2195. {
  2196. return $this->normalizePurchaseOrderWritePayload([
  2197. 'scydgy_id' => $scydgyId,
  2198. 'CCYDH' => $row['CCYDH'] ?? null,
  2199. 'CYJMC' => $row['CYJMC'] ?? null,
  2200. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2201. 'CDXMC' => $row['CDXMC'] ?? null,
  2202. 'CGYBH' => $row['CGYBH'] ?? null,
  2203. 'CGYMC' => $row['CGYMC'] ?? null,
  2204. 'CDW' => $row['CDW'] ?? null,
  2205. 'czlyq' => $row['czlyq'] ?? null,
  2206. 'NGZL' => $row['NGZL'] ?? null,
  2207. 'CDF' => $row['CDF'] ?? null,
  2208. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2209. 'MBZ' => $row['MBZ'] ?? null,
  2210. 'bwjg' => $row['bwjg'] ?? null,
  2211. 'iStatus' => $row['iStatus'] ?? null,
  2212. 'dStamp' => $row['dStamp'] ?? null,
  2213. 'dputrecord' => $row['dputrecord'] ?? null,
  2214. 'cywyxm' => $row['cywyxm'] ?? null,
  2215. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2216. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2217. ], $row);
  2218. }
  2219. /**
  2220. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2221. *
  2222. * @param array<string, mixed> $data
  2223. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2224. * @return array<string, mixed>
  2225. */
  2226. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2227. {
  2228. $this->ensurePurchaseOrderCzlyqColumn();
  2229. $cz = '';
  2230. foreach (['czlyq', 'CZLYQ'] as $k) {
  2231. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2232. $cz = trim((string)$data[$k]);
  2233. break;
  2234. }
  2235. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2236. $cz = trim((string)$row[$k]);
  2237. break;
  2238. }
  2239. }
  2240. if ($cz === '') {
  2241. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2242. if ($ccydh !== '') {
  2243. try {
  2244. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2245. $cz = trim((string)$fromMcyd);
  2246. } catch (\Throwable $e) {
  2247. $cz = '';
  2248. }
  2249. }
  2250. }
  2251. $data['czlyq'] = $cz;
  2252. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2253. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2254. if (!array_key_exists($col, $data)) {
  2255. continue;
  2256. }
  2257. if ($data[$col] === null || !is_scalar($data[$col])) {
  2258. $data[$col] = '';
  2259. } else {
  2260. $data[$col] = (string)$data[$col];
  2261. }
  2262. }
  2263. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2264. if (array_key_exists($col, $data) && $data[$col] === null) {
  2265. $data[$col] = 0;
  2266. }
  2267. }
  2268. return $data;
  2269. }
  2270. /**
  2271. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2272. *
  2273. * @return array{po:?array<string,mixed>, hidden:bool}
  2274. */
  2275. protected function resolvePickRowPoContext(int $sid): array
  2276. {
  2277. $po = null;
  2278. try {
  2279. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2280. if (is_array($found)) {
  2281. $po = $found;
  2282. }
  2283. } catch (\Throwable $e) {
  2284. }
  2285. $hideSet = $this->loadPickHiddenScydgySet();
  2286. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2287. }
  2288. /**
  2289. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2290. */
  2291. protected function assertPickRowCanDelete(int $sid, array $row): void
  2292. {
  2293. $ctx = $this->resolvePickRowPoContext($sid);
  2294. $po = $ctx['po'];
  2295. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2296. return;
  2297. }
  2298. if (is_array($po)) {
  2299. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2300. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2301. }
  2302. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2303. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2304. }
  2305. }
  2306. if ($ctx['hidden']) {
  2307. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2308. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2309. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2310. }
  2311. }
  2312. /**
  2313. * 初选直接完结前校验
  2314. */
  2315. protected function assertPickRowCanComplete(int $sid, array $row): void
  2316. {
  2317. $ctx = $this->resolvePickRowPoContext($sid);
  2318. $po = $ctx['po'];
  2319. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2320. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2321. }
  2322. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2323. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2324. }
  2325. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2326. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2327. }
  2328. }
  2329. /**
  2330. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2331. */
  2332. protected function softDeleteProcuremenPickRow(array $row): void
  2333. {
  2334. $sid = $this->extractScydgyRowId($row);
  2335. if (!$this->isValidScydgyRowId($sid)) {
  2336. throw new \InvalidArgumentException('无效的行主键');
  2337. }
  2338. $this->assertPickRowCanDelete($sid, $row);
  2339. $po = $this->resolvePickRowPoContext($sid)['po'];
  2340. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2341. return;
  2342. }
  2343. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2344. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2345. }
  2346. $now = date('Y-m-d H:i:s');
  2347. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2348. if (is_array($exists)) {
  2349. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2350. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2351. } else {
  2352. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2353. $data['mod_rq'] = $now;
  2354. $data['createtime'] = $now;
  2355. Db::table('purchase_order')->insert($data);
  2356. $poIdLog = (int)Db::getLastInsID();
  2357. }
  2358. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2359. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2360. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2361. if ($gymcLog !== '') {
  2362. $logTail .= ' / ' . $gymcLog;
  2363. }
  2364. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2365. }
  2366. /**
  2367. * 手工新增协助工序(写入 purchase_order)
  2368. *
  2369. * @param array<string, mixed> $params
  2370. * @return int scydgy_id
  2371. */
  2372. protected function saveManualPickOrder(array $params): int
  2373. {
  2374. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2375. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2376. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2377. $lockName = 'procuremen_manual_order_alloc';
  2378. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2379. throw new \RuntimeException('系统繁忙,请稍后重试');
  2380. }
  2381. try {
  2382. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2383. $now = date('Y-m-d H:i:s');
  2384. $sid = $this->allocateManualScydgyId();
  2385. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2386. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2387. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2388. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2389. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2390. $data = [
  2391. 'scydgy_id' => $sid,
  2392. 'CCYDH' => $ccydh,
  2393. 'CYJMC' => $cyjmc,
  2394. 'CGYMC' => $cgymc,
  2395. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2396. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2397. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2398. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2399. 'cGzzxMc' => $supplierName,
  2400. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2401. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2402. 'notify_salesman' => $notifySalesman,
  2403. 'rfq_salesman_notified' => 0,
  2404. 'rfq_salesman_notify_time' => null,
  2405. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2406. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2407. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2408. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2409. 'createtime' => $now,
  2410. 'dStamp' => $now,
  2411. 'dputrecord' => $now,
  2412. ];
  2413. Db::table('purchase_order')->insert($data);
  2414. $poId = (int)Db::getLastInsID();
  2415. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2416. return $sid;
  2417. } finally {
  2418. $this->releaseProcuremenNamedLock($lockName);
  2419. }
  2420. }
  2421. protected function formatProcuremenRowLabel(array $row): string
  2422. {
  2423. $dh = trim((string)($row['CCYDH'] ?? ''));
  2424. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2425. if ($dh !== '' && $gymc !== '') {
  2426. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2427. }
  2428. if ($dh !== '') {
  2429. return '订单「' . $dh . '」';
  2430. }
  2431. if ($gymc !== '') {
  2432. return '工序「' . $gymc . '」';
  2433. }
  2434. $id = $this->extractScydgyRowId($row);
  2435. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2436. }
  2437. /**
  2438. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2439. */
  2440. protected function extractScydgyRowId(array $row): int
  2441. {
  2442. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2443. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2444. return (int)$row['scydgy_id'];
  2445. }
  2446. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2447. return (int)$row['SCYDGY_ID'];
  2448. }
  2449. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2450. }
  2451. protected function isValidScydgyRowId(int $id): bool
  2452. {
  2453. return ProcuremenGuard::isValidScydgyId($id);
  2454. }
  2455. protected function isManualScydgyRowId(int $id): bool
  2456. {
  2457. return $id < 0;
  2458. }
  2459. /**
  2460. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2461. *
  2462. * @param int[] $scydgyIds
  2463. * @return array<int, string[]>
  2464. */
  2465. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2466. {
  2467. $out = [];
  2468. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2469. if ($scydgyIds === []) {
  2470. return $out;
  2471. }
  2472. try {
  2473. $rows = Db::table('purchase_order_detail')
  2474. ->where('scydgy_id', 'in', $scydgyIds)
  2475. ->field('scydgy_id,company_name')
  2476. ->order('company_name', 'asc')
  2477. ->select();
  2478. } catch (\Throwable $e) {
  2479. $rows = [];
  2480. }
  2481. if (!is_array($rows)) {
  2482. return $out;
  2483. }
  2484. foreach ($rows as $r) {
  2485. if (!is_array($r)) {
  2486. continue;
  2487. }
  2488. $sid = (int)($r['scydgy_id'] ?? 0);
  2489. $cn = trim((string)($r['company_name'] ?? ''));
  2490. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2491. continue;
  2492. }
  2493. if (!isset($out[$sid])) {
  2494. $out[$sid] = [];
  2495. }
  2496. if (!in_array($cn, $out[$sid], true)) {
  2497. $out[$sid][] = $cn;
  2498. }
  2499. }
  2500. return $out;
  2501. }
  2502. /**
  2503. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2504. *
  2505. * @param string[] $names
  2506. */
  2507. protected function formatNotifySupplierDisplay(array $names): string
  2508. {
  2509. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2510. return trim((string)$n);
  2511. }, $names))));
  2512. if ($names === []) {
  2513. return '';
  2514. }
  2515. sort($names, SORT_STRING);
  2516. return implode("\n", $names);
  2517. }
  2518. /**
  2519. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2520. *
  2521. * @param int[] $scydgyIds
  2522. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2523. */
  2524. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2525. {
  2526. $out = [];
  2527. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2528. if ($scydgyIds === []) {
  2529. return $out;
  2530. }
  2531. try {
  2532. $rows = Db::table('purchase_order_detail')
  2533. ->where('scydgy_id', 'in', $scydgyIds)
  2534. ->field('scydgy_id,company_name,amount')
  2535. ->select();
  2536. } catch (\Throwable $e) {
  2537. $rows = [];
  2538. }
  2539. if (!is_array($rows)) {
  2540. return $out;
  2541. }
  2542. foreach ($rows as $r) {
  2543. if (!is_array($r)) {
  2544. continue;
  2545. }
  2546. $sid = (int)($r['scydgy_id'] ?? 0);
  2547. $cn = trim((string)($r['company_name'] ?? ''));
  2548. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2549. continue;
  2550. }
  2551. if (!isset($out[$sid])) {
  2552. $out[$sid] = ['all' => [], 'quoted' => []];
  2553. }
  2554. $out[$sid]['all'][$cn] = true;
  2555. $am = trim((string)($r['amount'] ?? ''));
  2556. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2557. $out[$sid]['quoted'][$cn] = true;
  2558. }
  2559. }
  2560. return $out;
  2561. }
  2562. /**
  2563. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2564. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2565. */
  2566. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2567. {
  2568. $merged = ['all' => [], 'quoted' => []];
  2569. foreach ($buckets as $b) {
  2570. if (!is_array($b)) {
  2571. continue;
  2572. }
  2573. foreach ($b['all'] ?? [] as $cn => $_) {
  2574. $merged['all'][$cn] = true;
  2575. }
  2576. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2577. $merged['quoted'][$cn] = true;
  2578. }
  2579. }
  2580. return $merged;
  2581. }
  2582. /**
  2583. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2584. */
  2585. protected function formatQuotedSupplierLines(array $bucket): string
  2586. {
  2587. $all = array_keys($bucket['all'] ?? []);
  2588. if ($all === []) {
  2589. return '';
  2590. }
  2591. sort($all, SORT_STRING);
  2592. $lines = [];
  2593. foreach ($all as $cn) {
  2594. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2595. $lines[] = $cn . '(' . $status . ')';
  2596. }
  2597. return implode("\n", $lines);
  2598. }
  2599. /**
  2600. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2601. */
  2602. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2603. {
  2604. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2605. $this->view->engine->layout(false);
  2606. try {
  2607. $bodyHtml = $this->view->fetch($view);
  2608. $this->view->assign('dialogBody', $bodyHtml);
  2609. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2610. return $this->view->fetch('procuremen/dialog_lite_shell');
  2611. } finally {
  2612. if ($restoreLayout) {
  2613. $this->view->engine->layout($restoreLayout);
  2614. }
  2615. }
  2616. }
  2617. /**
  2618. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2619. */
  2620. protected function resolveBundleSysRq(array $bundle): string
  2621. {
  2622. foreach ($bundle['pos'] ?? [] as $po) {
  2623. if (!is_array($po)) {
  2624. continue;
  2625. }
  2626. $sr = trim((string)($po['sys_rq'] ?? ''));
  2627. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2628. return $sr;
  2629. }
  2630. }
  2631. return '';
  2632. }
  2633. /**
  2634. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2635. */
  2636. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2637. {
  2638. $raw = trim((string)$sysRq);
  2639. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2640. return true;
  2641. }
  2642. $ts = strtotime(str_replace('T', ' ', $raw));
  2643. if ($ts === false || $ts <= 0) {
  2644. return true;
  2645. }
  2646. return time() >= $ts;
  2647. }
  2648. /**
  2649. * 开标前校验:必须已过报价截止时间
  2650. *
  2651. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2652. */
  2653. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2654. {
  2655. $sysRq = $this->resolveBundleSysRq($bundle);
  2656. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2657. $this->error('未到招标截止日期');
  2658. }
  2659. }
  2660. /**
  2661. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2662. *
  2663. * @param array<string, mixed> $d
  2664. * @param string $deliveryYmd
  2665. */
  2666. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2667. {
  2668. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2669. return max(0, (int)$d['lead_days']);
  2670. }
  2671. if ($deliveryYmd === '') {
  2672. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2673. }
  2674. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2675. return null;
  2676. }
  2677. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2678. $t2 = strtotime($m[1] . ' 00:00:00');
  2679. if ($t1 === false || $t2 === false) {
  2680. return null;
  2681. }
  2682. return max(0, (int)round(($t2 - $t1) / 86400));
  2683. }
  2684. /**
  2685. * @param int|null $days
  2686. */
  2687. protected function formatProcuremenLeadDaysText($days): string
  2688. {
  2689. if ($days === null || $days === '') {
  2690. return '未填写';
  2691. }
  2692. if (!is_numeric($days)) {
  2693. return '未填写';
  2694. }
  2695. return ((int)$days) . '天';
  2696. }
  2697. /**
  2698. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2699. *
  2700. * @param array<string, mixed> $line
  2701. */
  2702. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2703. {
  2704. $amountFilled = !empty($line['amount_filled']);
  2705. $deliveryFilled = !empty($line['delivery_filled']);
  2706. $leadFilled = !empty($line['lead_days_filled']);
  2707. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2708. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2709. $line['amount_show'] = '';
  2710. if (array_key_exists('amount_text', $line)) {
  2711. $line['amount_text'] = $line['unit_price_text'];
  2712. }
  2713. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2714. $line['delivery_show'] = $deliveryText;
  2715. if (array_key_exists('delivery_text', $line)) {
  2716. $line['delivery_text'] = $deliveryText;
  2717. }
  2718. $line['delivery_ymd'] = '';
  2719. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2720. $line['lead_days_show'] = $leadText;
  2721. $line['lead_days_text'] = $leadText;
  2722. $line['lead_days'] = '';
  2723. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2724. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2725. $line['subtotal_num'] = null;
  2726. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2727. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2728. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2729. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2730. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2731. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2732. $line['amount_filled'] = false;
  2733. $line['delivery_filled'] = false;
  2734. $line['lead_days_filled'] = false;
  2735. $line['is_quoted'] = false;
  2736. if (array_key_exists('quote_label', $line)) {
  2737. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2738. }
  2739. }
  2740. protected function ensurePurchaseOrderBidOpenTable(): void
  2741. {
  2742. static $ready = false;
  2743. if ($ready) {
  2744. return;
  2745. }
  2746. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2747. try {
  2748. if (Cache::get($cacheKey)) {
  2749. $ready = true;
  2750. return;
  2751. }
  2752. } catch (\Throwable $e) {
  2753. }
  2754. try {
  2755. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2756. $ready = true;
  2757. try {
  2758. Cache::set($cacheKey, 1, 86400);
  2759. } catch (\Throwable $e) {
  2760. }
  2761. } catch (\Throwable $e) {
  2762. Db::execute(
  2763. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2764. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2765. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2766. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2767. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2768. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2769. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2770. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2771. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2772. `createtime` datetime DEFAULT NULL,
  2773. PRIMARY KEY (`id`),
  2774. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2775. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2776. );
  2777. $ready = true;
  2778. try {
  2779. Cache::set($cacheKey, 1, 86400);
  2780. } catch (\Throwable $e2) {
  2781. }
  2782. }
  2783. }
  2784. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2785. {
  2786. $ccydh = trim($ccydh);
  2787. if ($ccydh === '') {
  2788. return false;
  2789. }
  2790. $this->ensurePurchaseOrderBidOpenTable();
  2791. try {
  2792. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2793. return is_array($row);
  2794. } catch (\Throwable $e) {
  2795. return false;
  2796. }
  2797. }
  2798. /**
  2799. * 批量查询订单是否已开标验证
  2800. *
  2801. * @param array<int, string> $ccydhs
  2802. * @return array<string, bool> ccydh => true
  2803. */
  2804. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2805. {
  2806. $set = [];
  2807. $list = [];
  2808. foreach ($ccydhs as $c) {
  2809. $c = trim((string)$c);
  2810. if ($c !== '') {
  2811. $list[$c] = true;
  2812. }
  2813. }
  2814. if ($list === []) {
  2815. return $set;
  2816. }
  2817. $this->ensurePurchaseOrderBidOpenTable();
  2818. try {
  2819. $rows = Db::table('purchase_order_bid_open')
  2820. ->where('ccydh', 'in', array_keys($list))
  2821. ->field('ccydh')
  2822. ->select();
  2823. foreach ($rows as $row) {
  2824. if (!is_array($row)) {
  2825. continue;
  2826. }
  2827. $c = trim((string)($row['ccydh'] ?? ''));
  2828. if ($c !== '') {
  2829. $set[$c] = true;
  2830. }
  2831. }
  2832. } catch (\Throwable $e) {
  2833. return [];
  2834. }
  2835. return $set;
  2836. }
  2837. /**
  2838. * 批量查询订单是否已指定供应商(免开标)
  2839. *
  2840. * @param array<int, string> $ccydhs
  2841. * @return array<string, bool> ccydh => true
  2842. */
  2843. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2844. {
  2845. $set = [];
  2846. $list = [];
  2847. foreach ($ccydhs as $c) {
  2848. $c = trim((string)$c);
  2849. if ($c !== '') {
  2850. $list[$c] = true;
  2851. }
  2852. }
  2853. if ($list === []) {
  2854. return $set;
  2855. }
  2856. $this->ensurePurchaseOrderManualPickColumns();
  2857. try {
  2858. $rows = Db::table('purchase_order')
  2859. ->where('CCYDH', 'in', array_keys($list))
  2860. ->where('manual_pick', 1)
  2861. ->field('CCYDH')
  2862. ->select();
  2863. foreach ($rows as $row) {
  2864. if (!is_array($row)) {
  2865. continue;
  2866. }
  2867. $c = trim((string)($row['CCYDH'] ?? ''));
  2868. if ($c !== '') {
  2869. $set[$c] = true;
  2870. }
  2871. }
  2872. } catch (\Throwable $e) {
  2873. return [];
  2874. }
  2875. return $set;
  2876. }
  2877. /**
  2878. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2879. *
  2880. * @param array<int, array<string, mixed>> $pool
  2881. * @return array<int, array<string, mixed>>
  2882. */
  2883. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2884. {
  2885. $status = trim($status);
  2886. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2887. return $pool;
  2888. }
  2889. $ccydhList = [];
  2890. foreach ($pool as $rw) {
  2891. if (!is_array($rw)) {
  2892. continue;
  2893. }
  2894. $c = trim((string)($rw['CCYDH'] ?? ''));
  2895. if ($c !== '') {
  2896. $ccydhList[] = $c;
  2897. }
  2898. }
  2899. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2900. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2901. $out = [];
  2902. foreach ($pool as $rw) {
  2903. if (!is_array($rw)) {
  2904. continue;
  2905. }
  2906. $c = trim((string)($rw['CCYDH'] ?? ''));
  2907. if ($c !== '' && isset($bidOpenSet[$c])) {
  2908. $t = '已开标';
  2909. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2910. $t = '已指定供应商';
  2911. } else {
  2912. $t = '待开标';
  2913. }
  2914. if ($t === $status) {
  2915. $out[] = $rw;
  2916. }
  2917. }
  2918. return $out;
  2919. }
  2920. /**
  2921. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2922. *
  2923. * @param array<string, mixed> $group
  2924. */
  2925. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2926. {
  2927. if ($quoteVisible) {
  2928. $group['remark_quote_pending'] = 0;
  2929. return;
  2930. }
  2931. $group['remark'] = '';
  2932. $group['remark_quote_pending'] = 0;
  2933. }
  2934. /**
  2935. * @param array{ccydh?:string} $bundle
  2936. */
  2937. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2938. {
  2939. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2940. }
  2941. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2942. {
  2943. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2944. return true;
  2945. }
  2946. return $this->isProcuremenManualPickedForBundle($bundle);
  2947. }
  2948. /**
  2949. * 确保 purchase_order 自选供应商字段
  2950. */
  2951. protected function ensurePurchaseOrderManualPickColumns(): void
  2952. {
  2953. static $done = false;
  2954. if ($done) {
  2955. return;
  2956. }
  2957. $done = true;
  2958. $adds = [
  2959. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2960. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2961. ];
  2962. foreach ($adds as $col => $ddl) {
  2963. try {
  2964. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2965. if (!is_array($cols) || $cols === []) {
  2966. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2967. }
  2968. } catch (\Throwable $e) {
  2969. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2970. }
  2971. }
  2972. }
  2973. /**
  2974. * 是否已自选供应商(免开标查看报价)
  2975. *
  2976. * @param array{pos?:array} $bundle
  2977. */
  2978. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2979. {
  2980. $this->ensurePurchaseOrderManualPickColumns();
  2981. foreach ($bundle['pos'] ?? [] as $poRow) {
  2982. if (!is_array($poRow)) {
  2983. continue;
  2984. }
  2985. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2986. return true;
  2987. }
  2988. }
  2989. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2990. if ($ccydh === '') {
  2991. return false;
  2992. }
  2993. try {
  2994. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2995. return $v !== null && $v !== false && (int)$v > 0;
  2996. } catch (\Throwable $e) {
  2997. return false;
  2998. }
  2999. }
  3000. /**
  3001. * @param array{pos?:array} $bundle
  3002. * @return array{company:string,reason:string}
  3003. */
  3004. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3005. {
  3006. $this->ensurePurchaseOrderManualPickColumns();
  3007. foreach ($bundle['pos'] ?? [] as $poRow) {
  3008. if (!is_array($poRow)) {
  3009. continue;
  3010. }
  3011. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3012. continue;
  3013. }
  3014. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3015. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3016. return ['company' => $cn, 'reason' => $reason];
  3017. }
  3018. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3019. if ($ccydh === '') {
  3020. return ['company' => '', 'reason' => ''];
  3021. }
  3022. try {
  3023. $row = Db::table('purchase_order')
  3024. ->where('CCYDH', $ccydh)
  3025. ->where('manual_pick', 1)
  3026. ->field('pick_company_name,manual_pick_reason')
  3027. ->order('id', 'asc')
  3028. ->find();
  3029. } catch (\Throwable $e) {
  3030. $row = null;
  3031. }
  3032. if (!is_array($row)) {
  3033. return ['company' => '', 'reason' => ''];
  3034. }
  3035. return [
  3036. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  3037. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  3038. ];
  3039. }
  3040. protected function loadBidOpenAdminUser(int $adminId): ?array
  3041. {
  3042. if ($adminId <= 0) {
  3043. return null;
  3044. }
  3045. try {
  3046. $row = Db::name('admin')->where('id', $adminId)->find();
  3047. } catch (\Throwable $e) {
  3048. return null;
  3049. }
  3050. if (!is_array($row)) {
  3051. return null;
  3052. }
  3053. $status = strtolower(trim((string)($row['status'] ?? '')));
  3054. if ($status !== '' && $status !== 'normal') {
  3055. return null;
  3056. }
  3057. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3058. return null;
  3059. }
  3060. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3061. if (!preg_match('/^1\d{10}$/', $phone)) {
  3062. return null;
  3063. }
  3064. $name = trim((string)($row['nickname'] ?? ''));
  3065. if ($name === '') {
  3066. $name = trim((string)($row['username'] ?? ''));
  3067. }
  3068. return [
  3069. 'id' => (int)$row['id'],
  3070. 'username' => trim((string)($row['username'] ?? '')),
  3071. 'nickname' => $name,
  3072. 'mobile' => $phone,
  3073. ];
  3074. }
  3075. /**
  3076. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3077. */
  3078. protected function bidOpenVerifierAuthGroupRootId(): int
  3079. {
  3080. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3081. return $id > 0 ? $id : 10;
  3082. }
  3083. /**
  3084. * @return int[]
  3085. */
  3086. protected function loadBidOpenVerifierAuthGroupIds(): array
  3087. {
  3088. static $memo = [];
  3089. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3090. if (isset($memo[$rootId])) {
  3091. return $memo[$rootId];
  3092. }
  3093. try {
  3094. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3095. } catch (\Throwable $e) {
  3096. $memo[$rootId] = [$rootId];
  3097. return $memo[$rootId];
  3098. }
  3099. if (!is_array($groups) || $groups === []) {
  3100. $memo[$rootId] = [$rootId];
  3101. return $memo[$rootId];
  3102. }
  3103. $groupList = [];
  3104. foreach ($groups as $g) {
  3105. if (is_array($g)) {
  3106. $groupList[] = $g;
  3107. }
  3108. }
  3109. if ($groupList === []) {
  3110. $memo[$rootId] = [$rootId];
  3111. return $memo[$rootId];
  3112. }
  3113. $tree = \fast\Tree::instance();
  3114. $tree->init($groupList);
  3115. $ids = $tree->getChildrenIds($rootId, true);
  3116. if (!is_array($ids) || $ids === []) {
  3117. $memo[$rootId] = [$rootId];
  3118. return $memo[$rootId];
  3119. }
  3120. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3121. return $memo[$rootId];
  3122. }
  3123. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3124. {
  3125. if ($adminId <= 0) {
  3126. return false;
  3127. }
  3128. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3129. if ($groupIds === []) {
  3130. return false;
  3131. }
  3132. try {
  3133. return (bool)Db::name('auth_group_access')
  3134. ->where('uid', $adminId)
  3135. ->where('group_id', 'in', $groupIds)
  3136. ->count();
  3137. } catch (\Throwable $e) {
  3138. return false;
  3139. }
  3140. }
  3141. /**
  3142. * @return array<int, array<string, mixed>>
  3143. */
  3144. protected function listBidOpenVerifierCandidates(): array
  3145. {
  3146. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3147. if ($groupIds === []) {
  3148. return [];
  3149. }
  3150. try {
  3151. $adminIds = Db::name('auth_group_access')
  3152. ->where('group_id', 'in', $groupIds)
  3153. ->column('uid');
  3154. } catch (\Throwable $e) {
  3155. $adminIds = [];
  3156. }
  3157. $adminIds = is_array($adminIds)
  3158. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3159. : [];
  3160. if ($adminIds === []) {
  3161. return [];
  3162. }
  3163. try {
  3164. $rows = Db::name('admin')
  3165. ->where('status', 'normal')
  3166. ->where('id', 'in', $adminIds)
  3167. ->where('mobile', '<>', '')
  3168. ->order('id', 'asc')
  3169. ->select();
  3170. } catch (\Throwable $e) {
  3171. return [];
  3172. }
  3173. if (!is_array($rows)) {
  3174. return [];
  3175. }
  3176. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3177. $out = [];
  3178. foreach ($rows as $row) {
  3179. if (!is_array($row)) {
  3180. continue;
  3181. }
  3182. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3183. if ($one === null) {
  3184. continue;
  3185. }
  3186. $out[] = [
  3187. 'id' => $one['id'],
  3188. 'username' => $one['username'],
  3189. 'nickname' => $one['nickname'],
  3190. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3191. 'mobile' => mask_phone($one['mobile']),
  3192. 'mobile_plain' => (string)$one['mobile'],
  3193. ];
  3194. }
  3195. return $out;
  3196. }
  3197. /**
  3198. * @param int[] $adminIds
  3199. * @return array<int, string>
  3200. */
  3201. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3202. {
  3203. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3204. if ($adminIds === []) {
  3205. return [];
  3206. }
  3207. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3208. try {
  3209. $rows = Db::name('auth_group_access')
  3210. ->alias('aga')
  3211. ->join('auth_group ag', 'aga.group_id = ag.id')
  3212. ->where('aga.uid', 'in', $adminIds)
  3213. ->where('aga.group_id', 'in', $groupIds)
  3214. ->field('aga.uid,ag.name')
  3215. ->order('aga.uid', 'asc')
  3216. ->order('aga.group_id', 'asc')
  3217. ->select();
  3218. } catch (\Throwable $e) {
  3219. return [];
  3220. }
  3221. if (!is_array($rows)) {
  3222. return [];
  3223. }
  3224. $out = [];
  3225. foreach ($rows as $row) {
  3226. if (!is_array($row)) {
  3227. continue;
  3228. }
  3229. $uid = (int)($row['uid'] ?? 0);
  3230. $name = trim((string)($row['name'] ?? ''));
  3231. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3232. continue;
  3233. }
  3234. $out[$uid] = $name;
  3235. }
  3236. return $out;
  3237. }
  3238. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3239. {
  3240. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3241. }
  3242. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3243. {
  3244. return 'procuremen_bidopen_wait_' . $adminId;
  3245. }
  3246. protected function renderBidOpenVerifySms(string $code): string
  3247. {
  3248. $tpl = '';
  3249. try {
  3250. $row = $this->loadNotifyTemplateRow('bid_open');
  3251. if (is_array($row)) {
  3252. $tpl = trim((string)($row['content'] ?? ''));
  3253. }
  3254. } catch (\Throwable $e) {
  3255. $tpl = '';
  3256. }
  3257. if ($tpl === '') {
  3258. $tpl = '【可集达】您的短信验证码是{code}';
  3259. }
  3260. return str_replace('{code}', $code, $tpl);
  3261. }
  3262. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3263. {
  3264. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3265. }
  3266. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3267. {
  3268. $code = trim($code);
  3269. if (!preg_match('/^\d{6}$/', $code)) {
  3270. return false;
  3271. }
  3272. $mock = Config::get('mproc.mock_sms_code');
  3273. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3274. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3275. return true;
  3276. }
  3277. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3278. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3279. return false;
  3280. }
  3281. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3282. return true;
  3283. }
  3284. /**
  3285. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3286. */
  3287. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3288. {
  3289. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3290. if ($ccydh === '') {
  3291. throw new \InvalidArgumentException('订单号无效');
  3292. }
  3293. $this->ensurePurchaseOrderBidOpenTable();
  3294. list($operatorId, $operatorName) = $this->GetUseName();
  3295. $now = date('Y-m-d H:i:s');
  3296. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3297. $payload = [
  3298. 'ccydh' => $ccydh,
  3299. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3300. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3301. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3302. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3303. 'operator_id' => (int)$operatorId,
  3304. 'operator_name' => trim((string)$operatorName),
  3305. 'createtime' => $now,
  3306. ];
  3307. if (is_array($exists)) {
  3308. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3309. } else {
  3310. Db::table('purchase_order_bid_open')->insert($payload);
  3311. }
  3312. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3313. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3314. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3315. (int)$payload['verifier1_id'],
  3316. (int)$payload['verifier2_id'],
  3317. ]);
  3318. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3319. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3320. }
  3321. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3322. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3323. }
  3324. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3325. $seenSid = [];
  3326. foreach ($bundle['pos'] ?? [] as $poRow) {
  3327. if (!is_array($poRow)) {
  3328. continue;
  3329. }
  3330. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3331. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3332. continue;
  3333. }
  3334. $seenSid[$sid] = true;
  3335. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3336. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3337. }
  3338. if ($seenSid === []) {
  3339. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3340. if ($this->isValidScydgyRowId($anchor)) {
  3341. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3342. }
  3343. }
  3344. // 开标通过后计算并写入供应商服务评分
  3345. try {
  3346. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3347. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3348. } catch (\Throwable $e) {
  3349. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3350. }
  3351. }
  3352. /**
  3353. * 报价行展示字段默认值(模板安全访问)
  3354. *
  3355. * @param array<string, mixed> $line
  3356. * @return array<string, mixed>
  3357. */
  3358. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3359. {
  3360. if (!array_key_exists('amount_quote_pending', $line)) {
  3361. $line['amount_quote_pending'] = 0;
  3362. }
  3363. if (!array_key_exists('delivery_quote_pending', $line)) {
  3364. $line['delivery_quote_pending'] = 0;
  3365. }
  3366. if (!array_key_exists('quote_before_deadline', $line)) {
  3367. $line['quote_before_deadline'] = 0;
  3368. }
  3369. if (!array_key_exists('amount_filled', $line)) {
  3370. $line['amount_filled'] = 0;
  3371. }
  3372. if (!array_key_exists('delivery_filled', $line)) {
  3373. $line['delivery_filled'] = 0;
  3374. }
  3375. if (!array_key_exists('lead_days_filled', $line)) {
  3376. $line['lead_days_filled'] = 0;
  3377. }
  3378. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3379. $line['lead_days_quote_pending'] = 0;
  3380. }
  3381. if (!array_key_exists('lead_days_show', $line)) {
  3382. $line['lead_days_show'] = '未填写';
  3383. }
  3384. if (!array_key_exists('lead_days_text', $line)) {
  3385. $line['lead_days_text'] = $line['lead_days_show'];
  3386. }
  3387. return $line;
  3388. }
  3389. /**
  3390. * 审核弹窗:按供应商汇总报价明细
  3391. *
  3392. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3393. * @return array<int, array<string, mixed>>
  3394. */
  3395. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3396. {
  3397. $sids = [];
  3398. foreach ($bundle['pos'] ?? [] as $po) {
  3399. if (!is_array($po)) {
  3400. continue;
  3401. }
  3402. $sid = (int)($po['scydgy_id'] ?? 0);
  3403. if ($this->isValidScydgyRowId($sid)) {
  3404. $sids[$sid] = true;
  3405. }
  3406. }
  3407. if ($sids === []) {
  3408. return [];
  3409. }
  3410. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3411. $gymcMap = [];
  3412. $qtyBySid = [];
  3413. $orderedSids = [];
  3414. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3415. if (!is_array($mr)) {
  3416. continue;
  3417. }
  3418. $gid = $this->extractScydgyRowId($mr);
  3419. if ($this->isValidScydgyRowId($gid)) {
  3420. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3421. $orderedSids[] = $gid;
  3422. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3423. if ($qty === '') {
  3424. $qty = trim((string)($mr['NGZL'] ?? ''));
  3425. }
  3426. $qtyBySid[$gid] = $qty;
  3427. }
  3428. }
  3429. foreach ($bundle['pos'] ?? [] as $po) {
  3430. if (!is_array($po)) {
  3431. continue;
  3432. }
  3433. $gid = (int)($po['scydgy_id'] ?? 0);
  3434. if ($this->isValidScydgyRowId($gid)) {
  3435. $nm = trim((string)($po['CGYMC'] ?? ''));
  3436. if ($nm !== '') {
  3437. $gymcMap[$gid] = $nm;
  3438. }
  3439. if (!in_array($gid, $orderedSids, true)) {
  3440. $orderedSids[] = $gid;
  3441. }
  3442. }
  3443. }
  3444. try {
  3445. $detailsQuery = Db::table('purchase_order_detail')
  3446. ->where('scydgy_id', 'in', array_keys($sids));
  3447. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3448. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3449. } catch (\Throwable $e) {
  3450. try {
  3451. $detailsQuery = Db::table('purchase_order_detail')
  3452. ->where('scydgy_id', 'in', array_keys($sids));
  3453. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3454. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3455. } catch (\Throwable $e2) {
  3456. $details = [];
  3457. }
  3458. }
  3459. if (!is_array($details)) {
  3460. $details = [];
  3461. }
  3462. $byCompany = [];
  3463. foreach ($details as $d) {
  3464. if (!is_array($d)) {
  3465. continue;
  3466. }
  3467. $cn = trim((string)($d['company_name'] ?? ''));
  3468. if ($cn === '') {
  3469. continue;
  3470. }
  3471. if (!isset($byCompany[$cn])) {
  3472. $ph = trim((string)($d['phone'] ?? ''));
  3473. $username = trim((string)($d['username'] ?? ''));
  3474. if ($username === '') {
  3475. $username = $this->resolveCustomerContactName($ph, $cn);
  3476. }
  3477. $byCompany[$cn] = [
  3478. 'name' => $cn,
  3479. 'email' => trim((string)($d['email'] ?? '')),
  3480. 'phone' => $ph,
  3481. 'username' => $username,
  3482. 'remark' => '',
  3483. 'has_quote' => false,
  3484. 'lines_map' => [],
  3485. ];
  3486. }
  3487. if ($byCompany[$cn]['remark'] === '') {
  3488. $rm = '';
  3489. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3490. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3491. $rm = trim((string)$d[$rk]);
  3492. break;
  3493. }
  3494. }
  3495. if ($rm !== '') {
  3496. $byCompany[$cn]['remark'] = $rm;
  3497. }
  3498. }
  3499. $sid = (int)($d['scydgy_id'] ?? 0);
  3500. $am = trim((string)($d['amount'] ?? ''));
  3501. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3502. if ($gymc === '') {
  3503. $gymc = '工序';
  3504. }
  3505. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3506. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3507. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3508. $deliveryShow = $deliveryRaw;
  3509. }
  3510. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3511. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3512. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3513. $subtotal = null;
  3514. if ($amountNum !== null) {
  3515. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3516. }
  3517. $unitPriceText = $amountFilled
  3518. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3519. : '未填写';
  3520. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3521. $leadFilled = ($leadDays !== null);
  3522. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3523. $lineRow = [
  3524. 'cgymc' => $gymc,
  3525. 'amount' => $am,
  3526. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3527. 'amount_filled' => $amountFilled,
  3528. 'unit_price_text' => $unitPriceText,
  3529. 'delivery' => $deliveryRaw,
  3530. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3531. 'delivery_filled' => $deliveryFilled,
  3532. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3533. 'lead_days' => $leadFilled ? $leadDays : '',
  3534. 'lead_days_filled'=> $leadFilled,
  3535. 'lead_days_show' => $leadText,
  3536. 'lead_days_text' => $leadText,
  3537. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3538. 'subtotal_num' => $subtotal,
  3539. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3540. 'is_quoted' => $amountFilled,
  3541. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3542. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3543. ];
  3544. if (!$quoteVisible) {
  3545. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3546. }
  3547. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3548. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3549. }
  3550. foreach ($byCompany as $cn => $g) {
  3551. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3552. $lines = [];
  3553. $usedSids = [];
  3554. foreach ($orderedSids as $sid) {
  3555. if (!isset($linesMap[$sid])) {
  3556. continue;
  3557. }
  3558. $lines[] = $linesMap[$sid];
  3559. $usedSids[$sid] = true;
  3560. }
  3561. foreach ($linesMap as $sid => $ln) {
  3562. if (isset($usedSids[$sid])) {
  3563. continue;
  3564. }
  3565. $lines[] = $ln;
  3566. }
  3567. $total = count($lines);
  3568. $quoted = 0;
  3569. $groupTotal = 0.0;
  3570. $groupHasTotal = false;
  3571. if ($quoteVisible) {
  3572. foreach ($lines as $ln) {
  3573. $am = trim((string)($ln['amount'] ?? ''));
  3574. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3575. $quoted++;
  3576. }
  3577. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3578. $groupTotal += (float)$ln['subtotal_num'];
  3579. $groupHasTotal = true;
  3580. }
  3581. }
  3582. }
  3583. unset($byCompany[$cn]['lines_map']);
  3584. $byCompany[$cn]['lines'] = $lines;
  3585. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3586. $byCompany[$cn]['line_count'] = $total;
  3587. $byCompany[$cn]['has_total'] = $total > 0;
  3588. $byCompany[$cn]['has_remark'] = $total > 0;
  3589. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3590. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3591. // 工序行 + 备注行 + 总计行
  3592. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3593. }
  3594. $groups = array_values($byCompany);
  3595. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3596. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3597. }
  3598. /**
  3599. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3600. *
  3601. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3602. * @return array<int, array<string, mixed>>
  3603. */
  3604. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3605. {
  3606. $sids = [];
  3607. $poIdMap = [];
  3608. foreach ($bundle['pos'] ?? [] as $po) {
  3609. if (!is_array($po)) {
  3610. continue;
  3611. }
  3612. $sid = (int)($po['scydgy_id'] ?? 0);
  3613. if ($this->isValidScydgyRowId($sid)) {
  3614. $sids[$sid] = true;
  3615. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3616. }
  3617. }
  3618. if ($sids === []) {
  3619. return [];
  3620. }
  3621. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3622. $gymcMap = [];
  3623. $qtyBySid = [];
  3624. $orderedSids = [];
  3625. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3626. if (!is_array($mr)) {
  3627. continue;
  3628. }
  3629. $gid = $this->extractScydgyRowId($mr);
  3630. if ($this->isValidScydgyRowId($gid)) {
  3631. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3632. $orderedSids[] = $gid;
  3633. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3634. if ($qty === '') {
  3635. $qty = trim((string)($mr['NGZL'] ?? ''));
  3636. }
  3637. $qtyBySid[$gid] = $qty;
  3638. }
  3639. }
  3640. foreach ($bundle['pos'] ?? [] as $po) {
  3641. if (!is_array($po)) {
  3642. continue;
  3643. }
  3644. $gid = (int)($po['scydgy_id'] ?? 0);
  3645. if ($this->isValidScydgyRowId($gid)) {
  3646. $nm = trim((string)($po['CGYMC'] ?? ''));
  3647. if ($nm !== '') {
  3648. $gymcMap[$gid] = $nm;
  3649. }
  3650. }
  3651. }
  3652. try {
  3653. $details = Db::table('purchase_order_detail')
  3654. ->where('scydgy_id', 'in', array_keys($sids))
  3655. ->order('company_name', 'asc')
  3656. ->order('id', 'asc')
  3657. ->select();
  3658. } catch (\Throwable $e) {
  3659. try {
  3660. $details = Db::table('purchase_order_detail')
  3661. ->where('scydgy_id', 'in', array_keys($sids))
  3662. ->order('company_name', 'asc')
  3663. ->order('ID', 'asc')
  3664. ->select();
  3665. } catch (\Throwable $e2) {
  3666. $details = [];
  3667. }
  3668. }
  3669. if (!is_array($details)) {
  3670. $details = [];
  3671. }
  3672. $byCompany = [];
  3673. foreach ($details as $d) {
  3674. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3675. continue;
  3676. }
  3677. $cn = trim((string)($d['company_name'] ?? ''));
  3678. if ($cn === '') {
  3679. continue;
  3680. }
  3681. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3682. $sid = (int)($d['scydgy_id'] ?? 0);
  3683. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3684. continue;
  3685. }
  3686. if (!isset($byCompany[$cn])) {
  3687. $ph = trim((string)($d['phone'] ?? ''));
  3688. $username = trim((string)($d['username'] ?? ''));
  3689. if ($username === '') {
  3690. $username = $this->resolveCustomerContactName($ph, $cn);
  3691. }
  3692. $byCompany[$cn] = [
  3693. 'name' => $cn,
  3694. 'email' => trim((string)($d['email'] ?? '')),
  3695. 'phone' => $ph,
  3696. 'username' => $username,
  3697. 'remark' => '',
  3698. 'pick_lines' => [],
  3699. 'detail_picks' => [],
  3700. ];
  3701. }
  3702. if ($byCompany[$cn]['remark'] === '') {
  3703. $rm = '';
  3704. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3705. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3706. $rm = trim((string)$d[$rk]);
  3707. break;
  3708. }
  3709. }
  3710. if ($rm !== '') {
  3711. $byCompany[$cn]['remark'] = $rm;
  3712. }
  3713. }
  3714. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3715. if ($gymc === '') {
  3716. $gymc = '工序';
  3717. }
  3718. $am = trim((string)($d['amount'] ?? ''));
  3719. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3720. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3721. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3722. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3723. $deliveryShow = $deliveryRaw;
  3724. }
  3725. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3726. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3727. $subtotal = null;
  3728. if ($amountNum !== null) {
  3729. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3730. }
  3731. $unitPriceText = $amountFilled
  3732. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3733. : '未填写';
  3734. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3735. $leadFilled = ($leadDays !== null);
  3736. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3737. $pickLine = [
  3738. 'cgymc' => $gymc,
  3739. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3740. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3741. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3742. 'amount_filled' => $amountFilled,
  3743. 'delivery_filled' => $deliveryFilled,
  3744. 'unit_price_text' => $unitPriceText,
  3745. 'lead_days' => $leadFilled ? $leadDays : '',
  3746. 'lead_days_filled'=> $leadFilled,
  3747. 'lead_days_show' => $leadText,
  3748. 'lead_days_text' => $leadText,
  3749. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3750. 'subtotal_num' => $subtotal,
  3751. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3752. 'is_quoted' => $amountFilled,
  3753. ];
  3754. if (!$quoteVisible) {
  3755. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3756. }
  3757. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3758. $byCompany[$cn]['detail_picks'][$sid] = [
  3759. 'scydgy_id' => $sid,
  3760. 'detail_id' => $detailId,
  3761. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3762. 'cgymc' => $gymc,
  3763. ];
  3764. }
  3765. $out = [];
  3766. foreach ($byCompany as $g) {
  3767. $pickLinesMap = $g['pick_lines'] ?? [];
  3768. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3769. continue;
  3770. }
  3771. $pickLines = [];
  3772. $usedLineSids = [];
  3773. foreach ($orderedSids as $sid) {
  3774. if (!isset($pickLinesMap[$sid])) {
  3775. continue;
  3776. }
  3777. $pickLines[] = $pickLinesMap[$sid];
  3778. $usedLineSids[$sid] = true;
  3779. }
  3780. foreach ($pickLinesMap as $sid => $ln) {
  3781. if (isset($usedLineSids[$sid])) {
  3782. continue;
  3783. }
  3784. $pickLines[] = $ln;
  3785. }
  3786. $groupTotal = 0.0;
  3787. $groupHasTotal = false;
  3788. if ($quoteVisible) {
  3789. foreach ($pickLines as $ln) {
  3790. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3791. $groupTotal += (float)$ln['subtotal_num'];
  3792. $groupHasTotal = true;
  3793. }
  3794. }
  3795. }
  3796. $lineCount = count($pickLines);
  3797. $g['pick_lines'] = $pickLines;
  3798. $g['line_count'] = $lineCount;
  3799. $g['has_total'] = $lineCount > 0;
  3800. $g['has_remark'] = $lineCount > 0;
  3801. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3802. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3803. // 工序行 + 备注行 + 总计行
  3804. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3805. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3806. $detailPicks = [];
  3807. $usedPickSids = [];
  3808. foreach ($orderedSids as $sid) {
  3809. if (!isset($detailPicksMap[$sid])) {
  3810. continue;
  3811. }
  3812. $detailPicks[] = $detailPicksMap[$sid];
  3813. $usedPickSids[$sid] = true;
  3814. }
  3815. foreach ($detailPicksMap as $sid => $dp) {
  3816. if (isset($usedPickSids[$sid])) {
  3817. continue;
  3818. }
  3819. $detailPicks[] = $dp;
  3820. }
  3821. $g['detail_picks'] = $detailPicks;
  3822. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3823. unset($g['detail_picks']);
  3824. $out[] = $g;
  3825. }
  3826. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3827. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3828. }
  3829. /**
  3830. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3831. * @return array<int, int[]> scydgy_id => detail_id[]
  3832. */
  3833. protected function mapDetailIdsByScydgyId(array $details): array
  3834. {
  3835. $out = [];
  3836. foreach ($details as $d) {
  3837. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3838. continue;
  3839. }
  3840. $sid = (int)($d['scydgy_id'] ?? 0);
  3841. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3842. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3843. continue;
  3844. }
  3845. if (!isset($out[$sid])) {
  3846. $out[$sid] = [];
  3847. }
  3848. $out[$sid][] = $pk;
  3849. }
  3850. foreach ($out as $sid => $ids) {
  3851. $out[$sid] = array_values(array_unique($ids));
  3852. }
  3853. return $out;
  3854. }
  3855. /**
  3856. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3857. *
  3858. * @param array<string, mixed> $dbRow
  3859. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3860. */
  3861. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3862. {
  3863. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3864. $r = [
  3865. 'ID' => $sid,
  3866. 'scydgy_id' => $sid,
  3867. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3868. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3869. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3870. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3871. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3872. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3873. 'CDW' => $dbRow['CDW'] ?? '',
  3874. 'czlyq' => $dbRow['czlyq'] ?? '',
  3875. 'NGZL' => $dbRow['NGZL'] ?? '',
  3876. 'CDF' => $dbRow['CDF'] ?? '',
  3877. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3878. 'MBZ' => $dbRow['MBZ'] ?? '',
  3879. 'bwjg' => $dbRow['bwjg'] ?? '',
  3880. 'iStatus' => $dbRow['iStatus'] ?? '',
  3881. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3882. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3883. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3884. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3885. 'dStamp' => $dbRow['dStamp'] ?? '',
  3886. 'pick_time' => $dbRow['pick_time'] ?? '',
  3887. ];
  3888. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3889. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3890. if ($sid > 0 && isset($dStampMap[$sid])) {
  3891. $t = trim((string)$dStampMap[$sid]);
  3892. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3893. $r['dStamp'] = $dStampMap[$sid];
  3894. }
  3895. }
  3896. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3897. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3898. $ct = $dbRow['createtime'];
  3899. if (is_numeric($ct) && (int)$ct > 946684800) {
  3900. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3901. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3902. $r['dStamp'] = trim($ct);
  3903. }
  3904. }
  3905. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3906. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3907. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3908. $fallback = trim((string)($r['dStamp'] ?? ''));
  3909. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3910. $r['dputrecord'] = $fallback;
  3911. }
  3912. }
  3913. if (array_key_exists('id', $dbRow)) {
  3914. $r['purchase_order_id'] = (int)$dbRow['id'];
  3915. }
  3916. if ($sid < 0) {
  3917. $r['_is_manual'] = 1;
  3918. }
  3919. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3920. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3921. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3922. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3923. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3924. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3925. $r['pick_time'] = $pickFallback;
  3926. break;
  3927. }
  3928. }
  3929. }
  3930. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3931. if ($pickNm !== '') {
  3932. $r['pick_company_name'] = $pickNm;
  3933. $r['picked_supplier_name'] = $pickNm;
  3934. }
  3935. return $r;
  3936. }
  3937. /**
  3938. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3939. *
  3940. * @return array<int, array<string, mixed>>
  3941. */
  3942. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3943. {
  3944. $pool = [];
  3945. if (!is_array($dbRows) || $dbRows === []) {
  3946. return $pool;
  3947. }
  3948. $dStampMap = [];
  3949. $sidList = [];
  3950. foreach ($dbRows as $tmpRow) {
  3951. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3952. $sid = (int)$tmpRow['scydgy_id'];
  3953. if ($sid > 0) {
  3954. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3955. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3956. $sidList[$sid] = true;
  3957. }
  3958. }
  3959. }
  3960. }
  3961. if ($sidList !== []) {
  3962. try {
  3963. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3964. } catch (\Throwable $e) {
  3965. $dStampMap = [];
  3966. }
  3967. }
  3968. foreach ($dbRows as $dbRow) {
  3969. if (!is_array($dbRow)) {
  3970. continue;
  3971. }
  3972. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3973. }
  3974. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3975. $needCcydh = [];
  3976. foreach ($pool as $row) {
  3977. if (!is_array($row)) {
  3978. continue;
  3979. }
  3980. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3981. continue;
  3982. }
  3983. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3984. if ($ccydh !== '') {
  3985. $needCcydh[$ccydh] = true;
  3986. }
  3987. }
  3988. if ($needCcydh !== []) {
  3989. $czMap = [];
  3990. try {
  3991. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3992. } catch (\Throwable $e) {
  3993. $czMap = [];
  3994. }
  3995. if (is_array($czMap) && $czMap !== []) {
  3996. foreach ($pool as &$row) {
  3997. if (!is_array($row)) {
  3998. continue;
  3999. }
  4000. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4001. continue;
  4002. }
  4003. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4004. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4005. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4006. }
  4007. }
  4008. unset($row);
  4009. }
  4010. }
  4011. return $pool;
  4012. }
  4013. /**
  4014. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4015. *
  4016. * @param int[] $scydgyIds
  4017. * @return array<int, array<string, mixed>>
  4018. */
  4019. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4020. {
  4021. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4022. if ($scydgyIds === []) {
  4023. return [];
  4024. }
  4025. try {
  4026. $list = Db::table('purchase_order_detail')
  4027. ->where('scydgy_id', 'in', $scydgyIds)
  4028. ->field('scydgy_id,company_name,amount,delivery')
  4029. ->select();
  4030. } catch (\Throwable $e) {
  4031. $list = [];
  4032. }
  4033. return is_array($list) ? $list : [];
  4034. }
  4035. /**
  4036. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4037. *
  4038. * @param int[] $scydgyIds
  4039. * @param array<int, array<string, mixed>> $allRows
  4040. * @return array{cnt:int, amt:int, deliv:int}
  4041. */
  4042. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4043. {
  4044. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4045. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4046. if ($scydgyIds === [] || $allRows === []) {
  4047. return $out;
  4048. }
  4049. $idSet = array_flip($scydgyIds);
  4050. $all = [];
  4051. $withAmt = [];
  4052. $withDeliv = [];
  4053. foreach ($allRows as $r) {
  4054. if (!is_array($r)) {
  4055. continue;
  4056. }
  4057. $sid = (int)($r['scydgy_id'] ?? 0);
  4058. if (!isset($idSet[$sid])) {
  4059. continue;
  4060. }
  4061. $cn = trim((string)($r['company_name'] ?? ''));
  4062. if ($cn === '') {
  4063. continue;
  4064. }
  4065. $all[$cn] = true;
  4066. $am = $r['amount'] ?? null;
  4067. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4068. $withAmt[$cn] = true;
  4069. }
  4070. $dv = $r['delivery'] ?? null;
  4071. if ($dv !== null && trim((string)$dv) !== '') {
  4072. $withDeliv[$cn] = true;
  4073. }
  4074. }
  4075. return [
  4076. 'cnt' => count($all),
  4077. 'amt' => count($withAmt),
  4078. 'deliv' => count($withDeliv),
  4079. ];
  4080. }
  4081. /**
  4082. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4083. *
  4084. * @param array<string, mixed> $row
  4085. */
  4086. protected function resolveProcuremenThisQuantity(array $row): string
  4087. {
  4088. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4089. if ($q !== '') {
  4090. return $q;
  4091. }
  4092. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4093. if (!is_scalar($ngzl)) {
  4094. return '';
  4095. }
  4096. $s = trim((string)$ngzl);
  4097. if ($s === '') {
  4098. return '';
  4099. }
  4100. if (is_numeric($s) && (float)$s === 0.0) {
  4101. return '';
  4102. }
  4103. return $s;
  4104. }
  4105. /**
  4106. * @param array<string, mixed> $row
  4107. */
  4108. protected function resolveProcuremenCeilingPrice(array $row): string
  4109. {
  4110. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4111. }
  4112. /**
  4113. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4114. *
  4115. * @param array<int, mixed> $parts
  4116. */
  4117. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4118. {
  4119. $out = [];
  4120. foreach ($parts as $p) {
  4121. $s = trim((string)$p);
  4122. if ($s !== '') {
  4123. $out[] = $s;
  4124. }
  4125. }
  4126. return $out === [] ? '' : implode($sep, $out);
  4127. }
  4128. /**
  4129. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4130. *
  4131. * @param array<int, array<string, mixed>> $rows
  4132. */
  4133. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4134. {
  4135. if ($rows === []) {
  4136. return;
  4137. }
  4138. $idList = [];
  4139. foreach ($rows as $rw) {
  4140. if (!is_array($rw)) {
  4141. continue;
  4142. }
  4143. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4144. foreach ($rw['_order_merge_rows'] as $mr) {
  4145. if (!is_array($mr)) {
  4146. continue;
  4147. }
  4148. $mid = (int)($mr['ID'] ?? 0);
  4149. if ($this->isValidScydgyRowId($mid)) {
  4150. $idList[$mid] = true;
  4151. }
  4152. }
  4153. }
  4154. $id = (int)($rw['ID'] ?? 0);
  4155. if ($this->isValidScydgyRowId($id)) {
  4156. $idList[$id] = true;
  4157. }
  4158. }
  4159. if ($idList === []) {
  4160. return;
  4161. }
  4162. try {
  4163. $list = Db::table('purchase_order')
  4164. ->where('scydgy_id', 'in', array_keys($idList))
  4165. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4166. ->select();
  4167. } catch (\Throwable $e) {
  4168. return;
  4169. }
  4170. if (!is_array($list)) {
  4171. return;
  4172. }
  4173. $byId = [];
  4174. foreach ($list as $dbRow) {
  4175. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4176. continue;
  4177. }
  4178. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4179. }
  4180. foreach ($rows as &$rw) {
  4181. if (!is_array($rw)) {
  4182. continue;
  4183. }
  4184. $mergeRows = [];
  4185. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4186. $mergeRows = $rw['_order_merge_rows'];
  4187. } else {
  4188. $mergeRows = [$rw];
  4189. }
  4190. $qtyList = [];
  4191. $priceList = [];
  4192. $picked = '';
  4193. foreach ($mergeRows as $mr) {
  4194. if (!is_array($mr)) {
  4195. continue;
  4196. }
  4197. $sid = (int)($mr['ID'] ?? 0);
  4198. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4199. $src = $mr;
  4200. if (is_array($db)) {
  4201. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4202. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4203. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4204. if ($qDb !== '') {
  4205. $src['This_quantity'] = $qDb;
  4206. }
  4207. if ($pDb !== '') {
  4208. $src['ceilingPrice'] = $pDb;
  4209. }
  4210. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4211. $src['NGZL'] = $ngzlDb;
  4212. }
  4213. if ($picked === '') {
  4214. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4215. }
  4216. }
  4217. if ($picked === '') {
  4218. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4219. }
  4220. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4221. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4222. }
  4223. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4224. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4225. if ($picked !== '') {
  4226. $rw['pick_company_name'] = $picked;
  4227. $rw['picked_supplier_name'] = $picked;
  4228. }
  4229. }
  4230. unset($rw);
  4231. }
  4232. /**
  4233. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4234. *
  4235. * @param int[] $scydgyIds
  4236. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4237. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4238. */
  4239. protected function OrderDetailSummary(array $scydgyIds)
  4240. {
  4241. $out = [];
  4242. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4243. if ($scydgyIds === []) {
  4244. return $out;
  4245. }
  4246. $list = [];
  4247. try {
  4248. $list = Db::table('purchase_order_detail')
  4249. ->where('scydgy_id', 'in', $scydgyIds)
  4250. ->field('id,scydgy_id,amount,delivery')
  4251. ->select();
  4252. } catch (\Throwable $e) {
  4253. $list = [];
  4254. }
  4255. if (!is_array($list)) {
  4256. return $out;
  4257. }
  4258. foreach ($list as $r) {
  4259. if (!is_array($r)) {
  4260. continue;
  4261. }
  4262. $ids = (int)($r['scydgy_id'] ?? 0);
  4263. if (!$this->isValidScydgyRowId($ids)) {
  4264. continue;
  4265. }
  4266. if (!isset($out[$ids])) {
  4267. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4268. }
  4269. $out[$ids]['cnt']++;
  4270. $am = $r['amount'] ?? null;
  4271. if ($am !== null && $am !== '') {
  4272. if (!(is_string($am) && trim($am) === '')) {
  4273. $out[$ids]['amt']++;
  4274. }
  4275. }
  4276. $dv = $r['delivery'] ?? null;
  4277. if ($dv !== null && trim((string)$dv) !== '') {
  4278. $out[$ids]['deliv']++;
  4279. }
  4280. }
  4281. return $out;
  4282. }
  4283. /**
  4284. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4285. *
  4286. * @return array
  4287. */
  4288. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4289. {
  4290. $strContains = function ($haystack, $needle) {
  4291. if ($needle === '') {
  4292. return false;
  4293. }
  4294. $haystack = (string)$haystack;
  4295. if (function_exists('mb_stripos')) {
  4296. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4297. }
  4298. return stripos($haystack, $needle) !== false;
  4299. };
  4300. $stripAlias = function ($f) {
  4301. return preg_replace('/^[ab]\./i', '', (string)$f);
  4302. };
  4303. $searchColNames = [];
  4304. foreach (explode(',', $this->searchFields) as $colRaw) {
  4305. $c = $stripAlias(trim($colRaw));
  4306. if ($c !== '') {
  4307. $searchColNames[] = $c;
  4308. }
  4309. }
  4310. // 等值条件先行(表头下拉),减少后续日期解析量
  4311. $eqFilters = [];
  4312. $otherFilters = [];
  4313. foreach ($filterArr as $fk => $fv) {
  4314. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4315. continue;
  4316. }
  4317. if (is_array($fv)) {
  4318. continue;
  4319. }
  4320. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4321. continue;
  4322. }
  4323. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4324. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4325. $field = $stripAlias($fk);
  4326. if ($sym === '=' || $sym === '') {
  4327. $eqFilters[$field] = trim((string)$fv);
  4328. } else {
  4329. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4330. }
  4331. }
  4332. $ymTarget = '';
  4333. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4334. $ymTarget = $ymM[1];
  4335. }
  4336. $filtered = [];
  4337. foreach ($pool as $r) {
  4338. if (!is_array($r)) {
  4339. continue;
  4340. }
  4341. foreach ($eqFilters as $field => $fv) {
  4342. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4343. continue 2;
  4344. }
  4345. }
  4346. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4347. // 初选池不应含手工单;若混入则直接剔除
  4348. if ($isManual) {
  4349. continue;
  4350. }
  4351. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4352. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4353. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4354. continue;
  4355. }
  4356. if ($applyMonthRange) {
  4357. $mo = (int)$m[2];
  4358. if ($mo < 1 || $mo > 12) {
  4359. continue;
  4360. }
  4361. if ($ymTarget !== '') {
  4362. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4363. if ($ymRow !== $ymTarget) {
  4364. continue;
  4365. }
  4366. } else {
  4367. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4368. $rowMonthStart = $ymRow . '-01 00:00:00';
  4369. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4370. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4371. continue;
  4372. }
  4373. }
  4374. }
  4375. if ($search !== '') {
  4376. $hitSearch = false;
  4377. foreach ($searchColNames as $c) {
  4378. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4379. if ($cell !== '' && $strContains($cell, $search)) {
  4380. $hitSearch = true;
  4381. break;
  4382. }
  4383. }
  4384. if (!$hitSearch) {
  4385. continue;
  4386. }
  4387. }
  4388. foreach ($otherFilters as $item) {
  4389. $fv = $item['fv'];
  4390. $sym = $item['sym'];
  4391. $field = $item['field'];
  4392. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4393. $cellStr = trim((string)$cell);
  4394. switch ($sym) {
  4395. case '<>':
  4396. if ((string)$cell === (string)$fv) {
  4397. continue 3;
  4398. }
  4399. break;
  4400. case 'LIKE':
  4401. case 'NOT LIKE':
  4402. $needle = trim((string)$fv);
  4403. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4404. if ($sym === 'LIKE' && !$hit) {
  4405. continue 3;
  4406. }
  4407. if ($sym === 'NOT LIKE' && $hit) {
  4408. continue 3;
  4409. }
  4410. break;
  4411. case 'BETWEEN':
  4412. case 'RANGE':
  4413. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4414. if (count($parts) < 2) {
  4415. $parts = is_string($fv) ? explode(',', $fv) : [];
  4416. }
  4417. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4418. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4419. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4420. continue 3;
  4421. }
  4422. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4423. continue 3;
  4424. }
  4425. break;
  4426. case '>':
  4427. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4428. continue 3;
  4429. }
  4430. break;
  4431. case '>=':
  4432. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4433. continue 3;
  4434. }
  4435. break;
  4436. case '<':
  4437. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4438. continue 3;
  4439. }
  4440. break;
  4441. case '<=':
  4442. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4443. continue 3;
  4444. }
  4445. break;
  4446. default:
  4447. if ((string)$cell !== (string)$fv) {
  4448. continue 3;
  4449. }
  4450. break;
  4451. }
  4452. }
  4453. $filtered[] = $r;
  4454. }
  4455. return $filtered;
  4456. }
  4457. /**
  4458. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4459. */
  4460. public function snapshotToProcure()
  4461. {
  4462. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4463. $this->error(__('Invalid parameters'));
  4464. }
  4465. $row = json_decode($this->request->post('row_json', ''), true);
  4466. if (!is_array($row)) {
  4467. $this->error(__('Invalid parameters'));
  4468. }
  4469. try {
  4470. $ids = $this->extractScydgyRowId($row);
  4471. if (!$this->isValidScydgyRowId($ids)) {
  4472. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4473. }
  4474. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4475. $data = $this->normalizePurchaseOrderWritePayload([
  4476. 'scydgy_id' => $ids,
  4477. 'CCYDH' => $row['CCYDH'] ?? null,
  4478. 'CYJMC' => $row['CYJMC'] ?? null,
  4479. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4480. 'CDXMC' => $row['CDXMC'] ?? null,
  4481. 'CGYBH' => $row['CGYBH'] ?? null,
  4482. 'CGYMC' => $row['CGYMC'] ?? null,
  4483. 'CDW' => $row['CDW'] ?? null,
  4484. 'czlyq' => $row['czlyq'] ?? null,
  4485. 'NGZL' => $row['NGZL'] ?? null,
  4486. 'CDF' => $row['CDF'] ?? null,
  4487. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4488. 'MBZ' => $row['MBZ'] ?? null,
  4489. 'bwjg' => $row['bwjg'] ?? null,
  4490. 'iStatus' => $row['iStatus'] ?? null,
  4491. 'dStamp' => $row['dStamp'] ?? null,
  4492. 'dputrecord' => $row['dputrecord'] ?? null,
  4493. 'cywyxm' => $row['cywyxm'] ?? null,
  4494. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4495. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4496. ], $row);
  4497. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4498. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4499. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  4500. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  4501. $this->success('操作成功');
  4502. return;
  4503. }
  4504. if ($exists) {
  4505. $upd = $data;
  4506. unset($upd['scydgy_id'], $upd['status']);
  4507. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4508. } else {
  4509. // 新增:不写 status(空/走库默认);仅写创建时间
  4510. $data['createtime'] = date('Y-m-d H:i:s');
  4511. Db::table('purchase_order')->insert($data);
  4512. }
  4513. } catch (\Throwable $e) {
  4514. $this->error($e->getMessage());
  4515. }
  4516. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4517. $this->success('操作成功');
  4518. }
  4519. /**
  4520. * 未发列表
  4521. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  4522. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4523. */
  4524. public function completeDirectly()
  4525. {
  4526. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4527. $this->error(__('参数错误'));
  4528. }
  4529. if (!$this->procuremenCanComplete()) {
  4530. $this->error(__('You have no permission'));
  4531. }
  4532. $row = json_decode($this->request->post('row_json', ''), true);
  4533. if (!is_array($row)) {
  4534. $this->error(__('Invalid parameters'));
  4535. }
  4536. $finishRaw = $this->request->post('finish', '1');
  4537. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4538. $poIdLog = null;
  4539. try {
  4540. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4541. $ids = $this->extractScydgyRowId($row);
  4542. if (!$this->isValidScydgyRowId($ids)) {
  4543. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4544. }
  4545. if ($asComplete) {
  4546. $this->assertPickRowCanComplete($ids, $row);
  4547. }
  4548. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4549. $data = $this->normalizePurchaseOrderWritePayload([
  4550. 'scydgy_id' => $ids,
  4551. 'CCYDH' => $row['CCYDH'] ?? null,
  4552. 'CYJMC' => $row['CYJMC'] ?? null,
  4553. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4554. 'CDXMC' => $row['CDXMC'] ?? null,
  4555. 'CGYBH' => $row['CGYBH'] ?? null,
  4556. 'CGYMC' => $row['CGYMC'] ?? null,
  4557. 'CDW' => $row['CDW'] ?? null,
  4558. 'czlyq' => $row['czlyq'] ?? null,
  4559. 'NGZL' => $row['NGZL'] ?? null,
  4560. 'CDF' => $row['CDF'] ?? null,
  4561. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4562. 'MBZ' => $row['MBZ'] ?? null,
  4563. 'bwjg' => $row['bwjg'] ?? null,
  4564. 'iStatus' => $row['iStatus'] ?? null,
  4565. 'dStamp' => $row['dStamp'] ?? null,
  4566. 'dputrecord' => $row['dputrecord'] ?? null,
  4567. 'cywyxm' => $row['cywyxm'] ?? null,
  4568. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4569. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4570. ], $row);
  4571. if ($asComplete) {
  4572. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4573. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4574. }
  4575. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4576. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4577. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  4578. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  4579. $this->success('操作成功');
  4580. return;
  4581. }
  4582. if ($exists) {
  4583. $upd = $data;
  4584. unset($upd['scydgy_id']);
  4585. if (!$asComplete) {
  4586. unset($upd['status']);
  4587. }
  4588. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4589. } else {
  4590. // 新增:不写 status;完结时 $data 已含 status=1
  4591. $data['createtime'] = date('Y-m-d H:i:s');
  4592. Db::table('purchase_order')->insert($data);
  4593. }
  4594. } catch (\Throwable $e) {
  4595. $this->error($e->getMessage());
  4596. }
  4597. try {
  4598. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4599. if (is_array($rpo)) {
  4600. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4601. $poIdLog = $tid > 0 ? $tid : null;
  4602. }
  4603. } catch (\Throwable $e) {
  4604. $poIdLog = null;
  4605. }
  4606. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4607. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4608. if ($asComplete) {
  4609. $this->addOrderLog(
  4610. $ids,
  4611. 'mark_complete',
  4612. '点击「完结」,已标记为已完结',
  4613. $poIdLog
  4614. );
  4615. try {
  4616. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4617. if ($pdfPublicPath === '') {
  4618. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4619. }
  4620. } catch (\Throwable $e) {
  4621. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4622. }
  4623. } else {
  4624. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4625. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  4626. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4627. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4628. $mbzPart = '备注「' . ($mbz !== '' ? $mbz : '') . '」';
  4629. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart . ',' . $mbzPart;
  4630. $this->addOrderLog(
  4631. $ids,
  4632. 'save_qty_price',
  4633. '保存本次数量、最高限价、备注:' . $detail,
  4634. $poIdLog
  4635. );
  4636. }
  4637. $this->pickHiddenScydgySetCache = null;
  4638. $this->success("操作成功");
  4639. }
  4640. /**
  4641. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  4642. *
  4643. * @param array<int, array> $rows 引用传递当前页行
  4644. */
  4645. protected function mergePurchaseOrder(array &$rows)
  4646. {
  4647. if ($rows === []) {
  4648. return;
  4649. }
  4650. $ids = [];
  4651. foreach ($rows as $rw) {
  4652. if (!is_array($rw)) {
  4653. continue;
  4654. }
  4655. $id = (int)($rw['ID'] ?? 0);
  4656. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4657. if ($this->isValidScydgyRowId($id)) {
  4658. $ids[$id] = true;
  4659. }
  4660. }
  4661. $idList = array_keys($ids);
  4662. if ($idList === []) {
  4663. return;
  4664. }
  4665. try {
  4666. $list = Db::table('purchase_order')
  4667. ->where('scydgy_id', 'in', $idList)
  4668. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  4669. ->select();
  4670. } catch (\Throwable $e) {
  4671. return;
  4672. }
  4673. if (!is_array($list)) {
  4674. return;
  4675. }
  4676. $byId = [];
  4677. foreach ($list as $dbRow) {
  4678. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4679. continue;
  4680. }
  4681. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4682. }
  4683. foreach ($rows as &$rw) {
  4684. if (!is_array($rw)) {
  4685. continue;
  4686. }
  4687. $sid = (int)($rw['ID'] ?? 0);
  4688. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4689. continue;
  4690. }
  4691. $db = $byId[$sid];
  4692. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  4693. if (array_key_exists('This_quantity', $db)) {
  4694. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4695. }
  4696. if (array_key_exists('ceilingPrice', $db)) {
  4697. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4698. } elseif (array_key_exists('ceiling_price', $db)) {
  4699. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4700. }
  4701. if (array_key_exists('MBZ', $db)) {
  4702. $rw['MBZ'] = $db['MBZ'] === null ? '' : $db['MBZ'];
  4703. }
  4704. }
  4705. unset($rw);
  4706. }
  4707. /**
  4708. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4709. */
  4710. public function purchaseConfirmPick()
  4711. {
  4712. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4713. $this->error(__('Invalid parameters'));
  4714. }
  4715. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4716. $this->error(__('You have no permission'));
  4717. }
  4718. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4719. if ($batchRaw !== '') {
  4720. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4721. return;
  4722. }
  4723. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4724. $sid = (int)$scydgyId;
  4725. if (!$this->isValidScydgyRowId($sid)) {
  4726. $this->error('参数无效');
  4727. }
  4728. $parseIdList = function ($raw) {
  4729. if (is_array($raw)) {
  4730. $arr = $raw;
  4731. } else {
  4732. $decoded = json_decode((string)$raw, true);
  4733. $arr = is_array($decoded) ? $decoded : [];
  4734. }
  4735. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4736. };
  4737. $selectedRaw = $this->request->post('selected_ids', null);
  4738. if ($selectedRaw === null || $selectedRaw === '') {
  4739. $legacy = (int)$this->request->post('selected_id', 0);
  4740. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4741. } else {
  4742. $selectedIds = $parseIdList($selectedRaw);
  4743. }
  4744. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4745. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4746. try {
  4747. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4748. } catch (\InvalidArgumentException $e) {
  4749. $this->error($e->getMessage());
  4750. } catch (\Throwable $e) {
  4751. $this->error($e->getMessage());
  4752. }
  4753. $this->pickHiddenScydgySetCache = null;
  4754. $this->success('操作成功', '', $result);
  4755. }
  4756. /**
  4757. * 整单采购确认(多道工序一次提交)
  4758. */
  4759. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4760. {
  4761. $decoded = json_decode($batchRaw, true);
  4762. if (!is_array($decoded) || $decoded === []) {
  4763. $this->error('提交数据无效');
  4764. }
  4765. $picks = [];
  4766. foreach ($decoded as $item) {
  4767. if (!is_array($item)) {
  4768. continue;
  4769. }
  4770. $sid = (int)($item['scydgy_id'] ?? 0);
  4771. if (!$this->isValidScydgyRowId($sid)) {
  4772. continue;
  4773. }
  4774. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4775. if (!is_array($sel)) {
  4776. $sel = [(int)$sel];
  4777. }
  4778. $unsel = $item['unselected_ids'] ?? [];
  4779. if (!is_array($unsel)) {
  4780. $unsel = json_decode((string)$unsel, true);
  4781. $unsel = is_array($unsel) ? $unsel : [];
  4782. }
  4783. $picks[] = [
  4784. 'scydgy_id' => $sid,
  4785. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4786. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4787. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4788. ];
  4789. }
  4790. if ($picks === []) {
  4791. $this->error('提交数据无效');
  4792. }
  4793. Db::startTrans();
  4794. $results = [];
  4795. try {
  4796. foreach ($picks as $pick) {
  4797. $results[] = $this->runPurchaseConfirmPick(
  4798. (int)$pick['scydgy_id'],
  4799. $pick['selected_ids'],
  4800. $pick['unselected_ids'],
  4801. (int)$pick['purchase_order_id'],
  4802. false,
  4803. false
  4804. );
  4805. }
  4806. Db::commit();
  4807. } catch (\Throwable $e) {
  4808. Db::rollback();
  4809. $msg = $e->getMessage();
  4810. $this->error($msg !== '' ? $msg : '提交失败');
  4811. }
  4812. try {
  4813. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4814. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4815. } catch (\Throwable $e) {
  4816. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4817. }
  4818. $this->pickHiddenScydgySetCache = null;
  4819. $this->success('操作成功', '', ['batch' => $results]);
  4820. }
  4821. /**
  4822. * @return array<string, mixed>
  4823. */
  4824. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4825. {
  4826. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4827. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4828. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4829. $scydgyId = (string)$sid;
  4830. if ($selectedIds === []) {
  4831. throw new \InvalidArgumentException('请至少勾选一条明细');
  4832. }
  4833. $inter = array_intersect($selectedIds, $unselectedIds);
  4834. if ($inter !== []) {
  4835. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4836. }
  4837. $allIds = $this->purchaseOrderDetail($sid);
  4838. if ($allIds === []) {
  4839. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4840. }
  4841. foreach ($selectedIds as $id) {
  4842. if (!in_array($id, $allIds, true)) {
  4843. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4844. }
  4845. }
  4846. foreach ($unselectedIds as $id) {
  4847. if (!in_array($id, $allIds, true)) {
  4848. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4849. }
  4850. }
  4851. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4852. sort($union, SORT_NUMERIC);
  4853. $expect = $allIds;
  4854. sort($expect, SORT_NUMERIC);
  4855. if ($union !== $expect) {
  4856. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4857. }
  4858. if ($manageTransaction) {
  4859. Db::startTrans();
  4860. }
  4861. try {
  4862. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4863. $aff = 0;
  4864. try {
  4865. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4866. } catch (\Throwable $e) {
  4867. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4868. }
  4869. if ($aff < 1) {
  4870. throw new \Exception('更新选中状态失败');
  4871. }
  4872. $poPayload = [
  4873. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4874. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4875. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4876. ];
  4877. if ($purchaseOrderId > 0) {
  4878. $poAff = (int)Db::table('purchase_order')
  4879. ->where('id', $purchaseOrderId)
  4880. ->where('scydgy_id', $sid)
  4881. ->update($poPayload);
  4882. if ($poAff < 1) {
  4883. throw new \Exception('主表订单不存在或与工序行不匹配');
  4884. }
  4885. } else {
  4886. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4887. if ($poAff < 1) {
  4888. throw new \Exception('未找到');
  4889. }
  4890. }
  4891. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4892. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4893. if ($manageTransaction) {
  4894. Db::commit();
  4895. }
  4896. } catch (\Throwable $e) {
  4897. if ($manageTransaction) {
  4898. Db::rollback();
  4899. }
  4900. throw $e;
  4901. }
  4902. $poIdFinal = $purchaseOrderId;
  4903. if ($poIdFinal <= 0) {
  4904. try {
  4905. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4906. if (is_array($rpo)) {
  4907. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4908. }
  4909. } catch (\Throwable $e) {
  4910. $poIdFinal = 0;
  4911. }
  4912. }
  4913. $pickNames = [];
  4914. foreach ($selectedIds as $pid) {
  4915. $dr = $this->purchaseOrderDetai($sid, $pid);
  4916. $nm = trim((string)($dr['company_name'] ?? ''));
  4917. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4918. }
  4919. $this->addOrderLog(
  4920. $sid,
  4921. 'purchase_confirm',
  4922. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4923. $poIdFinal > 0 ? $poIdFinal : null
  4924. );
  4925. if ($sendNotifications) {
  4926. try {
  4927. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4928. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4929. 'scydgy_id' => $sid,
  4930. 'selected_ids' => $selectedIds,
  4931. 'unselected_ids' => $unselectedIds,
  4932. 'purchase_order_id' => $purchaseOrderId,
  4933. ]]);
  4934. } catch (\Throwable $e) {
  4935. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4936. }
  4937. }
  4938. Log::write(sprintf(
  4939. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4940. $scydgyId,
  4941. $purchaseOrderId,
  4942. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4943. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4944. ), 'notice');
  4945. $pdfPublicPath = '';
  4946. try {
  4947. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4948. } catch (\Throwable $e) {
  4949. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4950. }
  4951. return [
  4952. 'scydgy_id' => $scydgyId,
  4953. 'purchase_order_id' => $purchaseOrderId,
  4954. 'selected_ids' => $selectedIds,
  4955. 'unselected_ids' => $unselectedIds,
  4956. 'purchase_confirm_pdf' => $pdfPublicPath,
  4957. ];
  4958. }
  4959. /**
  4960. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4961. *
  4962. * @param int[]|string[] $scydgyIds
  4963. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4964. */
  4965. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4966. {
  4967. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4968. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4969. if ($scydgyIds === []) {
  4970. return $empty;
  4971. }
  4972. $pos = [];
  4973. try {
  4974. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4975. } catch (\Throwable $e) {
  4976. $rows = [];
  4977. }
  4978. if (is_array($rows)) {
  4979. foreach ($rows as $po) {
  4980. if (is_array($po)) {
  4981. $pos[] = $po;
  4982. }
  4983. }
  4984. }
  4985. if ($pos === []) {
  4986. return $empty;
  4987. }
  4988. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4989. return [
  4990. 'ccydh' => $ccydh,
  4991. 'pos' => $pos,
  4992. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4993. ];
  4994. }
  4995. /**
  4996. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4997. *
  4998. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4999. * @param array<int, array<string, mixed>> $picks
  5000. */
  5001. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5002. {
  5003. if ($picks === []) {
  5004. return;
  5005. }
  5006. $this->ensureConfirmResultEmailTemplates();
  5007. $fallbackDetailId = 0;
  5008. $winners = [];
  5009. $losers = [];
  5010. foreach ($picks as $pick) {
  5011. if (!is_array($pick)) {
  5012. continue;
  5013. }
  5014. $sid = (int)($pick['scydgy_id'] ?? 0);
  5015. if (!$this->isValidScydgyRowId($sid)) {
  5016. continue;
  5017. }
  5018. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5019. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5020. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5021. $fallbackDetailId = (int)$selectedIds[0];
  5022. }
  5023. foreach ($selectedIds as $pid) {
  5024. $dr = $this->purchaseOrderDetai($sid, $pid);
  5025. if (!is_array($dr)) {
  5026. continue;
  5027. }
  5028. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5029. }
  5030. foreach ($unselectedIds as $pid) {
  5031. $dr = $this->purchaseOrderDetai($sid, $pid);
  5032. if (!is_array($dr)) {
  5033. continue;
  5034. }
  5035. $key = $this->notifySupplierDedupeKey($dr);
  5036. if (!isset($winners[$key])) {
  5037. $losers[$key] = $dr;
  5038. }
  5039. }
  5040. }
  5041. if ($winners === [] && $losers === []) {
  5042. return;
  5043. }
  5044. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5045. $poIdLog = 0;
  5046. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5047. if (isset($pos[0]) && is_array($pos[0])) {
  5048. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5049. }
  5050. $sendSmsSafe = function ($phone, $content) {
  5051. $phone = trim((string)$phone);
  5052. if ($phone === '') {
  5053. return;
  5054. }
  5055. try {
  5056. $this->smsbao($phone, $content);
  5057. } catch (\Throwable $e) {
  5058. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5059. }
  5060. };
  5061. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  5062. $cname = trim((string)($dr['company_name'] ?? ''));
  5063. $ph = trim((string)($dr['phone'] ?? ''));
  5064. $toEmail = trim((string)($dr['email'] ?? ''));
  5065. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5066. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5067. return;
  5068. }
  5069. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5070. if ($detailId <= 0) {
  5071. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5072. }
  5073. try {
  5074. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5075. } catch (\Throwable $e) {
  5076. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5077. $platformUrl = '';
  5078. }
  5079. $vars = array_merge($confirmNotifyVars, [
  5080. 'company_name' => $cname,
  5081. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5082. 'phone' => $ph,
  5083. 'email' => $toEmail,
  5084. 'platform_url' => $platformUrl,
  5085. ]);
  5086. unset($vars['_fallback_detail_id']);
  5087. try {
  5088. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5089. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5090. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5091. $mailConfig = $this->loadMailerConfig();
  5092. $this->issueSendSupplierEmail([
  5093. 'company_name' => $cname,
  5094. 'email' => $toEmail,
  5095. 'mail_plain' => $mailPlain,
  5096. 'mail_body' => $mailBody,
  5097. 'notify_vars' => $vars,
  5098. 'sms_content' => '',
  5099. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5100. 'email_log_scene' => 'confirm_result',
  5101. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5102. 'email_log_purchase_order_id' => $poIdLog,
  5103. ], $mailConfig, $mailSubject);
  5104. } catch (\Throwable $e) {
  5105. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5106. }
  5107. };
  5108. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5109. foreach ($winners as $dr) {
  5110. $cname = trim((string)($dr['company_name'] ?? ''));
  5111. $ph = trim((string)($dr['phone'] ?? ''));
  5112. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5113. 'company_name' => $cname,
  5114. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5115. 'phone' => $ph,
  5116. ]));
  5117. $sendSmsSafe($ph, $sms);
  5118. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5119. }
  5120. foreach ($losers as $dr) {
  5121. $cname = trim((string)($dr['company_name'] ?? ''));
  5122. $ph = trim((string)($dr['phone'] ?? ''));
  5123. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5124. 'company_name' => $cname,
  5125. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5126. 'phone' => $ph,
  5127. ]));
  5128. $sendSmsSafe($ph, $sms);
  5129. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5130. }
  5131. }
  5132. /**
  5133. * 短信去重键:优先手机号,否则公司名
  5134. */
  5135. protected function notifySupplierDedupeKey(array $detailRow): string
  5136. {
  5137. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5138. if ($ph !== '') {
  5139. return 'p:' . $ph;
  5140. }
  5141. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5142. return 'c:' . $cn;
  5143. }
  5144. /**
  5145. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5146. *
  5147. * @param int[] $detailIds
  5148. */
  5149. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5150. {
  5151. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5152. if ($detailIds === []) {
  5153. return;
  5154. }
  5155. $payload = ['status_name' => $statusName];
  5156. try {
  5157. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5158. } catch (\Throwable $e) {
  5159. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5160. }
  5161. }
  5162. /**
  5163. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5164. */
  5165. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5166. {
  5167. try {
  5168. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5169. } catch (\Throwable $e) {
  5170. return;
  5171. }
  5172. if (!is_array($rows)) {
  5173. return;
  5174. }
  5175. foreach ($rows as $dr) {
  5176. if (!is_array($dr)) {
  5177. continue;
  5178. }
  5179. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5180. if ($id <= 0) {
  5181. continue;
  5182. }
  5183. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5184. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5185. try {
  5186. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5187. } catch (\Throwable $e) {
  5188. }
  5189. }
  5190. }
  5191. /**
  5192. * @param array<string, mixed> $detailRow
  5193. */
  5194. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5195. {
  5196. $am = $detailRow['amount'] ?? null;
  5197. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5198. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5199. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5200. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5201. }
  5202. /**
  5203. * @return int[]
  5204. */
  5205. protected function purchaseOrderDetail(int $scydgyId): array
  5206. {
  5207. if (!$this->isValidScydgyRowId($scydgyId)) {
  5208. return [];
  5209. }
  5210. try {
  5211. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5212. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5213. $list = $listQuery->select();
  5214. } catch (\Throwable $e) {
  5215. return [];
  5216. }
  5217. if (!is_array($list)) {
  5218. return [];
  5219. }
  5220. $ids = [];
  5221. foreach ($list as $r) {
  5222. if (!is_array($r)) {
  5223. continue;
  5224. }
  5225. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5226. if ($pk > 0) {
  5227. $ids[] = $pk;
  5228. }
  5229. }
  5230. return array_values(array_unique($ids));
  5231. }
  5232. /**
  5233. * 获取当前登录用户信息 [id, 展示名]
  5234. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  5235. */
  5236. protected function GetUseName(): array
  5237. {
  5238. $id = 0;
  5239. $name = '';
  5240. try {
  5241. if ($this->auth && $this->auth->isLogin()) {
  5242. $u = $this->auth->getUserInfo();
  5243. if (is_array($u)) {
  5244. $id = (int)($u['id'] ?? 0);
  5245. $name = trim((string)($u['nickname'] ?? ''));
  5246. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  5247. $sessionUser = trim((string)($u['username'] ?? ''));
  5248. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  5249. try {
  5250. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  5251. if (is_array($row)) {
  5252. $nick = trim((string)($row['nickname'] ?? ''));
  5253. if ($nick !== '') {
  5254. $name = $nick;
  5255. } elseif ($name === '') {
  5256. $name = trim((string)($row['username'] ?? ''));
  5257. }
  5258. }
  5259. } catch (\Throwable $e) {
  5260. }
  5261. }
  5262. if ($name === '') {
  5263. $name = $sessionUser;
  5264. }
  5265. }
  5266. }
  5267. } catch (\Throwable $e) {
  5268. }
  5269. if ($name === '') {
  5270. $name = '未知用户';
  5271. }
  5272. return [$id, $name];
  5273. }
  5274. /**
  5275. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5276. */
  5277. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5278. {
  5279. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5280. }
  5281. /**
  5282. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5283. *
  5284. * @param array<int, array<string, mixed>> $rows
  5285. */
  5286. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5287. {
  5288. $sidList = [];
  5289. foreach ($rows as $rw) {
  5290. if (!is_array($rw)) {
  5291. continue;
  5292. }
  5293. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5294. foreach ($rw['_order_merge_rows'] as $mr) {
  5295. $mid = (int)($mr['ID'] ?? 0);
  5296. if ($this->isValidScydgyRowId($mid)) {
  5297. $sidList[$mid] = true;
  5298. }
  5299. }
  5300. }
  5301. $id = (int)($rw['ID'] ?? 0);
  5302. if ($this->isValidScydgyRowId($id)) {
  5303. $sidList[$id] = true;
  5304. }
  5305. }
  5306. $sids = array_keys($sidList);
  5307. $issueBySid = [];
  5308. $confirmBySid = [];
  5309. $approveBySid = [];
  5310. if ($sids !== []) {
  5311. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5312. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5313. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5314. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5315. try {
  5316. $logs = Db::table('purchase_order_oper_log')
  5317. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5318. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5319. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5320. ->order('id', 'asc')
  5321. ->select();
  5322. } catch (\Throwable $e) {
  5323. $logs = [];
  5324. }
  5325. if (is_array($logs)) {
  5326. $issueSet = array_fill_keys($issueActs, true);
  5327. $confirmSet = array_fill_keys($confirmActs, true);
  5328. $approveSet = array_fill_keys($approveActs, true);
  5329. foreach ($logs as $lg) {
  5330. if (!is_array($lg)) {
  5331. continue;
  5332. }
  5333. $lg = ProcuremenOperLog::normalizeRow($lg);
  5334. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5335. if ($sid === 0) {
  5336. continue;
  5337. }
  5338. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5339. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5340. if ($t === '') {
  5341. continue;
  5342. }
  5343. if (isset($issueSet[$action])) {
  5344. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5345. $issueBySid[$sid] = $t;
  5346. }
  5347. }
  5348. if (isset($confirmSet[$action])) {
  5349. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5350. $confirmBySid[$sid] = $t;
  5351. }
  5352. }
  5353. if (isset($approveSet[$action])) {
  5354. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5355. $approveBySid[$sid] = $t;
  5356. }
  5357. }
  5358. }
  5359. }
  5360. }
  5361. foreach ($rows as &$rw) {
  5362. if (!is_array($rw)) {
  5363. continue;
  5364. }
  5365. $mergeSids = [];
  5366. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5367. foreach ($rw['_order_merge_rows'] as $mr) {
  5368. $mid = (int)($mr['ID'] ?? 0);
  5369. if ($this->isValidScydgyRowId($mid)) {
  5370. $mergeSids[] = $mid;
  5371. }
  5372. }
  5373. }
  5374. $rid = (int)($rw['ID'] ?? 0);
  5375. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5376. $mergeSids[] = $rid;
  5377. }
  5378. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5379. $issue = $pick;
  5380. $confirm = '';
  5381. $approve = '';
  5382. foreach ($mergeSids as $sid) {
  5383. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5384. $issue = $issueBySid[$sid];
  5385. }
  5386. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5387. $confirm = $confirmBySid[$sid];
  5388. }
  5389. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5390. $approve = $approveBySid[$sid];
  5391. }
  5392. }
  5393. if ($issue === '' && $pick !== '') {
  5394. $issue = $pick;
  5395. }
  5396. $rw['issue_time'] = $issue;
  5397. $rw['confirm_time'] = $confirm;
  5398. $rw['approve_time'] = $approve;
  5399. }
  5400. unset($rw);
  5401. }
  5402. /**
  5403. * 按主键取一条
  5404. */
  5405. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5406. {
  5407. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5408. return [];
  5409. }
  5410. try {
  5411. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5412. if (is_array($one)) {
  5413. return $one;
  5414. }
  5415. } catch (\Throwable $e) {
  5416. }
  5417. try {
  5418. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5419. if (is_array($one)) {
  5420. return $one;
  5421. }
  5422. } catch (\Throwable $e) {
  5423. }
  5424. return [];
  5425. }
  5426. /**
  5427. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5428. */
  5429. protected function formatProcuremenDetailTime($v): string
  5430. {
  5431. if ($v === null || $v === '') {
  5432. return '';
  5433. }
  5434. if (is_numeric($v) && (int)$v > 946684800) {
  5435. return date('Y-m-d H:i:s', (int)$v);
  5436. }
  5437. return ProcuremenTime::formatDisplayDateTime($v);
  5438. }
  5439. /**
  5440. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5441. */
  5442. protected function formatDeliveryYmd($v): string
  5443. {
  5444. if ($v === null || $v === '') {
  5445. return '';
  5446. }
  5447. $s = trim((string)$v);
  5448. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5449. return '';
  5450. }
  5451. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5452. return $m[1];
  5453. }
  5454. $ts = strtotime($s);
  5455. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5456. }
  5457. /**
  5458. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5459. */
  5460. protected function detailRowSupplierOperated(array $r): bool
  5461. {
  5462. $am = $r['amount'] ?? null;
  5463. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5464. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5465. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5466. return $okAmt || $okDel;
  5467. }
  5468. /**
  5469. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5470. */
  5471. protected function resolveDetailSupplierOperTime(array $r): string
  5472. {
  5473. if (!$this->detailRowSupplierOperated($r)) {
  5474. return '';
  5475. }
  5476. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5477. if ($t !== '') {
  5478. return $t;
  5479. }
  5480. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5481. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5482. continue;
  5483. }
  5484. $t = $this->formatProcuremenDetailTime($r[$col]);
  5485. if ($t !== '') {
  5486. return $t;
  5487. }
  5488. }
  5489. return '';
  5490. }
  5491. /**
  5492. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5493. */
  5494. protected function detailRowSupplierAccepted(array $r): bool
  5495. {
  5496. $am = $r['amount'] ?? null;
  5497. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5498. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5499. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5500. return $okAmt && $okDel;
  5501. }
  5502. /**
  5503. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5504. */
  5505. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5506. {
  5507. if ($detailCount > 0) {
  5508. return true;
  5509. }
  5510. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5511. return true;
  5512. }
  5513. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5514. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5515. return true;
  5516. }
  5517. return false;
  5518. }
  5519. /**
  5520. * 下发时间:优先 pick_time,其次首条下发明细时间
  5521. */
  5522. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5523. {
  5524. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5525. if ($issueTime !== '') {
  5526. return $issueTime;
  5527. }
  5528. foreach ($details as $dr) {
  5529. if (!is_array($dr)) {
  5530. continue;
  5531. }
  5532. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5533. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5534. $issueTime = $t;
  5535. }
  5536. }
  5537. if ($issueTime !== '') {
  5538. return $issueTime;
  5539. }
  5540. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5541. }
  5542. /**
  5543. * 直接点「完结」时间:优先操作记录 mark_complete
  5544. */
  5545. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5546. {
  5547. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5548. }
  5549. /**
  5550. * 操作记录时间(取指定 action 最近一条)
  5551. *
  5552. * @param string|array<int, string> $actions
  5553. */
  5554. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5555. {
  5556. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5557. }
  5558. /**
  5559. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5560. *
  5561. * @param array $main purchase_order 一行
  5562. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5563. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5564. */
  5565. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5566. {
  5567. $issueCnt = count($details);
  5568. $acceptCnt = 0;
  5569. $pickedName = '';
  5570. $pickedTime = '';
  5571. foreach ($details as $dr) {
  5572. if (!is_array($dr)) {
  5573. continue;
  5574. }
  5575. if ($this->detailRowSupplierAccepted($dr)) {
  5576. $acceptCnt++;
  5577. }
  5578. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5579. if ($pickedName === '') {
  5580. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5581. }
  5582. if ($pickedTime === '') {
  5583. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5584. if ($pickedTime === '') {
  5585. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5586. }
  5587. }
  5588. }
  5589. }
  5590. $hasMain = $main !== [];
  5591. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5592. if ($poTime === '') {
  5593. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5594. }
  5595. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5596. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5597. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5598. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5599. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5600. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5601. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5602. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5603. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5604. $inboundResult = '';
  5605. if ($scydgyId > 0) {
  5606. try {
  5607. $inRow = Db::table('purchase_order_inbound_score')
  5608. ->where('scydgy_id', $scydgyId)
  5609. ->field('result,updatetime,createtime')
  5610. ->find();
  5611. } catch (\Throwable $e) {
  5612. $inRow = null;
  5613. }
  5614. if (is_array($inRow) && $inRow !== []) {
  5615. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5616. if ($inboundScoreTime === '') {
  5617. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5618. }
  5619. }
  5620. }
  5621. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5622. $supplierTime = '';
  5623. if ($acceptCnt > 0) {
  5624. foreach ($details as $dr) {
  5625. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5626. continue;
  5627. }
  5628. $t = $this->resolveDetailSupplierOperTime($dr);
  5629. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5630. $supplierTime = $t;
  5631. }
  5632. }
  5633. }
  5634. $directComplete = ($mainCompleted && !$issued);
  5635. $doneTime = '';
  5636. if ($mainCompleted) {
  5637. if ($directComplete) {
  5638. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5639. }
  5640. if ($doneTime === '' && $inboundScoreTime !== '') {
  5641. $doneTime = $inboundScoreTime;
  5642. }
  5643. if ($doneTime === '') {
  5644. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5645. }
  5646. if ($doneTime === '') {
  5647. foreach ($details as $dr) {
  5648. if (!is_array($dr)) {
  5649. continue;
  5650. }
  5651. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5652. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5653. $doneTime = $t;
  5654. }
  5655. }
  5656. }
  5657. if ($doneTime === '') {
  5658. $doneTime = $poTime;
  5659. }
  5660. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5661. if ($doneTime === '' && $confirmApproveTime !== '') {
  5662. $doneTime = $confirmApproveTime;
  5663. }
  5664. }
  5665. if ($directComplete) {
  5666. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5667. $step1Done = $hasMain;
  5668. $step2Done = false;
  5669. $step3Done = false;
  5670. $step4Done = false;
  5671. $step5Done = false;
  5672. $stepInboundDone = $inboundScored;
  5673. $step6Done = $mainCompleted && $inboundScored;
  5674. } else {
  5675. $step1Done = $issued;
  5676. $step2Done = $issued;
  5677. $step3Done = $acceptCnt > 0;
  5678. $step4Done = $wflowPendingApproval;
  5679. if (!$step4Done) {
  5680. foreach ($details as $dr) {
  5681. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5682. $step4Done = true;
  5683. break;
  5684. }
  5685. }
  5686. }
  5687. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5688. $stepInboundDone = $inboundScored;
  5689. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5690. $step6Done = $mainCompleted && $inboundScored;
  5691. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5692. if ($mainCompleted && $issued) {
  5693. $step3Done = true;
  5694. $step4Done = true;
  5695. $step5Done = true;
  5696. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5697. if ($supplierTime === '') {
  5698. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5699. if ($fillT !== '') {
  5700. $supplierTime = $fillT;
  5701. }
  5702. }
  5703. if ($pickedTime === '') {
  5704. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5705. if ($fillT !== '') {
  5706. $pickedTime = $fillT;
  5707. }
  5708. }
  5709. if ($auditSelectTime === '') {
  5710. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5711. if ($fillT !== '') {
  5712. $auditSelectTime = $fillT;
  5713. }
  5714. }
  5715. if ($confirmApproveTime === '') {
  5716. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5717. if ($fillT !== '') {
  5718. $confirmApproveTime = $fillT;
  5719. }
  5720. }
  5721. }
  5722. }
  5723. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5724. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5725. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5726. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5727. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5728. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5729. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5730. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5731. $deadlineLines = [];
  5732. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5733. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5734. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5735. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5736. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5737. }
  5738. }
  5739. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5740. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5741. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5742. if ($deliveryDisp === '') {
  5743. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5744. }
  5745. if ($deliveryDisp !== '') {
  5746. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5747. }
  5748. }
  5749. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5750. $deadlineText = implode("\n", $deadlineLines);
  5751. $prefixOperTime = static function (string $t): string {
  5752. $t = trim($t);
  5753. if ($t === '' || $t === '—') {
  5754. return $t;
  5755. }
  5756. if (strpos($t, '操作时间') === 0) {
  5757. return $t;
  5758. }
  5759. return '操作时间:' . $t;
  5760. };
  5761. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5762. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5763. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5764. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5765. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5766. $steps = [
  5767. [
  5768. 'title' => '未发',
  5769. 'subtitle' => '',
  5770. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5771. 'done' => $step1Done,
  5772. ],
  5773. [
  5774. 'title' => '下发',
  5775. 'subtitle' => $deadlineText,
  5776. 'time' => $prefixOperTime($step2Time),
  5777. 'done' => $step2Done,
  5778. ],
  5779. [
  5780. 'title' => '供应商接单',
  5781. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5782. 'time' => '',
  5783. 'done' => $step3Done,
  5784. ],
  5785. [
  5786. 'title' => '待确认',
  5787. 'subtitle' => $step4Done
  5788. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5789. : ($issued ? '待选供应商' : ''),
  5790. 'time' => $prefixOperTime($step4Time),
  5791. 'done' => $step4Done,
  5792. ],
  5793. [
  5794. 'title' => '待审批',
  5795. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5796. 'time' => $prefixOperTime($step5Time),
  5797. 'done' => $step5Done,
  5798. ],
  5799. [
  5800. 'title' => '是否合格',
  5801. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5802. 'time' => $prefixOperTime($stepInboundTime),
  5803. 'done' => $stepInboundDone,
  5804. ],
  5805. [
  5806. 'title' => '已完结',
  5807. 'subtitle' => '',
  5808. 'time' => $prefixOperTime($step6Time),
  5809. 'done' => $step6Done,
  5810. ],
  5811. ];
  5812. $currentIdx = count($steps) - 1;
  5813. if ($directComplete) {
  5814. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5815. if (!$step6Done) {
  5816. foreach ($steps as $i => $s) {
  5817. if (($s['title'] ?? '') === '是否合格') {
  5818. $currentIdx = $i;
  5819. break;
  5820. }
  5821. }
  5822. }
  5823. } else {
  5824. foreach ($steps as $i => $s) {
  5825. if (!$s['done']) {
  5826. $currentIdx = $i;
  5827. break;
  5828. }
  5829. }
  5830. }
  5831. $nSteps = count($steps);
  5832. foreach ($steps as $idx => &$s) {
  5833. $s['current'] = ($idx === $currentIdx);
  5834. if ($idx === 0) {
  5835. $s['pdf_left_bg'] = '';
  5836. } else {
  5837. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5838. }
  5839. if ($idx >= $nSteps - 1) {
  5840. $s['pdf_right_bg'] = '';
  5841. } else {
  5842. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5843. }
  5844. }
  5845. unset($s);
  5846. $labelMap = [
  5847. 'CCYDH' => '订单号',
  5848. 'CYJMC' => '印件名称',
  5849. 'CCLBMMC' => '承揽部门',
  5850. 'CGYMC' => '工序名称',
  5851. 'CDW' => '单位',
  5852. 'czlyq' => '类型',
  5853. 'NGZL' => '工作量',
  5854. 'CDF' => '单价',
  5855. 'cGzzxMc' => '工作中心',
  5856. 'MBZ' => '备注',
  5857. 'This_quantity' => '本次数量',
  5858. 'ceilingPrice' => '最高限价',
  5859. ];
  5860. $orderSummary = [];
  5861. foreach ($labelMap as $key => $lab) {
  5862. if (!array_key_exists($key, $main)) {
  5863. continue;
  5864. }
  5865. $val = $main[$key];
  5866. if ($val === null) {
  5867. $val = '';
  5868. } elseif (!is_scalar($val)) {
  5869. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5870. } else {
  5871. $val = (string)$val;
  5872. }
  5873. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5874. }
  5875. $orderSummary[] = [
  5876. 'label' => '是否合格',
  5877. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5878. ];
  5879. $orderSummaryGrid = [];
  5880. $n = count($orderSummary);
  5881. for ($i = 0; $i < $n; $i += 2) {
  5882. $left = $orderSummary[$i];
  5883. $hasRight = ($i + 1) < $n;
  5884. $orderSummaryGrid[] = [
  5885. 'l1' => $left['label'],
  5886. 'v1' => $left['value'],
  5887. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5888. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5889. ];
  5890. }
  5891. return [
  5892. 'steps' => $steps,
  5893. 'orderSummary' => $orderSummary,
  5894. 'orderSummaryGrid' => $orderSummaryGrid,
  5895. 'inbound_result' => $inboundResult,
  5896. 'inbound_score_time'=> $inboundScoreTime,
  5897. 'detailRows' => $details,
  5898. ];
  5899. }
  5900. /**
  5901. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5902. *
  5903. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5904. */
  5905. protected function prepareProcuremenDetailsView(string $ids): array
  5906. {
  5907. $main = [];
  5908. try {
  5909. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5910. $main = is_array($one) ? $one : [];
  5911. } catch (\Throwable $e) {
  5912. $main = [];
  5913. }
  5914. $details = [];
  5915. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5916. if ($mergeRows === []) {
  5917. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5918. if ($mergeRows === [] && $main !== []) {
  5919. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5920. }
  5921. }
  5922. $detailSidList = [];
  5923. $anchorSid = (int)$ids;
  5924. if ($anchorSid !== 0) {
  5925. $detailSidList[$anchorSid] = true;
  5926. }
  5927. foreach ($mergeRows as $mr) {
  5928. if (!is_array($mr)) {
  5929. continue;
  5930. }
  5931. $sid = $this->extractScydgyRowId($mr);
  5932. if ($sid !== 0) {
  5933. $detailSidList[$sid] = true;
  5934. }
  5935. }
  5936. try {
  5937. if ($detailSidList !== []) {
  5938. $details = Db::table('purchase_order_detail')
  5939. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5940. ->order('id', 'asc')
  5941. ->select();
  5942. }
  5943. } catch (\Throwable $e) {
  5944. $details = [];
  5945. }
  5946. if (!is_array($details)) {
  5947. $details = [];
  5948. }
  5949. foreach ($details as &$r) {
  5950. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5951. $r['id'] = $r['ID'];
  5952. }
  5953. if (isset($r['createtime'])) {
  5954. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5955. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5956. } else {
  5957. $r['createtime_text'] = (string)$r['createtime'];
  5958. }
  5959. } else {
  5960. $r['createtime_text'] = '';
  5961. }
  5962. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5963. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5964. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5965. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5966. if (is_array($r)) {
  5967. $r = $this->maskSupplierContactFields($r);
  5968. }
  5969. }
  5970. unset($r);
  5971. $activeDetails = [];
  5972. foreach ($details as $r) {
  5973. if (is_array($r) && empty($r['is_void'])) {
  5974. $activeDetails[] = $r;
  5975. }
  5976. }
  5977. $operLogs = [];
  5978. try {
  5979. $operSidList = array_keys($detailSidList);
  5980. if ($operSidList === [] && (int)$ids !== 0) {
  5981. $operSidList = [(int)$ids];
  5982. }
  5983. if ($operSidList !== []) {
  5984. $operLogs = Db::table('purchase_order_oper_log')
  5985. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5986. ->order('id', 'asc')
  5987. ->select();
  5988. }
  5989. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5990. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5991. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5992. if ($poId > 0) {
  5993. $operLogs = Db::table('purchase_order_oper_log')
  5994. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5995. ->order('id', 'asc')
  5996. ->select();
  5997. }
  5998. }
  5999. } catch (\Throwable $e) {
  6000. $operLogs = [];
  6001. }
  6002. if (!is_array($operLogs)) {
  6003. $operLogs = [];
  6004. }
  6005. $operLogsRaw = $operLogs;
  6006. $processNameBySid = [];
  6007. foreach ($mergeRows as $mr) {
  6008. if (!is_array($mr)) {
  6009. continue;
  6010. }
  6011. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6012. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6013. if ($psid !== 0 && $gymc !== '') {
  6014. $processNameBySid[$psid] = $gymc;
  6015. }
  6016. }
  6017. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6018. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6019. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6020. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6021. if ($ccydh === '') {
  6022. foreach ($details as $r) {
  6023. if (!is_array($r)) {
  6024. continue;
  6025. }
  6026. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6027. if ($ccydh !== '') {
  6028. break;
  6029. }
  6030. }
  6031. }
  6032. $this->view->assign('ccydh', $ccydh);
  6033. $this->view->assign('steps', $bundle['steps']);
  6034. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6035. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6036. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6037. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6038. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6039. $this->view->assign('processCount', count($mergeRows));
  6040. $this->view->assign('detailRows', $details);
  6041. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6042. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6043. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6044. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6045. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6046. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6047. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6048. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6049. $this->view->assign('operLogs', $operLogs);
  6050. $sg = $quoteView['supplier_groups'] ?? [];
  6051. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6052. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6053. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6054. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6055. return [
  6056. 'ok' => $main !== [] || $details !== [],
  6057. 'ccydh' => $ccydh,
  6058. 'steps' => $bundle['steps'],
  6059. ];
  6060. }
  6061. /**
  6062. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6063. */
  6064. public function details()
  6065. {
  6066. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6067. if (is_array($ids)) {
  6068. $ids = isset($ids[0]) ? $ids[0] : '';
  6069. }
  6070. $ids = trim((string)$ids);
  6071. if ($ids === '') {
  6072. $this->error(__('Invalid parameters'));
  6073. }
  6074. $this->assertManualOrderDetailsViewable((int)$ids);
  6075. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6076. $sid = (int)$ids;
  6077. if ($this->isValidScydgyRowId($sid)) {
  6078. try {
  6079. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6080. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6081. $this->refreshCompletedOrderArchivePdf($sid, true);
  6082. }
  6083. } catch (\Throwable $e) {
  6084. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6085. }
  6086. }
  6087. $this->prepareProcuremenDetailsView($ids);
  6088. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6089. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6090. $this->view->engine->layout(false);
  6091. try {
  6092. return $this->view->fetch('procuremen/details_dialog_shell');
  6093. } finally {
  6094. if ($restoreLayout) {
  6095. $this->view->engine->layout($restoreLayout);
  6096. }
  6097. }
  6098. }
  6099. /**
  6100. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6101. *
  6102. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6103. * @return string 本地 web 路径或 OSS URL,失败为空串
  6104. */
  6105. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6106. {
  6107. if (!$this->isValidScydgyRowId($scydgyId)) {
  6108. return '';
  6109. }
  6110. try {
  6111. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6112. } catch (\Throwable $e) {
  6113. $po = null;
  6114. }
  6115. if (!is_array($po) || $po === []) {
  6116. return '';
  6117. }
  6118. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6119. return trim((string)($po['pdf_url'] ?? ''));
  6120. }
  6121. $poId = (int)($po['id'] ?? 0);
  6122. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6123. }
  6124. /**
  6125. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6126. */
  6127. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6128. {
  6129. if ((int)$scydgyId === 0) {
  6130. return '';
  6131. }
  6132. try {
  6133. $ctl = new class extends Procuremen {
  6134. public function _initialize()
  6135. {
  6136. $this->request = \think\Request::instance();
  6137. $tpl = \think\Config::get('template');
  6138. if (!is_array($tpl)) {
  6139. $tpl = [];
  6140. }
  6141. // CLI / 跨模块调用时无 admin 视图目录
  6142. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6143. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6144. $this->model = new \app\admin\model\Procuremen();
  6145. try {
  6146. ProcuremenSchema::ensureAll();
  6147. } catch (\Throwable $e) {
  6148. }
  6149. }
  6150. public function runRegen(int $sid, bool $requireCompleted): string
  6151. {
  6152. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6153. }
  6154. };
  6155. return $ctl->runRegen($scydgyId, $requireCompleted);
  6156. } catch (\Throwable $e) {
  6157. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6158. return '';
  6159. }
  6160. }
  6161. /**
  6162. * 解析合并审核工序行(订单号须一致,且均未协助)
  6163. *
  6164. * @return array<int, array<string, mixed>>
  6165. */
  6166. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6167. {
  6168. $primary = json_decode($rowJson, true);
  6169. if (!is_array($primary)) {
  6170. $this->error(__('Invalid parameters'));
  6171. }
  6172. $merge = json_decode($mergeRowsJson, true);
  6173. if (!is_array($merge) || $merge === []) {
  6174. $merge = [$primary];
  6175. }
  6176. $seen = [];
  6177. $out = [];
  6178. foreach ($merge as $r) {
  6179. if (!is_array($r)) {
  6180. continue;
  6181. }
  6182. $id = $this->extractScydgyRowId($r);
  6183. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6184. continue;
  6185. }
  6186. $seen[$id] = true;
  6187. $out[] = $r;
  6188. }
  6189. if ($out === []) {
  6190. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6191. }
  6192. $ccydh = null;
  6193. foreach ($out as $r) {
  6194. $dh = trim((string)($r['CCYDH'] ?? ''));
  6195. if ($ccydh === null) {
  6196. $ccydh = $dh;
  6197. } elseif ($dh !== $ccydh) {
  6198. $this->error('合并审核要求所选行的订单号一致');
  6199. }
  6200. }
  6201. $ids = [];
  6202. foreach ($out as $r) {
  6203. $id = $this->extractScydgyRowId($r);
  6204. if ($this->isValidScydgyRowId($id)) {
  6205. $ids[$id] = true;
  6206. }
  6207. }
  6208. $poBySid = [];
  6209. $detCntBySid = [];
  6210. if ($ids !== []) {
  6211. $idList = array_keys($ids);
  6212. try {
  6213. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6214. if (is_array($poList)) {
  6215. foreach ($poList as $po) {
  6216. if (!is_array($po)) {
  6217. continue;
  6218. }
  6219. $sid = (int)($po['scydgy_id'] ?? 0);
  6220. if ($this->isValidScydgyRowId($sid)) {
  6221. $poBySid[$sid] = $po;
  6222. }
  6223. }
  6224. }
  6225. } catch (\Throwable $e) {
  6226. }
  6227. try {
  6228. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6229. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6230. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6231. if (is_array($detRows)) {
  6232. foreach ($detRows as $dr) {
  6233. if (!is_array($dr)) {
  6234. continue;
  6235. }
  6236. $sid = (int)($dr['scydgy_id'] ?? 0);
  6237. if ($this->isValidScydgyRowId($sid)) {
  6238. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6239. }
  6240. }
  6241. }
  6242. } catch (\Throwable $e) {
  6243. }
  6244. }
  6245. foreach ($out as $r) {
  6246. $id = $this->extractScydgyRowId($r);
  6247. if (!$this->isValidScydgyRowId($id)) {
  6248. continue;
  6249. }
  6250. $po = $poBySid[$id] ?? null;
  6251. if (!is_array($po)) {
  6252. continue;
  6253. }
  6254. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6255. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6256. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6257. }
  6258. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6259. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6260. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6261. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6262. }
  6263. }
  6264. return $out;
  6265. }
  6266. /**
  6267. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6268. */
  6269. protected function maskSupplierContactFields(array $item): array
  6270. {
  6271. if (array_key_exists('email', $item)) {
  6272. $item['email'] = mask_email((string)$item['email']);
  6273. }
  6274. if (array_key_exists('phone', $item)) {
  6275. $item['phone'] = mask_phone((string)$item['phone']);
  6276. }
  6277. return $item;
  6278. }
  6279. /**
  6280. * @param array<int, array<string, mixed>> $list
  6281. * @return array<int, array<string, mixed>>
  6282. */
  6283. protected function maskSupplierContactList(array $list): array
  6284. {
  6285. $out = [];
  6286. foreach ($list as $item) {
  6287. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6288. }
  6289. return $out;
  6290. }
  6291. /**
  6292. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6293. *
  6294. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6295. * @return array<string, string>|null
  6296. */
  6297. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6298. {
  6299. if (!is_array($row)) {
  6300. return null;
  6301. }
  6302. $norm = [];
  6303. foreach ($row as $k => $v) {
  6304. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6305. }
  6306. $row = $norm;
  6307. $st = $row['status'] ?? '';
  6308. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6309. return null;
  6310. }
  6311. $companyName = '';
  6312. foreach (['company_name', 'name'] as $nk) {
  6313. if (!empty($row[$nk])) {
  6314. $companyName = trim((string)$row[$nk]);
  6315. break;
  6316. }
  6317. }
  6318. if ($companyName === '') {
  6319. return null;
  6320. }
  6321. $username = '';
  6322. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6323. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6324. $username = trim((string)$row[$uk]);
  6325. break;
  6326. }
  6327. }
  6328. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6329. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6330. if ($phone === '' && isset($row['account'])) {
  6331. $phone = trim((string)$row['account']);
  6332. }
  6333. if ($phone === '' && isset($row['mobile'])) {
  6334. $phone = trim((string)$row['mobile']);
  6335. }
  6336. if ($requireContactChannels && $email === '' && $phone === '') {
  6337. return null;
  6338. }
  6339. $category = '';
  6340. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6341. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6342. $category = trim((string)$row[$ck]);
  6343. break;
  6344. }
  6345. }
  6346. return [
  6347. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6348. 'name' => $companyName,
  6349. 'company_name' => $companyName,
  6350. 'username' => $username,
  6351. 'email' => $email,
  6352. 'phone' => $phone,
  6353. 'category' => $category,
  6354. 'company_type' => $category,
  6355. ];
  6356. }
  6357. /**
  6358. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6359. */
  6360. protected function resolveCustomerContactById(string $id): ?array
  6361. {
  6362. $id = trim($id);
  6363. if ($id === '' || !ctype_digit($id)) {
  6364. return null;
  6365. }
  6366. try {
  6367. $row = Db::table('customer')->where('id', (int)$id)->find();
  6368. } catch (\Throwable $e) {
  6369. return null;
  6370. }
  6371. return $this->buildCustomerContactPayloadFromRow($row);
  6372. }
  6373. /**
  6374. * 按供应商名称解析联系信息(兼容旧提交数据)
  6375. *
  6376. * @param bool $requireContactChannels true 时须有邮箱或手机
  6377. */
  6378. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6379. {
  6380. $name = trim($name);
  6381. if ($name === '') {
  6382. return null;
  6383. }
  6384. try {
  6385. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6386. $row = Db::table('customer')
  6387. ->where('company_name', $name)
  6388. ->order('id', 'desc')
  6389. ->find();
  6390. } catch (\Throwable $e) {
  6391. return null;
  6392. }
  6393. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6394. }
  6395. /**
  6396. * 规范化下发/确认时勾选的供应商
  6397. *
  6398. * @param array<int, mixed> $companies
  6399. * @return array<int, array<string, string>>
  6400. */
  6401. protected function normalizePickCompanies(array $companies): array
  6402. {
  6403. $out = [];
  6404. foreach ($companies as $c) {
  6405. if (!is_array($c)) {
  6406. continue;
  6407. }
  6408. $resolved = null;
  6409. $cid = trim((string)($c['id'] ?? ''));
  6410. if ($cid !== '') {
  6411. $resolved = $this->resolveCustomerContactById($cid);
  6412. }
  6413. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6414. if ($resolved === null && $name !== '') {
  6415. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6416. }
  6417. if ($resolved === null) {
  6418. continue;
  6419. }
  6420. $out[] = $resolved;
  6421. }
  6422. return $out;
  6423. }
  6424. /**
  6425. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6426. *
  6427. * @param array<int, array<string, mixed>> $pool
  6428. * @return array<int, array<string, mixed>>
  6429. */
  6430. protected function collapseProcuremenPoolByOrder(array $pool): array
  6431. {
  6432. if ($pool === []) {
  6433. return [];
  6434. }
  6435. $groups = [];
  6436. foreach ($pool as $row) {
  6437. if (!is_array($row)) {
  6438. continue;
  6439. }
  6440. $dh = trim((string)($row['CCYDH'] ?? ''));
  6441. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6442. if (!isset($groups[$key])) {
  6443. $groups[$key] = [];
  6444. }
  6445. $groups[$key][] = $row;
  6446. }
  6447. $out = [];
  6448. foreach ($groups as $ccydh => $rows) {
  6449. if ($rows === []) {
  6450. continue;
  6451. }
  6452. usort($rows, function ($a, $b) {
  6453. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6454. });
  6455. $head = $rows[0];
  6456. $gymcList = [];
  6457. foreach ($rows as $r) {
  6458. $g = trim((string)($r['CGYMC'] ?? ''));
  6459. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6460. $gymcList[] = $g;
  6461. }
  6462. }
  6463. $merged = $head;
  6464. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6465. $merged['process_count'] = count($rows);
  6466. $merged['_order_merge_rows'] = $rows;
  6467. $qtyList = [];
  6468. $priceList = [];
  6469. foreach ($rows as $r) {
  6470. if (!is_array($r)) {
  6471. continue;
  6472. }
  6473. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6474. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6475. }
  6476. if (count($rows) > 1) {
  6477. $merged['CGYMC'] = implode('、', $gymcList);
  6478. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6479. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6480. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6481. } else {
  6482. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6483. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6484. }
  6485. // 已选供应商:取合并行中首个非空 pick_company_name
  6486. $pickedName = '';
  6487. foreach ($rows as $r) {
  6488. if (!is_array($r)) {
  6489. continue;
  6490. }
  6491. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6492. if ($pn !== '') {
  6493. $pickedName = $pn;
  6494. break;
  6495. }
  6496. }
  6497. if ($pickedName !== '') {
  6498. $merged['pick_company_name'] = $pickedName;
  6499. $merged['picked_supplier_name'] = $pickedName;
  6500. }
  6501. $mergedPickTime = '';
  6502. foreach ($rows as $r) {
  6503. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6504. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6505. $mergedPickTime = $t;
  6506. }
  6507. }
  6508. if ($mergedPickTime !== '') {
  6509. $merged['pick_time'] = $mergedPickTime;
  6510. }
  6511. $out[] = $merged;
  6512. }
  6513. usort($out, function ($a, $b) {
  6514. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6515. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6516. if ($ta === $tb) {
  6517. $ida = (int)($a['purchase_order_id'] ?? 0);
  6518. $idb = (int)($b['purchase_order_id'] ?? 0);
  6519. if ($ida !== $idb) {
  6520. return $idb <=> $ida;
  6521. }
  6522. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6523. }
  6524. if ($ta === '') {
  6525. return 1;
  6526. }
  6527. if ($tb === '') {
  6528. return -1;
  6529. }
  6530. return strcmp($tb, $ta);
  6531. });
  6532. return $out;
  6533. }
  6534. /**
  6535. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6536. *
  6537. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6538. */
  6539. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6540. {
  6541. $scydgyId = trim($scydgyId);
  6542. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6543. if ($scydgyId === '') {
  6544. return $empty;
  6545. }
  6546. try {
  6547. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6548. } catch (\Throwable $e) {
  6549. $anchor = null;
  6550. }
  6551. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6552. return $empty;
  6553. }
  6554. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6555. if ($ccydh === '') {
  6556. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6557. }
  6558. try {
  6559. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6560. } catch (\Throwable $e) {
  6561. $pos = [$anchor];
  6562. }
  6563. if (!is_array($pos) || $pos === []) {
  6564. $pos = [$anchor];
  6565. }
  6566. return [
  6567. 'ccydh' => $ccydh,
  6568. 'pos' => $pos,
  6569. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6570. ];
  6571. }
  6572. /**
  6573. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6574. */
  6575. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6576. {
  6577. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6578. return false;
  6579. }
  6580. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6581. return false;
  6582. }
  6583. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6584. return true;
  6585. }
  6586. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6587. $sid = (int)($po['scydgy_id'] ?? 0);
  6588. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6589. }
  6590. return false;
  6591. }
  6592. /**
  6593. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6594. *
  6595. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6596. */
  6597. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6598. {
  6599. $scydgyId = trim($scydgyId);
  6600. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6601. if ($scydgyId === '') {
  6602. return $empty;
  6603. }
  6604. try {
  6605. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6606. } catch (\Throwable $e) {
  6607. $anchor = null;
  6608. }
  6609. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6610. return $empty;
  6611. }
  6612. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6613. if ($ccydh === '') {
  6614. return [
  6615. 'ccydh' => '',
  6616. 'pos' => [$anchor],
  6617. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6618. ];
  6619. }
  6620. try {
  6621. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6622. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6623. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6624. } catch (\Throwable $e) {
  6625. $pos = [$anchor];
  6626. }
  6627. if (!is_array($pos) || $pos === []) {
  6628. $pos = [$anchor];
  6629. }
  6630. $pos = array_values(array_filter($pos, function ($po) {
  6631. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6632. }));
  6633. if ($pos === []) {
  6634. $pos = [$anchor];
  6635. }
  6636. return [
  6637. 'ccydh' => $ccydh,
  6638. 'pos' => $pos,
  6639. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6640. ];
  6641. }
  6642. /**
  6643. * @param array<int, array<string, mixed>> $purchaseOrders
  6644. * @return array<int, array<string, mixed>>
  6645. */
  6646. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6647. {
  6648. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6649. $byId = [];
  6650. foreach ($pool as $r) {
  6651. if (!is_array($r)) {
  6652. continue;
  6653. }
  6654. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6655. if ($this->isValidScydgyRowId($sid)) {
  6656. $byId[$sid] = $r;
  6657. }
  6658. }
  6659. $out = [];
  6660. foreach ($purchaseOrders as $po) {
  6661. if (!is_array($po)) {
  6662. continue;
  6663. }
  6664. $sid = (int)($po['scydgy_id'] ?? 0);
  6665. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6666. $out[] = $byId[$sid];
  6667. }
  6668. }
  6669. return $out;
  6670. }
  6671. /**
  6672. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6673. *
  6674. * @return array<int, array<string, mixed>>
  6675. */
  6676. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6677. {
  6678. $scydgyId = trim($scydgyId);
  6679. if ($scydgyId === '') {
  6680. return [];
  6681. }
  6682. try {
  6683. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6684. } catch (\Throwable $e) {
  6685. $anchor = null;
  6686. }
  6687. if (!is_array($anchor)) {
  6688. return [];
  6689. }
  6690. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6691. return [];
  6692. }
  6693. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6694. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6695. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6696. try {
  6697. $q = Db::table('purchase_order');
  6698. if ($ccydh !== '') {
  6699. $q->where('CCYDH', $ccydh);
  6700. } else {
  6701. $q->where('scydgy_id', $scydgyId);
  6702. }
  6703. if ($isValidPick) {
  6704. $q->where('pick_time', $pickTime);
  6705. }
  6706. $pos = $q->order('scydgy_id', 'asc')->select();
  6707. } catch (\Throwable $e) {
  6708. $pos = [$anchor];
  6709. }
  6710. if (!is_array($pos) || $pos === []) {
  6711. $pos = [$anchor];
  6712. }
  6713. $pos = array_values(array_filter($pos, function ($po) {
  6714. if (!is_array($po)) {
  6715. return false;
  6716. }
  6717. $mr = $po['mod_rq'] ?? null;
  6718. if ($mr === null || $mr === '') {
  6719. return true;
  6720. }
  6721. $mrs = trim((string)$mr);
  6722. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6723. }));
  6724. if ($pos === []) {
  6725. $pos = [$anchor];
  6726. }
  6727. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6728. if ($rows === []) {
  6729. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6730. }
  6731. return $rows;
  6732. }
  6733. /**
  6734. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6735. *
  6736. * @param array<int, array<string, mixed>> $mergeRows
  6737. * @return array<int, array<string, mixed>>
  6738. */
  6739. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6740. {
  6741. $list = array_values($mergeRows);
  6742. $n = count($list);
  6743. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6744. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6745. $mergeSame = $n > 1 && $orderKey0 !== '';
  6746. if ($mergeSame) {
  6747. foreach ($list as $rr) {
  6748. if (!is_array($rr)) {
  6749. $mergeSame = false;
  6750. break;
  6751. }
  6752. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6753. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6754. $mergeSame = false;
  6755. break;
  6756. }
  6757. }
  6758. }
  6759. $out = [];
  6760. foreach ($list as $idx => $r) {
  6761. if (!is_array($r)) {
  6762. continue;
  6763. }
  6764. $qty = $this->resolveProcuremenThisQuantity($r);
  6765. $price = $this->resolveProcuremenCeilingPrice($r);
  6766. $sid = $this->extractScydgyRowId($r);
  6767. $out[] = [
  6768. 'seq' => $idx + 1,
  6769. 'scydgy_id' => $sid,
  6770. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6771. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6772. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6773. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6774. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6775. 'NGZL' => $r['NGZL'] ?? '',
  6776. 'This_quantity' => $qty,
  6777. 'ceilingPrice' => $price,
  6778. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6779. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6780. 'show_order_cells' => !$mergeSame || $idx === 0,
  6781. 'order_rowspan' => $mergeSame ? $n : 1,
  6782. ];
  6783. }
  6784. return $out;
  6785. }
  6786. /**
  6787. * 解析金额/数量(去千分位等非数字字符)
  6788. */
  6789. protected function parseProcuremenMoneyNumber($value): ?float
  6790. {
  6791. if ($value === null || $value === '') {
  6792. return null;
  6793. }
  6794. if (is_numeric($value)) {
  6795. return (float)$value;
  6796. }
  6797. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6798. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6799. }
  6800. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6801. {
  6802. if ($amount === null) {
  6803. return '';
  6804. }
  6805. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6806. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6807. return $s === '' ? '0' : $s;
  6808. }
  6809. /**
  6810. * 列表/详情展示:工作量为 0 时显示空
  6811. */
  6812. protected function formatProcuremenWorkloadDisplay($value): string
  6813. {
  6814. if ($value === null || $value === '') {
  6815. return '';
  6816. }
  6817. $s = trim((string)$value);
  6818. if ($s === '') {
  6819. return '';
  6820. }
  6821. if (is_numeric($s) && (float)$s == 0) {
  6822. return '';
  6823. }
  6824. return $s;
  6825. }
  6826. /**
  6827. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6828. */
  6829. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6830. {
  6831. foreach ($details as $d) {
  6832. if (!is_array($d)) {
  6833. continue;
  6834. }
  6835. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6836. $cn = trim((string)($d['company_name'] ?? ''));
  6837. if ($cn !== '') {
  6838. return $cn;
  6839. }
  6840. }
  6841. }
  6842. return trim((string)($main['pick_company_name'] ?? ''));
  6843. }
  6844. /**
  6845. * 详情报价小计:单价 × 本工序本次数量
  6846. */
  6847. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6848. {
  6849. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6850. if ($unit === null) {
  6851. return null;
  6852. }
  6853. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6854. if ($qty === null || $qty <= 0) {
  6855. return null;
  6856. }
  6857. return $unit * $qty;
  6858. }
  6859. /**
  6860. * 详情页:工序小计 + 供应商分组报价与总计
  6861. *
  6862. * @param array<int, array<string, mixed>> $mergeRows
  6863. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6864. * @return array{
  6865. * process_rows: array,
  6866. * supplier_groups: array,
  6867. * order_total_text: string,
  6868. * order_total_has: bool,
  6869. * selected_company: string
  6870. * }
  6871. */
  6872. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6873. {
  6874. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6875. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6876. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6877. || ((int)($main['manual_pick'] ?? 0) === 1);
  6878. $qtyBySid = [];
  6879. $gymcBySid = [];
  6880. $orderedSids = [];
  6881. foreach ($mergeRows as $mr) {
  6882. if (!is_array($mr)) {
  6883. continue;
  6884. }
  6885. $sid = $this->extractScydgyRowId($mr);
  6886. if ($this->isValidScydgyRowId($sid)) {
  6887. $orderedSids[] = $sid;
  6888. }
  6889. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6890. if ($qty === '') {
  6891. $qty = trim((string)($mr['NGZL'] ?? ''));
  6892. }
  6893. $qtyBySid[$sid] = $qty;
  6894. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6895. }
  6896. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6897. $detailByCompanySid = [];
  6898. foreach ($details as $d) {
  6899. if (!is_array($d)) {
  6900. continue;
  6901. }
  6902. $cn = trim((string)($d['company_name'] ?? ''));
  6903. $sid = (int)($d['scydgy_id'] ?? 0);
  6904. if ($cn === '' || $sid === 0) {
  6905. continue;
  6906. }
  6907. if (!isset($detailByCompanySid[$cn])) {
  6908. $detailByCompanySid[$cn] = [];
  6909. }
  6910. $detailByCompanySid[$cn][$sid] = $d;
  6911. }
  6912. $supplierGroups = [];
  6913. foreach ($detailByCompanySid as $cn => $bySid) {
  6914. $lines = [];
  6915. $groupTotal = 0.0;
  6916. $groupHas = false;
  6917. $groupVoid = true;
  6918. $usedSids = [];
  6919. $appendLine = function (int $sid, array $d) use (
  6920. &$lines,
  6921. &$groupTotal,
  6922. &$groupHas,
  6923. &$groupVoid,
  6924. $qtyBySid,
  6925. $gymcBySid,
  6926. $quoteVisible
  6927. ) {
  6928. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6929. if (!$isVoid) {
  6930. $groupVoid = false;
  6931. }
  6932. $qtyStr = $qtyBySid[$sid] ?? '';
  6933. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6934. $am = trim((string)($d['amount'] ?? ''));
  6935. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6936. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6937. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6938. $sub = null;
  6939. if (!$isVoid && $amountNum !== null) {
  6940. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6941. }
  6942. $ct = $this->resolveDetailSupplierOperTime($d);
  6943. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6944. $leadFilled = ($leadDays !== null);
  6945. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6946. $line = [
  6947. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6948. 'amount' => $am,
  6949. 'unit_price_text' => $amountFilled
  6950. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6951. : '未填写',
  6952. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6953. 'delivery_ymd' => $deliveryYmd,
  6954. 'amount_filled' => $amountFilled,
  6955. 'delivery_filled' => $deliveryFilled,
  6956. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6957. 'lead_days' => $leadFilled ? $leadDays : '',
  6958. 'lead_days_filled'=> $leadFilled,
  6959. 'lead_days_show' => $leadText,
  6960. 'lead_days_text' => $leadText,
  6961. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6962. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6963. 'is_void' => $isVoid,
  6964. 'oper_time_text' => $ct,
  6965. ];
  6966. if (!$quoteVisible && !$isVoid) {
  6967. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6968. } elseif ($sub !== null) {
  6969. $groupTotal += $sub;
  6970. $groupHas = true;
  6971. }
  6972. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6973. };
  6974. foreach ($orderedSids as $sid) {
  6975. if (!isset($bySid[$sid])) {
  6976. continue;
  6977. }
  6978. $usedSids[$sid] = true;
  6979. $appendLine($sid, $bySid[$sid]);
  6980. }
  6981. foreach ($bySid as $sid => $d) {
  6982. if (isset($usedSids[$sid])) {
  6983. continue;
  6984. }
  6985. $appendLine((int)$sid, $d);
  6986. }
  6987. $firstDetail = null;
  6988. foreach ($bySid as $d) {
  6989. if (is_array($d)) {
  6990. $firstDetail = $d;
  6991. break;
  6992. }
  6993. }
  6994. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6995. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6996. if ($username === '' && $ph !== '') {
  6997. $username = $this->resolveCustomerContactName($ph, $cn);
  6998. }
  6999. $remark = '';
  7000. foreach ($bySid as $d) {
  7001. if (!is_array($d)) {
  7002. continue;
  7003. }
  7004. $rm = '';
  7005. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  7006. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  7007. $rm = trim((string)$d[$rk]);
  7008. break;
  7009. }
  7010. }
  7011. if ($rm !== '') {
  7012. $remark = $rm;
  7013. break;
  7014. }
  7015. }
  7016. $lineCount = count($lines);
  7017. $hasRemark = $lineCount > 0;
  7018. $supplierGroup = [
  7019. 'company_name' => $cn,
  7020. 'username' => $username,
  7021. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  7022. 'phone' => $ph,
  7023. 'remark' => $remark,
  7024. 'has_remark' => $hasRemark,
  7025. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  7026. 'is_void' => $groupVoid,
  7027. 'lines' => $lines,
  7028. 'line_count' => $lineCount,
  7029. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  7030. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  7031. 'has_total' => $lineCount > 0,
  7032. ];
  7033. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  7034. $supplierGroups[] = $supplierGroup;
  7035. }
  7036. usort($supplierGroups, function ($a, $b) {
  7037. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  7038. return ($a['is_void'] ?? false) ? 1 : -1;
  7039. }
  7040. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  7041. return ($a['is_selected'] ?? false) ? -1 : 1;
  7042. }
  7043. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  7044. });
  7045. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  7046. return [
  7047. 'process_rows' => $processRows,
  7048. 'supplier_groups' => $supplierGroups,
  7049. 'order_total_text' => '',
  7050. 'order_total_has' => false,
  7051. 'selected_company' => $selectedCompany,
  7052. ];
  7053. }
  7054. /**
  7055. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  7056. */
  7057. protected function buildProcessLinesPlain(array $mergeRows): string
  7058. {
  7059. $lines = [];
  7060. $i = 1;
  7061. foreach ($mergeRows as $r) {
  7062. if (!is_array($r)) {
  7063. continue;
  7064. }
  7065. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7066. $dw = trim((string)($r['CDW'] ?? ''));
  7067. $gzl = trim((string)($r['NGZL'] ?? ''));
  7068. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7069. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  7070. if ($dw !== '') {
  7071. $parts[] = '单位:' . $dw;
  7072. }
  7073. if ($gzl !== '') {
  7074. $parts[] = '工作量:' . $gzl;
  7075. }
  7076. if ($qty !== '') {
  7077. $parts[] = '本次数量:' . $qty;
  7078. }
  7079. $lines[] = implode(' ', $parts);
  7080. $i++;
  7081. }
  7082. return implode("\n", $lines);
  7083. }
  7084. /**
  7085. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  7086. *
  7087. * @return array<string, string>
  7088. */
  7089. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  7090. {
  7091. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  7092. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  7093. }
  7094. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  7095. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  7096. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7097. $cyjmc = '';
  7098. foreach ($mergeRows as $mr) {
  7099. if (!is_array($mr)) {
  7100. continue;
  7101. }
  7102. if ($ccydh === '') {
  7103. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  7104. }
  7105. if ($cyjmc === '') {
  7106. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  7107. }
  7108. }
  7109. if ($pos !== []) {
  7110. $firstPo = $pos[0];
  7111. if (is_array($firstPo)) {
  7112. if ($ccydh === '') {
  7113. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  7114. }
  7115. if ($cyjmc === '') {
  7116. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  7117. }
  7118. }
  7119. }
  7120. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  7121. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  7122. if (is_array($any)) {
  7123. if ($ccydh === '') {
  7124. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  7125. }
  7126. if ($cyjmc === '') {
  7127. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  7128. }
  7129. }
  7130. }
  7131. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  7132. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  7133. $cgymc = '';
  7134. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  7135. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  7136. }
  7137. return [
  7138. 'ccydh' => $ccydh,
  7139. 'cyjmc' => $cyjmc,
  7140. 'cgymc' => $cgymc,
  7141. 'process_lines' => $processLines,
  7142. 'process_lines_html' => '',
  7143. ];
  7144. }
  7145. /**
  7146. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  7147. */
  7148. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  7149. {
  7150. $lines = [];
  7151. if ($ccydh !== '') {
  7152. $lines[] = '订单号:' . $ccydh;
  7153. }
  7154. if ($cyjmc !== '') {
  7155. $lines[] = '印件名称:' . $cyjmc;
  7156. }
  7157. if ($processPlain !== '') {
  7158. $lines[] = $processPlain;
  7159. }
  7160. return implode("\n", $lines);
  7161. }
  7162. /**
  7163. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  7164. *
  7165. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7166. */
  7167. protected function buildPlatformLinksPlain(array $detailLinks): string
  7168. {
  7169. $lines = [];
  7170. $i = 1;
  7171. foreach ($detailLinks as $lk) {
  7172. if (!is_array($lk)) {
  7173. continue;
  7174. }
  7175. $url = trim((string)($lk['url'] ?? ''));
  7176. if ($url === '') {
  7177. continue;
  7178. }
  7179. $label = trim((string)($lk['cgymc'] ?? ''));
  7180. if ($label === '') {
  7181. $label = '工序' . $i;
  7182. }
  7183. $lines[] = $label . ':' . $url;
  7184. $i++;
  7185. }
  7186. return implode("\n", $lines);
  7187. }
  7188. /**
  7189. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  7190. *
  7191. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7192. */
  7193. protected function buildPlatformLinksHtml(array $detailLinks): string
  7194. {
  7195. $parts = [];
  7196. $i = 1;
  7197. foreach ($detailLinks as $lk) {
  7198. if (!is_array($lk)) {
  7199. continue;
  7200. }
  7201. $url = trim((string)($lk['url'] ?? ''));
  7202. if ($url === '') {
  7203. continue;
  7204. }
  7205. $label = trim((string)($lk['cgymc'] ?? ''));
  7206. if ($label === '') {
  7207. $label = '工序' . $i;
  7208. }
  7209. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7210. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7211. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7212. $i++;
  7213. }
  7214. return implode("<br>\n", $parts);
  7215. }
  7216. /**
  7217. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7218. *
  7219. * @return array<string, mixed>
  7220. */
  7221. protected function loadMailerConfig(): array
  7222. {
  7223. try {
  7224. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7225. } catch (\Throwable $e) {
  7226. $cfg = [];
  7227. }
  7228. return is_array($cfg) ? $cfg : [];
  7229. }
  7230. protected function loadNotifyTemplateRow(string $scene): ?array
  7231. {
  7232. try {
  7233. $row = Db::table('purchase_sms_template')
  7234. ->where('scene', $scene)
  7235. ->where(function ($q) {
  7236. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7237. })
  7238. ->order('id', 'asc')
  7239. ->find();
  7240. } catch (\Throwable $e) {
  7241. return null;
  7242. }
  7243. if (!is_array($row) || $row === []) {
  7244. return null;
  7245. }
  7246. return [
  7247. 'title' => trim((string)($row['title'] ?? '')),
  7248. 'content' => trim((string)($row['content'] ?? '')),
  7249. ];
  7250. }
  7251. /**
  7252. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7253. */
  7254. protected function buildProcessLinesHtml(array $mergeRows): string
  7255. {
  7256. if (count($mergeRows) <= 1) {
  7257. $r = $mergeRows[0] ?? [];
  7258. if (!is_array($r)) {
  7259. return '';
  7260. }
  7261. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7262. $dw = trim((string)($r['CDW'] ?? ''));
  7263. $gzl = trim((string)($r['NGZL'] ?? ''));
  7264. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7265. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7266. if ($dw !== '') {
  7267. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7268. }
  7269. if ($gzl !== '') {
  7270. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7271. }
  7272. if ($qty !== '') {
  7273. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7274. }
  7275. return $html;
  7276. }
  7277. $rows = '';
  7278. $i = 1;
  7279. foreach ($mergeRows as $r) {
  7280. if (!is_array($r)) {
  7281. continue;
  7282. }
  7283. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7284. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7285. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7286. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7287. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7288. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7289. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7290. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7291. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7292. $i++;
  7293. }
  7294. if ($rows === '') {
  7295. return '';
  7296. }
  7297. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7298. . '<thead><tr style="background:#f5f5f5;">'
  7299. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7300. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7301. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7302. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7303. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7304. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7305. }
  7306. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7307. {
  7308. $sysRq = trim($sysRq);
  7309. if ($sysRq === '') {
  7310. if ($required) {
  7311. $this->error('请选择招标截止日期');
  7312. }
  7313. return '';
  7314. }
  7315. $ts = strtotime($sysRq);
  7316. if ($ts === false || $ts <= 0) {
  7317. $this->error('招标截止日期格式无效');
  7318. }
  7319. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7320. if (!$allowPast) {
  7321. $ymd = date('Y-m-d', $ts);
  7322. if ($ymd < date('Y-m-d')) {
  7323. $this->error('招标截止日期不能早于今天');
  7324. }
  7325. if ($ts <= time()) {
  7326. $this->error('招标截止时间不能早于当前时间');
  7327. }
  7328. }
  7329. return date('Y-m-d H:i:s', $ts);
  7330. }
  7331. /**
  7332. * 确保 purchase_order.czlyq(类型)存在
  7333. */
  7334. protected function ensurePurchaseOrderCzlyqColumn(): void
  7335. {
  7336. static $done = false;
  7337. if ($done) {
  7338. return;
  7339. }
  7340. $done = true;
  7341. try {
  7342. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7343. if (empty($cols)) {
  7344. Db::execute(
  7345. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7346. );
  7347. }
  7348. } catch (\Throwable $e) {
  7349. // ignore
  7350. }
  7351. }
  7352. /**
  7353. * 确保 purchase_order.delivery_deadline 存在
  7354. */
  7355. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7356. {
  7357. static $done = false;
  7358. if ($done) {
  7359. return;
  7360. }
  7361. $done = true;
  7362. try {
  7363. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7364. if (empty($cols)) {
  7365. Db::execute(
  7366. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7367. );
  7368. }
  7369. } catch (\Throwable $e) {
  7370. // ignore
  7371. }
  7372. }
  7373. /**
  7374. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7375. */
  7376. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7377. {
  7378. static $done = false;
  7379. if ($done) {
  7380. return;
  7381. }
  7382. $done = true;
  7383. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7384. $adds = [
  7385. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7386. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7387. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7388. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7389. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7390. ];
  7391. $changed = false;
  7392. foreach ($adds as $col => $ddl) {
  7393. try {
  7394. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7395. if (!is_array($cols) || $cols === []) {
  7396. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7397. $changed = true;
  7398. }
  7399. } catch (\Throwable $e) {
  7400. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7401. }
  7402. }
  7403. if ($changed) {
  7404. $this->clearPurchaseOrderTableFieldsCache();
  7405. }
  7406. }
  7407. /**
  7408. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7409. */
  7410. protected function clearPurchaseOrderTableFieldsCache(): void
  7411. {
  7412. try {
  7413. $db = (string)Config::get('database.database');
  7414. $key = $db . '.purchase_order';
  7415. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7416. $ref->setAccessible(true);
  7417. $info = $ref->getValue();
  7418. if (is_array($info) && isset($info[$key])) {
  7419. unset($info[$key]);
  7420. $ref->setValue(null, $info);
  7421. }
  7422. } catch (\Throwable $e) {
  7423. }
  7424. try {
  7425. $db = (string)Config::get('database.database');
  7426. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7427. if (is_file($schemaFile)) {
  7428. @unlink($schemaFile);
  7429. }
  7430. } catch (\Throwable $e) {
  7431. }
  7432. }
  7433. /**
  7434. * @return array<string, bool>
  7435. */
  7436. protected function loadPurchaseOrderColumnSet(): array
  7437. {
  7438. static $set = null;
  7439. if (is_array($set)) {
  7440. return $set;
  7441. }
  7442. $set = [];
  7443. try {
  7444. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7445. } catch (\Throwable $e) {
  7446. return $set;
  7447. }
  7448. if (!is_array($cols)) {
  7449. return $set;
  7450. }
  7451. foreach ($cols as $c) {
  7452. if (!is_array($c)) {
  7453. continue;
  7454. }
  7455. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7456. if ($f !== '') {
  7457. $set[$f] = true;
  7458. }
  7459. }
  7460. return $set;
  7461. }
  7462. /**
  7463. * 解析交货截止日期(仅年月日)
  7464. */
  7465. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7466. {
  7467. $raw = trim($raw);
  7468. if ($raw === '') {
  7469. if ($required) {
  7470. $this->error('请选择交货截止日期');
  7471. }
  7472. return '';
  7473. }
  7474. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7475. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7476. } else {
  7477. $ts = strtotime(str_replace('/', '-', $raw));
  7478. if ($ts === false || $ts <= 0) {
  7479. $this->error('交货截止日期格式无效');
  7480. }
  7481. $ymd = date('Y-m-d', $ts);
  7482. }
  7483. if ($ymd < date('Y-m-d')) {
  7484. $this->error('交货截止日期不能早于今天');
  7485. }
  7486. return $ymd;
  7487. }
  7488. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7489. {
  7490. $s = trim((string)$value);
  7491. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7492. return '';
  7493. }
  7494. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7495. return $m[1];
  7496. }
  7497. $ts = strtotime(str_replace('/', '-', $s));
  7498. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7499. }
  7500. /**
  7501. * @param array{pos?:array} $bundle
  7502. */
  7503. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7504. {
  7505. foreach ($bundle['pos'] ?? [] as $po) {
  7506. if (!is_array($po)) {
  7507. continue;
  7508. }
  7509. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7510. if ($d !== '') {
  7511. return $d;
  7512. }
  7513. }
  7514. return '';
  7515. }
  7516. protected function formatProcuremenSysRqForInput($sysRq): string
  7517. {
  7518. $sr = trim((string)$sysRq);
  7519. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7520. return '';
  7521. }
  7522. $ts = strtotime($sr);
  7523. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7524. }
  7525. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7526. {
  7527. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7528. if ($sr === '') {
  7529. return '—';
  7530. }
  7531. $ts = strtotime($sr);
  7532. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7533. }
  7534. /**
  7535. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7536. *
  7537. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7538. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7539. */
  7540. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7541. {
  7542. return $bundle;
  7543. }
  7544. /**
  7545. * 写入/更新 purchase_order(单道工序行)
  7546. *
  7547. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7548. */
  7549. protected function upsertPurchaseOrderFromRow(
  7550. array $row,
  7551. string $sysRqDb,
  7552. $wflowStatus = null,
  7553. ?string $pickTime = null,
  7554. ?array $exists = null,
  7555. ?string $deliveryDeadline = null,
  7556. $scoreRuleId = null
  7557. ): void {
  7558. $ids = $this->extractScydgyRowId($row);
  7559. if (!$this->isValidScydgyRowId($ids)) {
  7560. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7561. }
  7562. if ($exists === null) {
  7563. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7564. }
  7565. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7566. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7567. $this->ensurePurchaseOrderCzlyqColumn();
  7568. $data = $this->normalizePurchaseOrderWritePayload([
  7569. 'scydgy_id' => $ids,
  7570. 'CCYDH' => $row['CCYDH'] ?? null,
  7571. 'CYJMC' => $row['CYJMC'] ?? null,
  7572. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7573. 'CDXMC' => $row['CDXMC'] ?? null,
  7574. 'CGYBH' => $row['CGYBH'] ?? null,
  7575. 'CGYMC' => $row['CGYMC'] ?? null,
  7576. 'CDW' => $row['CDW'] ?? null,
  7577. 'czlyq' => $row['czlyq'] ?? null,
  7578. 'NGZL' => $row['NGZL'] ?? null,
  7579. 'CDF' => $row['CDF'] ?? null,
  7580. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7581. 'MBZ' => $row['MBZ'] ?? null,
  7582. 'bwjg' => $row['bwjg'] ?? null,
  7583. 'iStatus' => $row['iStatus'] ?? null,
  7584. 'dStamp' => $row['dStamp'] ?? null,
  7585. 'dputrecord' => $row['dputrecord'] ?? null,
  7586. 'cywyxm' => $row['cywyxm'] ?? null,
  7587. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7588. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7589. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7590. 'sys_rq' => $sysRqDb,
  7591. ], $row);
  7592. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7593. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7594. if ($qtyUp === '') {
  7595. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7596. 'This_quantity' => '',
  7597. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7598. ]);
  7599. if ($qtyFallback !== '') {
  7600. $data['This_quantity'] = $qtyFallback;
  7601. }
  7602. }
  7603. if ($deliveryDeadline !== null) {
  7604. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7605. }
  7606. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7607. $scoreRule = null;
  7608. if (is_array($scoreRuleId)) {
  7609. $scoreRule = $scoreRuleId;
  7610. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7611. } else {
  7612. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7613. }
  7614. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7615. $poCols = $this->loadPurchaseOrderColumnSet();
  7616. if (!empty($poCols['score_rule_id'])) {
  7617. $data['score_rule_id'] = $scoreRuleId;
  7618. if (is_array($scoreRule)) {
  7619. if (!empty($poCols['score_rule_name'])) {
  7620. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7621. }
  7622. if (!empty($poCols['score_quality_weight'])) {
  7623. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7624. }
  7625. if (!empty($poCols['score_price_weight'])) {
  7626. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7627. }
  7628. if (!empty($poCols['score_lead_weight'])) {
  7629. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7630. }
  7631. }
  7632. }
  7633. }
  7634. if ($wflowStatus !== null && $wflowStatus !== '') {
  7635. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7636. }
  7637. if ($pickTime !== null && $pickTime !== '') {
  7638. $data['pick_time'] = $pickTime;
  7639. $data['pick_company_name'] = '';
  7640. }
  7641. if ($exists) {
  7642. $upd = $data;
  7643. unset($upd['scydgy_id']);
  7644. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7645. } else {
  7646. $data['createtime'] = date('Y-m-d H:i:s');
  7647. Db::table('purchase_order')->insert($data);
  7648. }
  7649. }
  7650. /**
  7651. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7652. *
  7653. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7654. */
  7655. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7656. {
  7657. $toDb = function ($value) {
  7658. if ($value === null) {
  7659. return null;
  7660. }
  7661. if (is_scalar($value)) {
  7662. return $value;
  7663. }
  7664. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7665. };
  7666. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7667. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7668. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7669. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7670. if ($username === '') {
  7671. $username = $this->resolveCustomerContactName($phone, $companyName);
  7672. }
  7673. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7674. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7675. }
  7676. if ($requirePhone && $phone === '') {
  7677. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7678. }
  7679. $detailLinks = [];
  7680. foreach ($mergeRows as $row) {
  7681. if (!is_array($row)) {
  7682. continue;
  7683. }
  7684. $sid = $this->extractScydgyRowId($row);
  7685. $detailId = 0;
  7686. if ($skipExisting) {
  7687. try {
  7688. $existsQuery = Db::table('purchase_order_detail')
  7689. ->where('scydgy_id', $sid)
  7690. ->where('company_name', $companyName);
  7691. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7692. $exists = $existsQuery->find();
  7693. } catch (\Throwable $e) {
  7694. $exists = null;
  7695. }
  7696. if (is_array($exists)) {
  7697. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7698. }
  7699. }
  7700. if ($detailId <= 0) {
  7701. $one = [
  7702. 'scydgy_id' => $toDb($sid),
  7703. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7704. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7705. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7706. 'username' => $username !== '' ? $username : null,
  7707. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7708. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7709. 'createtime' => date('Y-m-d H:i:s'),
  7710. 'status' => ProcuremenStatus::POD_UNPICKED,
  7711. 'status_name' => '未提交',
  7712. ];
  7713. Db::table('purchase_order_detail')->insert($one);
  7714. $detailId = (int)Db::getLastInsID();
  7715. }
  7716. $mprocUrl = '';
  7717. if ($buildMobileLinks && $detailId > 0) {
  7718. // 手工询价 → 待报价;协助下发 → 未提交
  7719. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  7720. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  7721. }
  7722. $detailLinks[] = [
  7723. 'detail_id' => $detailId,
  7724. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7725. 'url' => $mprocUrl,
  7726. ];
  7727. }
  7728. $this->invalidatePickHiddenScydgyCache();
  7729. return $detailLinks;
  7730. }
  7731. /**
  7732. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7733. * @return array<string, mixed>
  7734. */
  7735. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7736. {
  7737. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7738. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7739. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7740. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7741. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7742. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7743. $isMerge = !empty($ctx['is_merge']);
  7744. $contactName = trim((string)($c['username'] ?? ''));
  7745. if ($contactName === '') {
  7746. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7747. }
  7748. $notifyVars = [
  7749. 'company_name' => $companyName,
  7750. 'contact_name' => $contactName,
  7751. 'phone' => $phone,
  7752. 'email' => $toEmail,
  7753. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7754. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7755. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7756. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7757. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7758. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7759. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7760. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7761. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7762. 'platform_url' => $platformUrl,
  7763. 'platform_links' => $platformLinksPlain,
  7764. 'platform_links_html' => $platformLinksHtml,
  7765. ];
  7766. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7767. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7768. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7769. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7770. return [
  7771. 'company_name' => $companyName,
  7772. 'phone' => $phone,
  7773. 'email' => $toEmail,
  7774. 'sms_content' => $smsContent,
  7775. 'mail_plain' => $mailPlain,
  7776. 'mail_body' => $mailBody,
  7777. 'notify_vars' => $notifyVars,
  7778. 'detail_links' => $detailLinks,
  7779. ];
  7780. }
  7781. /**
  7782. * @param array<string, mixed> $chosen
  7783. * @param array<int, array<string, mixed>> $mergeRows
  7784. * @param array{ccydh:string, pos:array} $bundle
  7785. */
  7786. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7787. {
  7788. if (!$sendSms && !$sendEmail) {
  7789. return;
  7790. }
  7791. $companyName = trim((string)($chosen['name'] ?? ''));
  7792. $phone = trim((string)($chosen['phone'] ?? ''));
  7793. $toEmail = trim((string)($chosen['email'] ?? ''));
  7794. if ($companyName === '') {
  7795. throw new \Exception('供应商名称无效');
  7796. }
  7797. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7798. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7799. }
  7800. if ($sendSms && $phone === '') {
  7801. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7802. }
  7803. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7804. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  7805. $sids = [];
  7806. foreach ($mergeRows as $mr) {
  7807. if (!is_array($mr)) {
  7808. continue;
  7809. }
  7810. $sid = $this->extractScydgyRowId($mr);
  7811. if ($this->isValidScydgyRowId($sid)) {
  7812. $sids[$sid] = true;
  7813. }
  7814. }
  7815. if ($sids === []) {
  7816. throw new \Exception('未找到工序行,无法发送通知');
  7817. }
  7818. $sysRqNotify = '';
  7819. $pos = $bundle['pos'] ?? [];
  7820. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7821. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7822. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7823. $ts = strtotime($sr);
  7824. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7825. }
  7826. }
  7827. try {
  7828. $detailsQuery = Db::table('purchase_order_detail')
  7829. ->where('scydgy_id', 'in', array_keys($sids))
  7830. ->where('company_name', $companyName);
  7831. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7832. $details = $detailsQuery->order('id', 'asc')->select();
  7833. } catch (\Throwable $e) {
  7834. $details = [];
  7835. }
  7836. if (!is_array($details) || $details === []) {
  7837. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7838. try {
  7839. $detailsQuery = Db::table('purchase_order_detail')
  7840. ->where('scydgy_id', 'in', array_keys($sids))
  7841. ->where('company_name', $companyName);
  7842. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7843. $details = $detailsQuery->order('id', 'asc')->select();
  7844. } catch (\Throwable $e) {
  7845. $details = [];
  7846. }
  7847. }
  7848. if (!is_array($details) || $details === []) {
  7849. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7850. }
  7851. $detailLinks = [];
  7852. foreach ($details as $d) {
  7853. if (!is_array($d)) {
  7854. continue;
  7855. }
  7856. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7857. if ($detailId <= 0) {
  7858. continue;
  7859. }
  7860. $sid = (int)($d['scydgy_id'] ?? 0);
  7861. $gymc = '';
  7862. foreach ($mergeRows as $mr) {
  7863. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7864. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7865. break;
  7866. }
  7867. }
  7868. $detailLinks[] = [
  7869. 'detail_id' => $detailId,
  7870. 'cgymc' => $gymc,
  7871. // 询价邮件 → 待报价;下发报价 → 未提交
  7872. 'url' => $this->buildMprocMobileOrderUrl(
  7873. $detailId,
  7874. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  7875. ),
  7876. ];
  7877. }
  7878. if ($detailLinks === []) {
  7879. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7880. }
  7881. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7882. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7883. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7884. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7885. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7886. $notifyBundle['email_log_scene'] = $emailLogScene;
  7887. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7888. $poIdLog = 0;
  7889. $pos = $bundle['pos'] ?? [];
  7890. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7891. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7892. }
  7893. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7894. if ($sendEmail) {
  7895. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7896. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7897. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7898. }
  7899. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7900. $mailConfig = $this->loadMailerConfig();
  7901. if (!$this->isProcuremenNotifyDryRun()) {
  7902. if (empty($mailConfig['host'])) {
  7903. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7904. }
  7905. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7906. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7907. }
  7908. }
  7909. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7910. }
  7911. if ($sendSms) {
  7912. $this->issueSendSupplierSms($notifyBundle);
  7913. }
  7914. }
  7915. /**
  7916. * @param array<int, array<string, mixed>> $quoteGroups
  7917. * @return array<int, array<string, mixed>>
  7918. */
  7919. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7920. {
  7921. $names = [];
  7922. if (is_string($companiesJson) && $companiesJson !== '') {
  7923. $decoded = json_decode($companiesJson, true);
  7924. if (is_array($decoded)) {
  7925. foreach ($decoded as $nm) {
  7926. $nm = trim((string)$nm);
  7927. if ($nm !== '') {
  7928. $names[] = $nm;
  7929. }
  7930. }
  7931. }
  7932. }
  7933. $names = array_values(array_unique($names));
  7934. if ($names === [] && $selectedCompany !== '') {
  7935. $names = [$selectedCompany];
  7936. }
  7937. if ($names === []) {
  7938. return $quoteGroups;
  7939. }
  7940. $targets = [];
  7941. foreach ($quoteGroups as $g) {
  7942. if (!is_array($g)) {
  7943. continue;
  7944. }
  7945. $cn = trim((string)($g['name'] ?? ''));
  7946. if ($cn !== '' && in_array($cn, $names, true)) {
  7947. $targets[] = $g;
  7948. }
  7949. }
  7950. return $targets;
  7951. }
  7952. /**
  7953. * @return array{pos:array, merge_rows:array, bundle:array}
  7954. */
  7955. protected function loadAuditResendBundle(string $scydgyId): array
  7956. {
  7957. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7958. $pos = $bundle['pos'];
  7959. $mergeRows = $bundle['merge_rows'];
  7960. if ($pos === [] || $mergeRows === []) {
  7961. $this->error('该订单不在待确认供应商状态');
  7962. }
  7963. $sysRqDb = '';
  7964. if (isset($pos[0]) && is_array($pos[0])) {
  7965. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7966. }
  7967. foreach ($pos as $i => $poRow) {
  7968. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7969. $pos[$i]['sys_rq'] = $sysRqDb;
  7970. }
  7971. }
  7972. $bundle['pos'] = $pos;
  7973. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7974. }
  7975. /**
  7976. * @param array<int, array<string, mixed>> $targets
  7977. */
  7978. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7979. {
  7980. if ($targets === []) {
  7981. $this->error('未找到可通知的供应商');
  7982. }
  7983. $notifyErrors = [];
  7984. try {
  7985. $this->notifyDryRunPreview = [];
  7986. foreach ($targets as $g) {
  7987. if (!is_array($g)) {
  7988. continue;
  7989. }
  7990. $cname = trim((string)($g['name'] ?? ''));
  7991. if ($cname === '') {
  7992. continue;
  7993. }
  7994. $chosen = [
  7995. 'name' => $cname,
  7996. 'company_name' => $cname,
  7997. 'email' => trim((string)($g['email'] ?? '')),
  7998. 'phone' => trim((string)($g['phone'] ?? '')),
  7999. 'username' => trim((string)($g['username'] ?? '')),
  8000. ];
  8001. try {
  8002. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  8003. } catch (\Throwable $e) {
  8004. $notifyErrors[] = $cname . ':' . $e->getMessage();
  8005. }
  8006. }
  8007. } catch (\Throwable $e) {
  8008. $this->error('通知发送失败:' . $e->getMessage());
  8009. }
  8010. if ($notifyErrors !== []) {
  8011. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  8012. }
  8013. if ($this->isProcuremenNotifyDryRun()) {
  8014. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  8015. 'notify_dry_run' => true,
  8016. 'notify_preview' => $this->notifyDryRunPreview,
  8017. ]);
  8018. }
  8019. $nameLabels = [];
  8020. foreach ($targets as $g) {
  8021. if (!is_array($g)) {
  8022. continue;
  8023. }
  8024. $n = trim((string)($g['name'] ?? ''));
  8025. if ($n !== '') {
  8026. $nameLabels[] = $n;
  8027. }
  8028. }
  8029. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  8030. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  8031. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  8032. $seenLogSid = [];
  8033. foreach ($bundle['pos'] ?? [] as $poRow) {
  8034. if (!is_array($poRow)) {
  8035. continue;
  8036. }
  8037. $sid = (int)($poRow['scydgy_id'] ?? 0);
  8038. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  8039. continue;
  8040. }
  8041. $seenLogSid[$sid] = true;
  8042. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  8043. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  8044. }
  8045. if ($seenLogSid === []) {
  8046. foreach ($mergeRows as $mr) {
  8047. if (!is_array($mr)) {
  8048. continue;
  8049. }
  8050. $sid = $this->extractScydgyRowId($mr);
  8051. if ($this->isValidScydgyRowId($sid)) {
  8052. $this->addOrderLog($sid, $logAction, $logMsg, null);
  8053. break;
  8054. }
  8055. }
  8056. }
  8057. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  8058. }
  8059. /**
  8060. * 协助下发 — 发送短信(一家供应商)
  8061. *
  8062. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  8063. */
  8064. protected function issueSendSupplierSms(array $bundle): void
  8065. {
  8066. $companyName = (string)($bundle['company_name'] ?? '');
  8067. $phone = (string)($bundle['phone'] ?? '');
  8068. $smsContent = (string)($bundle['sms_content'] ?? '');
  8069. $this->logIssueNotifyDebug('短信', [
  8070. 'company' => $companyName,
  8071. 'phone' => $phone,
  8072. 'sms_content' => $smsContent,
  8073. ]);
  8074. if ($this->isProcuremenNotifyDryRun()) {
  8075. $this->recordNotifyDryRunPreview([
  8076. 'scene' => 'issue_sms',
  8077. 'company_name' => $companyName,
  8078. 'phone' => $phone,
  8079. 'sms_content' => $smsContent,
  8080. ]);
  8081. return;
  8082. }
  8083. $this->smsbao($phone, $smsContent);
  8084. }
  8085. /**
  8086. * 协助下发 — 发送邮件(一家供应商)
  8087. *
  8088. * @param array<string, mixed> $bundle
  8089. * @param array<string, mixed> $mailConfig
  8090. */
  8091. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  8092. {
  8093. $companyName = (string)($bundle['company_name'] ?? '');
  8094. $toEmail = (string)($bundle['email'] ?? '');
  8095. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  8096. $mailBody = (string)($bundle['mail_body'] ?? '');
  8097. $this->logIssueNotifyDebug('邮件', [
  8098. 'company' => $companyName,
  8099. 'email' => $toEmail,
  8100. 'mail_subject' => $mailSubject,
  8101. 'mail_body' => $mailPlain,
  8102. ]);
  8103. if ($this->isProcuremenNotifyDryRun()) {
  8104. $this->recordNotifyDryRunPreview([
  8105. 'scene' => 'issue_email',
  8106. 'company_name' => $companyName,
  8107. 'email' => $toEmail,
  8108. 'mail_subject' => $mailSubject,
  8109. 'mail_body' => $mailPlain,
  8110. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  8111. 'notify_vars' => $bundle['notify_vars'] ?? [],
  8112. 'detail_links' => $bundle['detail_links'] ?? [],
  8113. ]);
  8114. return;
  8115. }
  8116. $mail = new PHPMailer(true);
  8117. $mail->isSMTP();
  8118. $mail->Host = $mailConfig['host'];
  8119. $mail->SMTPAuth = true;
  8120. $mail->Username = $mailConfig['addr'];
  8121. $mail->Password = $mailConfig['pass'];
  8122. $mail->SMTPSecure = $mailConfig['security'];
  8123. $mail->Port = $mailConfig['port'];
  8124. $mail->CharSet = $mailConfig['charset'];
  8125. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  8126. $mail->addAddress($toEmail, $companyName);
  8127. $mail->isHTML(true);
  8128. $mail->Subject = $mailSubject;
  8129. $mail->Body = $mailBody;
  8130. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  8131. $sendOk = true;
  8132. $failReason = '';
  8133. try {
  8134. $mail->send();
  8135. } catch (\Throwable $e) {
  8136. $sendOk = false;
  8137. $failReason = $e->getMessage();
  8138. $this->persistEmailSendLog([
  8139. 'from_email' => $fromEmail,
  8140. 'to_email' => $toEmail,
  8141. 'send_time' => date('Y-m-d H:i:s'),
  8142. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8143. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8144. 'company_name' => $companyName,
  8145. 'mail_subject' => $mailSubject,
  8146. 'status' => 0,
  8147. 'fail_reason' => $failReason,
  8148. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8149. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8150. ]);
  8151. throw $e;
  8152. }
  8153. $this->persistEmailSendLog([
  8154. 'from_email' => $fromEmail,
  8155. 'to_email' => $toEmail,
  8156. 'send_time' => date('Y-m-d H:i:s'),
  8157. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8158. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8159. 'company_name' => $companyName,
  8160. 'mail_subject' => $mailSubject,
  8161. 'status' => 1,
  8162. 'fail_reason' => '',
  8163. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8164. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8165. ]);
  8166. }
  8167. /**
  8168. * 下发通知:解析订单类型名称与评分比例文案
  8169. *
  8170. * @param array<string, mixed> $bundle
  8171. * @return array{order_type:string,score_weights:string}
  8172. */
  8173. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  8174. {
  8175. $orderType = '';
  8176. $scoreWeights = '';
  8177. $rule = null;
  8178. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  8179. $rule = $bundle['score_rule'];
  8180. }
  8181. $pos = $bundle['pos'] ?? [];
  8182. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  8183. if ($rule === null && is_array($po0)) {
  8184. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  8185. if ($ruleId > 0) {
  8186. try {
  8187. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  8188. } catch (\Throwable $e) {
  8189. $rule = null;
  8190. }
  8191. }
  8192. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  8193. $qw = (int)($po0['score_quality_weight'] ?? 0);
  8194. $pw = (int)($po0['score_price_weight'] ?? 0);
  8195. $lw = (int)($po0['score_lead_weight'] ?? 0);
  8196. if ($qw > 0 || $pw > 0 || $lw > 0) {
  8197. $rule = [
  8198. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  8199. 'quality_weight' => $qw,
  8200. 'price_weight' => $pw,
  8201. 'lead_weight' => $lw,
  8202. ];
  8203. }
  8204. }
  8205. }
  8206. if (is_array($rule)) {
  8207. $orderType = trim((string)($rule['name'] ?? ''));
  8208. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8209. }
  8210. if ($orderType === '' && is_array($po0)) {
  8211. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8212. }
  8213. return [
  8214. 'order_type' => $orderType,
  8215. 'score_weights' => $scoreWeights,
  8216. ];
  8217. }
  8218. /**
  8219. * 评分比例文案:质量30%、价格50%、交货20%
  8220. *
  8221. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8222. */
  8223. protected function formatScoreRuleWeightsText(array $rule): string
  8224. {
  8225. $parts = [];
  8226. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8227. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8228. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8229. $fmt = static function ($n) {
  8230. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8231. return $s === '' ? '0' : $s;
  8232. };
  8233. if ($qw > 0) {
  8234. $parts[] = '质量' . $fmt($qw) . '%';
  8235. }
  8236. if ($pw > 0) {
  8237. $parts[] = '价格' . $fmt($pw) . '%';
  8238. }
  8239. if ($lw > 0) {
  8240. $parts[] = '交货' . $fmt($lw) . '%';
  8241. }
  8242. return implode('、', $parts);
  8243. }
  8244. /**
  8245. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8246. *
  8247. * @param array<int, array<string, mixed>> $mergeRows
  8248. * @return array<string, mixed>
  8249. */
  8250. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8251. {
  8252. $head = $mergeRows[0] ?? [];
  8253. $isMerge = count($mergeRows) > 1;
  8254. return [
  8255. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8256. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8257. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8258. 'is_merge' => $isMerge,
  8259. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8260. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8261. 'deadline' => $sysRqNotify,
  8262. 'order_type' => '',
  8263. 'score_weights' => '',
  8264. ];
  8265. }
  8266. /**
  8267. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8268. *
  8269. * @param array<string, mixed> $data
  8270. */
  8271. protected function logIssueNotifyDebug(string $type, array $data): void
  8272. {
  8273. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8274. return;
  8275. }
  8276. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8277. }
  8278. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8279. {
  8280. try {
  8281. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8282. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8283. return;
  8284. } catch (\Throwable $e) {
  8285. }
  8286. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8287. if (is_file($sqlFile)) {
  8288. $sql = file_get_contents($sqlFile);
  8289. if (is_string($sql) && $sql !== '') {
  8290. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8291. $stmt = trim($stmt);
  8292. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8293. continue;
  8294. }
  8295. try {
  8296. Db::execute($stmt);
  8297. } catch (\Throwable $ignore) {
  8298. }
  8299. }
  8300. }
  8301. }
  8302. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8303. }
  8304. /**
  8305. * @param array<string, mixed> $row
  8306. */
  8307. protected function persistEmailSendLog(array $row): void
  8308. {
  8309. try {
  8310. $this->ensurePurchaseEmailSendLogTableOnce();
  8311. } catch (\Throwable $e) {
  8312. return;
  8313. }
  8314. list($adminId, $adminName) = $this->GetUseName();
  8315. $cut = function ($s, $max) {
  8316. $s = (string)$s;
  8317. if (function_exists('mb_substr')) {
  8318. return mb_substr($s, 0, $max, 'UTF-8');
  8319. }
  8320. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8321. };
  8322. $data = [
  8323. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8324. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8325. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8326. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8327. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8328. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8329. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8330. 'status' => !empty($row['status']) ? 1 : 0,
  8331. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8332. 'admin_id' => (int)$adminId,
  8333. 'admin_name' => $cut($adminName, 64),
  8334. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8335. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8336. 'createtime' => date('Y-m-d H:i:s'),
  8337. ];
  8338. try {
  8339. Db::table('purchase_email_send_log')->insert($data);
  8340. } catch (\Throwable $e) {
  8341. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8342. }
  8343. }
  8344. protected function formatEmailLogSceneText(string $scene): string
  8345. {
  8346. $map = [
  8347. 'pick_issue' => '初选下发',
  8348. 'audit_resend' => '确认页重发',
  8349. 'rfq_salesman' => '询价通知业务员',
  8350. 'rfq_supplier' => '供应商询价通知',
  8351. ];
  8352. return $map[$scene] ?? $scene;
  8353. }
  8354. /**
  8355. * 邮件发送日志列表
  8356. */
  8357. public function emailLog()
  8358. {
  8359. $this->relationSearch = false;
  8360. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8361. $this->request->filter(['strip_tags', 'trim']);
  8362. $bakModel = $this->model;
  8363. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8364. if ($this->request->isAjax()) {
  8365. $this->ensurePurchaseEmailSendLogTableOnce();
  8366. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8367. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8368. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8369. $list = $this->model
  8370. ->where($where)
  8371. ->order($sortField, $orderDir)
  8372. ->paginate($limit);
  8373. $rows = [];
  8374. foreach ($list->items() as $item) {
  8375. $row = is_array($item) ? $item : $item->toArray();
  8376. $scene = trim((string)($row['scene'] ?? ''));
  8377. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8378. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8379. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8380. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8381. $rows[] = $row;
  8382. }
  8383. $this->model = $bakModel;
  8384. return json(['total' => $list->total(), 'rows' => $rows]);
  8385. }
  8386. $this->model = $bakModel;
  8387. return $this->view->fetch('procuremen/emaillog');
  8388. }
  8389. /**
  8390. * 协助下发弹窗(选多家供应商并通知)
  8391. */
  8392. public function pickReview()
  8393. {
  8394. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8395. $this->error(__('You have no permission'));
  8396. }
  8397. if ($this->request->isPost()) {
  8398. $this->error('请使用弹窗内「确认下发」提交');
  8399. }
  8400. $this->view->assign('pickMode', 1);
  8401. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8402. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8403. }
  8404. /**
  8405. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8406. */
  8407. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8408. {
  8409. static $done = false;
  8410. if ($done) {
  8411. return;
  8412. }
  8413. $done = true;
  8414. try {
  8415. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8416. if (empty($cols)) {
  8417. Db::execute(
  8418. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8419. );
  8420. } else {
  8421. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8422. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8423. Db::execute(
  8424. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8425. );
  8426. }
  8427. }
  8428. } catch (\Throwable $e) {
  8429. // ignore
  8430. }
  8431. }
  8432. /**
  8433. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8434. */
  8435. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8436. {
  8437. static $done = false;
  8438. if ($done) {
  8439. return;
  8440. }
  8441. $done = true;
  8442. try {
  8443. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8444. if (empty($cols)) {
  8445. Db::execute(
  8446. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8447. );
  8448. }
  8449. } catch (\Throwable $e) {
  8450. // ignore
  8451. }
  8452. try {
  8453. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8454. if (empty($cols2)) {
  8455. Db::execute(
  8456. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8457. );
  8458. }
  8459. } catch (\Throwable $e) {
  8460. // ignore
  8461. }
  8462. }
  8463. /**
  8464. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8465. */
  8466. protected function ensureConfirmResultEmailTemplates(): void
  8467. {
  8468. static $done = false;
  8469. if ($done) {
  8470. return;
  8471. }
  8472. $done = true;
  8473. $now = date('Y-m-d H:i:s');
  8474. $seeds = [
  8475. 'confirm_ok_email' => [
  8476. 'title' => '采购确认结果:已通过',
  8477. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8478. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8479. ],
  8480. 'confirm_fail_email' => [
  8481. 'title' => '采购确认结果:未通过',
  8482. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8483. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8484. ],
  8485. ];
  8486. try {
  8487. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8488. } catch (\Throwable $e) {
  8489. return;
  8490. }
  8491. $colNames = [];
  8492. foreach ($cols as $c) {
  8493. if (!is_array($c)) {
  8494. continue;
  8495. }
  8496. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8497. if ($n !== '') {
  8498. $colNames[$n] = true;
  8499. }
  8500. }
  8501. foreach ($seeds as $scene => $seed) {
  8502. try {
  8503. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8504. } catch (\Throwable $e) {
  8505. continue;
  8506. }
  8507. if (is_array($row) && $row !== []) {
  8508. continue;
  8509. }
  8510. $data = [
  8511. 'scene' => $scene,
  8512. 'title' => $seed['title'],
  8513. 'content' => $seed['content'],
  8514. 'remark' => $seed['remark'],
  8515. 'status' => 1,
  8516. ];
  8517. if (isset($colNames['updatetime'])) {
  8518. $data['updatetime'] = $now;
  8519. }
  8520. if (isset($colNames['createtime'])) {
  8521. $data['createtime'] = $now;
  8522. }
  8523. try {
  8524. Db::table('purchase_sms_template')->insert($data);
  8525. } catch (\Throwable $e) {
  8526. // ignore
  8527. }
  8528. }
  8529. }
  8530. /**
  8531. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8532. */
  8533. protected function ensureRfqSupplierEmailTemplate(): void
  8534. {
  8535. static $done = false;
  8536. if ($done) {
  8537. return;
  8538. }
  8539. $done = true;
  8540. $content = "您好,{company_name}:\n\n"
  8541. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8542. . "需求编号:{ccydh}\n"
  8543. . "印件名称:{cyjmc}\n"
  8544. . "{process_lines}\n\n"
  8545. . "请在 {deadline} 前完成回复。\n\n"
  8546. . "平台链接:{platform_url}\n";
  8547. try {
  8548. $row = Db::table('purchase_sms_template')
  8549. ->where('scene', 'rfq_supplier_email')
  8550. ->find();
  8551. } catch (\Throwable $e) {
  8552. return;
  8553. }
  8554. $now = date('Y-m-d H:i:s');
  8555. if (is_array($row) && $row !== []) {
  8556. return;
  8557. }
  8558. try {
  8559. $data = [
  8560. 'scene' => 'rfq_supplier_email',
  8561. 'title' => '供应商询价通知',
  8562. 'content' => $content,
  8563. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8564. 'status' => 1,
  8565. ];
  8566. try {
  8567. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8568. } catch (\Throwable $e) {
  8569. $cols = [];
  8570. }
  8571. $colNames = [];
  8572. foreach ($cols as $c) {
  8573. if (!is_array($c)) {
  8574. continue;
  8575. }
  8576. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8577. if ($n !== '') {
  8578. $colNames[$n] = true;
  8579. }
  8580. }
  8581. if (isset($colNames['updatetime'])) {
  8582. $data['updatetime'] = $now;
  8583. }
  8584. if (isset($colNames['createtime'])) {
  8585. $data['createtime'] = $now;
  8586. }
  8587. Db::table('purchase_sms_template')->insert($data);
  8588. } catch (\Throwable $e) {
  8589. // ignore
  8590. }
  8591. }
  8592. /**
  8593. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8594. */
  8595. protected function ensureRfqSalesmanEmailTemplate(): void
  8596. {
  8597. static $done = false;
  8598. if ($done) {
  8599. return;
  8600. }
  8601. $done = true;
  8602. $content = "您好,{contact_name}:\n\n"
  8603. . "有新的协助采购询价需求,请知悉。\n"
  8604. . "印件名称:{cyjmc}\n"
  8605. . "工序名称:{cgymc}\n"
  8606. . "本次数量:{this_quantity}\n"
  8607. . "供应商报价:\n{supplier_quotes}\n"
  8608. . "平台链接:{platform_url}\n"
  8609. . "需求发起人:{cywyxm}\n";
  8610. try {
  8611. $row = Db::table('purchase_sms_template')
  8612. ->where('scene', 'rfq_salesman_email')
  8613. ->find();
  8614. } catch (\Throwable $e) {
  8615. return;
  8616. }
  8617. $now = date('Y-m-d H:i:s');
  8618. if (is_array($row) && $row !== []) {
  8619. $old = (string)($row['content'] ?? '');
  8620. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  8621. $urlPos = strpos($old, '{platform_url}');
  8622. $cywyPos = strpos($old, '需求发起人');
  8623. $linkNotAboveStarter = ($urlPos === false)
  8624. || ($cywyPos !== false && $urlPos > $cywyPos);
  8625. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8626. || (strpos($old, '供应商:{supplier_name}') !== false)
  8627. || $linkNotAboveStarter;
  8628. if ($needMigrate) {
  8629. $data = ['content' => $content];
  8630. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8631. $data['title'] = '业务员询价通知';
  8632. }
  8633. try {
  8634. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8635. if (!empty($cols)) {
  8636. $data['updatetime'] = $now;
  8637. }
  8638. } catch (\Throwable $e) {
  8639. }
  8640. try {
  8641. Db::table('purchase_sms_template')
  8642. ->where('id', (int)($row['id'] ?? 0))
  8643. ->update($data);
  8644. } catch (\Throwable $e) {
  8645. }
  8646. }
  8647. return;
  8648. }
  8649. try {
  8650. $data = [
  8651. 'scene' => 'rfq_salesman_email',
  8652. 'title' => '业务员询价通知',
  8653. 'content' => $content,
  8654. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8655. 'status' => 1,
  8656. ];
  8657. try {
  8658. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8659. } catch (\Throwable $e) {
  8660. $cols = [];
  8661. }
  8662. $colNames = [];
  8663. foreach ($cols as $c) {
  8664. if (!is_array($c)) {
  8665. continue;
  8666. }
  8667. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8668. if ($n !== '') {
  8669. $colNames[$n] = true;
  8670. }
  8671. }
  8672. if (isset($colNames['updatetime'])) {
  8673. $data['updatetime'] = $now;
  8674. }
  8675. if (isset($colNames['createtime'])) {
  8676. $data['createtime'] = $now;
  8677. }
  8678. Db::table('purchase_sms_template')->insert($data);
  8679. } catch (\Throwable $e) {
  8680. // ignore
  8681. }
  8682. }
  8683. /**
  8684. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8685. *
  8686. * @return array<int, array{name:string,amount:string}>
  8687. */
  8688. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8689. {
  8690. $list = [];
  8691. $seen = [];
  8692. try {
  8693. $rows = Db::table('purchase_order_detail')
  8694. ->where('scydgy_id', $sid)
  8695. ->field('company_name,amount')
  8696. ->order('id', 'asc')
  8697. ->select();
  8698. if (is_array($rows)) {
  8699. foreach ($rows as $r) {
  8700. if (!is_array($r)) {
  8701. continue;
  8702. }
  8703. $cn = trim((string)($r['company_name'] ?? ''));
  8704. if ($cn === '' || isset($seen[$cn])) {
  8705. continue;
  8706. }
  8707. $seen[$cn] = true;
  8708. $amount = trim((string)($r['amount'] ?? ''));
  8709. $list[] = [
  8710. 'name' => $cn,
  8711. 'amount' => $amount !== '' ? $amount : '未报价',
  8712. ];
  8713. }
  8714. }
  8715. } catch (\Throwable $e) {
  8716. }
  8717. if ($list === [] && $supplierRaw !== '') {
  8718. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8719. if ($cn === '' || isset($seen[$cn])) {
  8720. continue;
  8721. }
  8722. $seen[$cn] = true;
  8723. $list[] = [
  8724. 'name' => $cn,
  8725. 'amount' => '未报价',
  8726. ];
  8727. }
  8728. }
  8729. return $list;
  8730. }
  8731. /**
  8732. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8733. */
  8734. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8735. {
  8736. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8737. if ($rows === []) {
  8738. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8739. }
  8740. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8741. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8742. . '<thead><tr style="background:#f5f5f5;">'
  8743. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8744. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8745. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8746. . '</tr></thead><tbody>';
  8747. foreach ($rows as $i => $row) {
  8748. $html .= '<tr>'
  8749. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8750. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8751. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8752. . '</tr>';
  8753. }
  8754. $html .= '</tbody></table>';
  8755. return $html;
  8756. }
  8757. /**
  8758. * 询价多选字段:数组或字符串统一为顿号拼接
  8759. *
  8760. * @param mixed $raw
  8761. */
  8762. protected function joinRfqMultiSelectValues($raw): string
  8763. {
  8764. $parts = [];
  8765. if (is_array($raw)) {
  8766. foreach ($raw as $item) {
  8767. if (is_array($item)) {
  8768. continue;
  8769. }
  8770. $v = trim((string)$item);
  8771. if ($v !== '') {
  8772. $parts[] = $v;
  8773. }
  8774. }
  8775. } else {
  8776. $s = trim((string)$raw);
  8777. if ($s !== '') {
  8778. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8779. $v = trim((string)$piece);
  8780. if ($v !== '') {
  8781. $parts[] = $v;
  8782. }
  8783. }
  8784. }
  8785. }
  8786. $parts = array_values(array_unique($parts));
  8787. return implode('、', $parts);
  8788. }
  8789. /**
  8790. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8791. *
  8792. * @return string[]
  8793. */
  8794. protected function loadRfqSupplierNameOptions(): array
  8795. {
  8796. $out = [];
  8797. try {
  8798. $rows = Db::table('customer')
  8799. ->where(function ($q) {
  8800. $q->where('status', 1)
  8801. ->whereOr('status', '1')
  8802. ->whereOr('status', '')
  8803. ->whereNull('status');
  8804. })
  8805. ->order('id', 'desc')
  8806. ->column('company_name');
  8807. } catch (\Throwable $e) {
  8808. return [];
  8809. }
  8810. if (!is_array($rows)) {
  8811. return [];
  8812. }
  8813. foreach ($rows as $name) {
  8814. $name = trim((string)$name);
  8815. if ($name === '' || isset($out[$name])) {
  8816. continue;
  8817. }
  8818. $out[$name] = $name;
  8819. }
  8820. return array_values($out);
  8821. }
  8822. /**
  8823. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8824. */
  8825. protected function rfqNotifySalesmanAuthGroupId(): int
  8826. {
  8827. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8828. if ($id > 0) {
  8829. return $id;
  8830. }
  8831. try {
  8832. $found = Db::name('auth_group')
  8833. ->where('name', '业务员')
  8834. ->where('status', 'normal')
  8835. ->order('id', 'asc')
  8836. ->value('id');
  8837. $id = (int)$found;
  8838. } catch (\Throwable $e) {
  8839. $id = 0;
  8840. }
  8841. return $id > 0 ? $id : 12;
  8842. }
  8843. /**
  8844. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8845. *
  8846. * @return string[]
  8847. */
  8848. protected function loadRfqSalesmanNameOptions(): array
  8849. {
  8850. $out = [];
  8851. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8852. $name = trim((string)($row['name'] ?? ''));
  8853. if ($name !== '') {
  8854. $out[] = $name;
  8855. }
  8856. }
  8857. return $out;
  8858. }
  8859. /**
  8860. * 业务员角色组下管理员:姓名、邮箱、手机
  8861. *
  8862. * @return array<int, array{name:string,email:string,mobile:string}>
  8863. */
  8864. protected function loadRfqSalesmanContactOptions(): array
  8865. {
  8866. $out = [];
  8867. $seen = [];
  8868. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8869. if ($groupId <= 0) {
  8870. return [];
  8871. }
  8872. try {
  8873. $adminIds = Db::name('auth_group_access')
  8874. ->where('group_id', $groupId)
  8875. ->column('uid');
  8876. } catch (\Throwable $e) {
  8877. return [];
  8878. }
  8879. $adminIds = is_array($adminIds)
  8880. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8881. : [];
  8882. if ($adminIds === []) {
  8883. return [];
  8884. }
  8885. try {
  8886. $rows = Db::name('admin')
  8887. ->where('status', 'normal')
  8888. ->where('id', 'in', $adminIds)
  8889. ->order('id', 'asc')
  8890. ->field('id,nickname,username,email,mobile')
  8891. ->select();
  8892. } catch (\Throwable $e) {
  8893. return [];
  8894. }
  8895. if (!is_array($rows)) {
  8896. return [];
  8897. }
  8898. foreach ($rows as $row) {
  8899. if (!is_array($row)) {
  8900. continue;
  8901. }
  8902. $name = trim((string)($row['nickname'] ?? ''));
  8903. if ($name === '') {
  8904. $name = trim((string)($row['username'] ?? ''));
  8905. }
  8906. if ($name === '' || isset($seen[$name])) {
  8907. continue;
  8908. }
  8909. $seen[$name] = true;
  8910. $out[] = [
  8911. 'name' => $name,
  8912. 'email' => trim((string)($row['email'] ?? '')),
  8913. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8914. ];
  8915. }
  8916. return $out;
  8917. }
  8918. /**
  8919. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8920. *
  8921. * @return string[]
  8922. */
  8923. protected function loadRfqDeptNameOptions(): array
  8924. {
  8925. $out = [];
  8926. // ERP 承揽部门(主来源)
  8927. try {
  8928. $vals = Db::table('mcyd')
  8929. ->where('CCLBMMC', '<>', '')
  8930. ->whereNotNull('CCLBMMC')
  8931. ->distinct(true)
  8932. ->limit(300)
  8933. ->column('CCLBMMC');
  8934. } catch (\Throwable $e) {
  8935. $vals = [];
  8936. }
  8937. if (is_array($vals)) {
  8938. foreach ($vals as $v) {
  8939. $v = trim((string)$v);
  8940. if ($v === '' || isset($out[$v])) {
  8941. continue;
  8942. }
  8943. $out[$v] = $v;
  8944. }
  8945. }
  8946. // 手工询价历史部门补全
  8947. try {
  8948. $poVals = Db::table('purchase_order')
  8949. ->where('CCLBMMC', '<>', '')
  8950. ->whereNotNull('CCLBMMC')
  8951. ->distinct(true)
  8952. ->limit(200)
  8953. ->column('CCLBMMC');
  8954. } catch (\Throwable $e) {
  8955. $poVals = [];
  8956. }
  8957. if (is_array($poVals)) {
  8958. foreach ($poVals as $v) {
  8959. $v = trim((string)$v);
  8960. if ($v === '' || isset($out[$v])) {
  8961. continue;
  8962. }
  8963. $out[$v] = $v;
  8964. }
  8965. }
  8966. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8967. if (!isset($out[$preset])) {
  8968. $out[$preset] = $preset;
  8969. }
  8970. }
  8971. $list = array_values($out);
  8972. // 常用部门靠前
  8973. usort($list, static function ($a, $b) {
  8974. $weight = [
  8975. '营销中心' => 1,
  8976. '业务部' => 2,
  8977. '市场部' => 3,
  8978. '外贸部' => 4,
  8979. '新华技术业务部' => 5,
  8980. ];
  8981. $wa = $weight[$a] ?? 100;
  8982. $wb = $weight[$b] ?? 100;
  8983. if ($wa !== $wb) {
  8984. return $wa <=> $wb;
  8985. }
  8986. return strcmp((string)$a, (string)$b);
  8987. });
  8988. return $list;
  8989. }
  8990. /**
  8991. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8992. */
  8993. public function add()
  8994. {
  8995. if ($this->request->isPost()) {
  8996. $params = $this->request->post('row/a');
  8997. if (!is_array($params)) {
  8998. $this->error(__('Parameter %s can not be empty', ''));
  8999. }
  9000. [, $adminName] = $this->GetUseName();
  9001. $params['cywyxm'] = $adminName;
  9002. try {
  9003. $sid = $this->saveManualPickOrder($params);
  9004. } catch (\InvalidArgumentException $e) {
  9005. $this->error($e->getMessage());
  9006. } catch (\Throwable $e) {
  9007. $this->error($e->getMessage());
  9008. }
  9009. $this->success('新增成功', '', [
  9010. 'scydgy_id' => $sid,
  9011. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  9012. ]);
  9013. }
  9014. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9015. [, $adminName] = $this->GetUseName();
  9016. $this->view->assign('adminNickname', $adminName);
  9017. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  9018. $this->view->assign('defaultCclbmmc', '营销中心');
  9019. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  9020. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  9021. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  9022. return $this->view->fetch();
  9023. }
  9024. /**
  9025. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  9026. */
  9027. public function rfqlist()
  9028. {
  9029. $this->relationSearch = false;
  9030. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  9031. $this->request->filter(['strip_tags', 'trim']);
  9032. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9033. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9034. $this->ensureRfqSalesmanEmailTemplate();
  9035. $this->ensureRfqSupplierEmailTemplate();
  9036. if ($this->request->isAjax()) {
  9037. try {
  9038. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9039. $limit = max(10, min(500, (int)$limit));
  9040. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  9041. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  9042. $filterYm = date('Y-m');
  9043. }
  9044. $applyFilters = function ($query) use ($where, $filterYm) {
  9045. $query->where('scydgy_id', '<', 0);
  9046. $this->applyPurchaseOrderNotDeletedWhere($query);
  9047. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  9048. $this->applyRfqListMonthFilter($query, $filterYm);
  9049. if (!empty($where)) {
  9050. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  9051. $safeWhere = [];
  9052. $skipFields = [
  9053. 'supplier_name' => true,
  9054. 'progress_text' => true,
  9055. 'createtime_text' => true,
  9056. 'notify_time_text' => true,
  9057. 'can_notify_salesman' => true,
  9058. 'has_issued' => true,
  9059. 'has_quoted' => true,
  9060. ];
  9061. foreach ((array)$where as $cond) {
  9062. if (!is_array($cond) || !isset($cond[0])) {
  9063. continue;
  9064. }
  9065. $field = (string)$cond[0];
  9066. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  9067. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  9068. if (isset($skipFields[$fieldBase])) {
  9069. continue;
  9070. }
  9071. if ($fieldBase === 'supplier_name') {
  9072. continue;
  9073. }
  9074. $safeWhere[] = $cond;
  9075. }
  9076. if ($safeWhere !== []) {
  9077. $query->where($safeWhere);
  9078. }
  9079. }
  9080. };
  9081. $countQuery = Db::table('purchase_order');
  9082. $applyFilters($countQuery);
  9083. $total = (int)$countQuery->count();
  9084. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9085. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9086. $listQuery = Db::table('purchase_order');
  9087. $applyFilters($listQuery);
  9088. $rows = $listQuery
  9089. ->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')
  9090. ->order($sortField, $orderDir)
  9091. ->limit($offset, $limit)
  9092. ->select();
  9093. if (!is_array($rows)) {
  9094. $rows = [];
  9095. }
  9096. $sidList = [];
  9097. foreach ($rows as $r) {
  9098. if (!is_array($r)) {
  9099. continue;
  9100. }
  9101. $sid = (int)($r['scydgy_id'] ?? 0);
  9102. if ($sid < 0) {
  9103. $sidList[$sid] = true;
  9104. }
  9105. }
  9106. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  9107. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  9108. $out = [];
  9109. foreach ($rows as $r) {
  9110. if (!is_array($r)) {
  9111. continue;
  9112. }
  9113. $sid = (int)($r['scydgy_id'] ?? 0);
  9114. if ($sid >= 0) {
  9115. continue;
  9116. }
  9117. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9118. if ($createdText === '') {
  9119. $createdText = trim((string)($r['dStamp'] ?? ''));
  9120. }
  9121. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  9122. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  9123. if ($supplier === '') {
  9124. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  9125. }
  9126. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  9127. || isset($issuedSidSet[$sid]);
  9128. $hasQuoted = isset($quotedSidSet[$sid]);
  9129. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  9130. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  9131. $out[] = [
  9132. 'id' => (int)($r['id'] ?? 0),
  9133. 'scydgy_id' => $sid,
  9134. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  9135. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  9136. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  9137. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  9138. 'CDW' => trim((string)($r['CDW'] ?? '')),
  9139. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  9140. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  9141. 'CDF' => trim((string)($r['CDF'] ?? '')),
  9142. 'supplier_name' => $supplier,
  9143. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  9144. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  9145. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  9146. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  9147. 'notify_time_text' => $notifyTimeText,
  9148. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  9149. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  9150. 'has_issued' => $hasIssued ? 1 : 0,
  9151. 'has_quoted' => $hasQuoted ? 1 : 0,
  9152. 'can_notify_salesman' => $canNotifySalesman,
  9153. 'createtime' => $r['createtime'] ?? null,
  9154. 'createtime_text' => $createdText,
  9155. ];
  9156. }
  9157. return json(['total' => $total, 'rows' => $out]);
  9158. } catch (\Throwable $e) {
  9159. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  9160. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  9161. }
  9162. }
  9163. $sidebar = $this->loadRfqSidebarYearMonths();
  9164. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  9165. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  9166. [, $adminName] = $this->GetUseName();
  9167. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  9168. $this->view->assign('adminNickname', $adminName);
  9169. $this->view->assign('defaultYm', $defaultYm);
  9170. $this->view->assign('sidebarYearMonths', $sidebar);
  9171. return $this->view->fetch('procuremen/rfqlist');
  9172. }
  9173. /**
  9174. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  9175. *
  9176. * @param array<int, array{year:string, months:array}> $sidebar
  9177. */
  9178. protected function resolveRfqListDefaultYm(array $sidebar): string
  9179. {
  9180. $current = date('Y-m');
  9181. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  9182. if (in_array($current, $yms, true)) {
  9183. return $current;
  9184. }
  9185. if ($yms !== []) {
  9186. rsort($yms, SORT_STRING);
  9187. return (string)$yms[0];
  9188. }
  9189. return $current;
  9190. }
  9191. /**
  9192. * 手工询价列表左侧月份(按 createtime / dStamp)
  9193. *
  9194. * @return array<int, array{year:string, months:array}>
  9195. */
  9196. protected function loadRfqSidebarYearMonths(): array
  9197. {
  9198. $ymSet = [];
  9199. try {
  9200. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  9201. $this->applyPurchaseOrderNotDeletedWhere($q);
  9202. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  9203. } catch (\Throwable $e) {
  9204. $rows = [];
  9205. }
  9206. if (!is_array($rows)) {
  9207. $rows = [];
  9208. }
  9209. foreach ($rows as $r) {
  9210. if (!is_array($r)) {
  9211. continue;
  9212. }
  9213. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9214. if ($t === '') {
  9215. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9216. }
  9217. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9218. $ymSet[$m[1] . '-' . $m[2]] = true;
  9219. }
  9220. }
  9221. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9222. }
  9223. /**
  9224. * 手工询价可见范围(用于详情/操作校验):
  9225. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9226. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9227. */
  9228. protected function applyManualRfqViewerWhere($query): void
  9229. {
  9230. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9231. return;
  9232. }
  9233. [, $adminName] = $this->GetUseName();
  9234. $adminName = trim((string)$adminName);
  9235. if ($adminName === '') {
  9236. $query->whereRaw('1 = 0');
  9237. return;
  9238. }
  9239. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9240. $query->where(function ($q) use ($adminName) {
  9241. $q->where('cywyxm', $adminName)
  9242. ->whereOr('notify_salesman', $adminName)
  9243. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9244. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9245. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9246. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9247. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9248. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9249. });
  9250. }
  9251. /**
  9252. * 当前用户是否可查看/操作该手工询价单
  9253. */
  9254. protected function canViewManualRfqOrder(array $po): bool
  9255. {
  9256. if ($this->auth->isSuperAdmin()) {
  9257. return true;
  9258. }
  9259. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9260. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9261. return true;
  9262. }
  9263. [, $adminName] = $this->GetUseName();
  9264. $adminName = trim((string)$adminName);
  9265. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9266. return true;
  9267. }
  9268. if ($adminName !== '') {
  9269. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9270. if ($n === $adminName) {
  9271. return true;
  9272. }
  9273. }
  9274. }
  9275. return false;
  9276. }
  9277. /**
  9278. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9279. */
  9280. protected function applyRfqListMonthFilter($query, string $ym): void
  9281. {
  9282. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9283. $ym = date('Y-m');
  9284. }
  9285. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9286. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9287. $query->whereRaw(
  9288. "("
  9289. . "CASE "
  9290. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9291. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9292. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9293. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9294. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9295. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9296. . "END"
  9297. . ") LIKE '{$ymEsc}-%'"
  9298. );
  9299. }
  9300. /**
  9301. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9302. */
  9303. public function rfqlistDetails()
  9304. {
  9305. return $this->details();
  9306. }
  9307. /**
  9308. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9309. */
  9310. public function rfqnotifysalesmen()
  9311. {
  9312. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9313. $this->error(__('You have no permission'));
  9314. }
  9315. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9316. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9317. $sid = (int)$this->request->param('scydgy_id', 0);
  9318. if ($sid >= 0) {
  9319. $this->error('仅支持手工新增询价单');
  9320. }
  9321. $po = $this->loadManualRfqOrderForNotify($sid);
  9322. $selectedMap = [];
  9323. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9324. $selectedMap[$n] = true;
  9325. }
  9326. $list = [];
  9327. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9328. $name = trim((string)($row['name'] ?? ''));
  9329. if ($name === '') {
  9330. continue;
  9331. }
  9332. $email = trim((string)($row['email'] ?? ''));
  9333. $mobile = trim((string)($row['mobile'] ?? ''));
  9334. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9335. $list[] = [
  9336. 'name' => $name,
  9337. 'email' => $email,
  9338. 'mobile' => $mobile,
  9339. 'can_select' => $hasEmail ? 1 : 0,
  9340. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9341. ];
  9342. }
  9343. $canNotify = $this->canRfqNotifySalesman($po);
  9344. $this->success('', null, [
  9345. 'scydgy_id' => $sid,
  9346. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9347. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9348. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9349. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9350. 'list' => $list,
  9351. ]);
  9352. }
  9353. /**
  9354. * 查询询价 — 补加通知业务员可选名单
  9355. */
  9356. public function rfqsalesmanoptions()
  9357. {
  9358. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9359. $this->error(__('You have no permission'));
  9360. }
  9361. $out = [];
  9362. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9363. $email = trim((string)($row['email'] ?? ''));
  9364. $mobile = trim((string)($row['mobile'] ?? ''));
  9365. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9366. $out[] = [
  9367. 'name' => (string)($row['name'] ?? ''),
  9368. 'email' => $email,
  9369. 'mobile' => $mobile,
  9370. 'can_select' => $hasEmail ? 1 : 0,
  9371. ];
  9372. }
  9373. $this->success('', null, ['list' => $out]);
  9374. }
  9375. /**
  9376. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9377. */
  9378. public function rfqappendsalesmen()
  9379. {
  9380. if (!$this->request->isPost()) {
  9381. $this->error(__('Invalid parameters'));
  9382. }
  9383. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9384. $this->error(__('You have no permission'));
  9385. }
  9386. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9387. $sid = (int)$this->request->post('scydgy_id', 0);
  9388. if ($sid >= 0) {
  9389. $this->error('仅支持手工新增询价单');
  9390. }
  9391. $po = $this->loadManualRfqOrderForNotify($sid);
  9392. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9393. $this->error('订单已完结,无法添加业务员');
  9394. }
  9395. $raw = $this->request->post('salesmen/a', []);
  9396. if (!is_array($raw) || $raw === []) {
  9397. $salesmenJson = $this->request->post('salesmen_json', '');
  9398. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9399. $decoded = json_decode($salesmenJson, true);
  9400. $raw = is_array($decoded) ? $decoded : [];
  9401. }
  9402. }
  9403. $addNames = [];
  9404. foreach ((array)$raw as $item) {
  9405. if (is_array($item)) {
  9406. $n = trim((string)($item['name'] ?? ''));
  9407. } else {
  9408. $n = trim((string)$item);
  9409. }
  9410. if ($n !== '') {
  9411. $addNames[] = $n;
  9412. }
  9413. }
  9414. $addNames = array_values(array_unique($addNames));
  9415. if ($addNames === []) {
  9416. $this->error('请选择要添加的业务员');
  9417. }
  9418. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9419. $allowedMap = [];
  9420. foreach ($allowedOptions as $opt) {
  9421. $n = trim((string)($opt['name'] ?? ''));
  9422. if ($n === '') {
  9423. continue;
  9424. }
  9425. $email = trim((string)($opt['email'] ?? ''));
  9426. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9427. }
  9428. foreach ($addNames as $n) {
  9429. if (!array_key_exists($n, $allowedMap)) {
  9430. $this->error('业务员不在可选名单中:' . $n);
  9431. }
  9432. if (!$allowedMap[$n]) {
  9433. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9434. }
  9435. }
  9436. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9437. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9438. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9439. try {
  9440. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9441. } catch (\Throwable $e) {
  9442. $this->error('保存失败:' . $e->getMessage());
  9443. }
  9444. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9445. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9446. $this->success('已添加业务员', null, [
  9447. 'scydgy_id' => $sid,
  9448. 'notify_salesman' => $mergedStr,
  9449. 'added_count' => count($addNames),
  9450. ]);
  9451. }
  9452. /**
  9453. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9454. */
  9455. public function rfqnotifysalesman()
  9456. {
  9457. if (!$this->request->isPost()) {
  9458. $this->error(__('Invalid parameters'));
  9459. }
  9460. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9461. $this->error(__('You have no permission'));
  9462. }
  9463. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9464. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9465. $sid = (int)$this->request->post('scydgy_id', 0);
  9466. if ($sid >= 0) {
  9467. $this->error('仅支持手工新增询价单');
  9468. }
  9469. $po = $this->loadManualRfqOrderForNotify($sid);
  9470. $this->assertRfqCanNotifySalesman($po);
  9471. $raw = $this->request->post('salesmen/a', []);
  9472. if (!is_array($raw) || $raw === []) {
  9473. $salesmenJson = $this->request->post('salesmen_json', '');
  9474. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9475. $decoded = json_decode($salesmenJson, true);
  9476. $raw = is_array($decoded) ? $decoded : [];
  9477. }
  9478. }
  9479. // 兼容旧参数:notify_all / 单人 name
  9480. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9481. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9482. }
  9483. if ((!is_array($raw) || $raw === [])) {
  9484. $oneName = trim((string)$this->request->post('name', ''));
  9485. if ($oneName !== '') {
  9486. $raw = [$oneName];
  9487. }
  9488. }
  9489. $selectedNames = [];
  9490. foreach ((array)$raw as $item) {
  9491. if (is_array($item)) {
  9492. $n = trim((string)($item['name'] ?? ''));
  9493. } else {
  9494. $n = trim((string)$item);
  9495. }
  9496. if ($n !== '') {
  9497. $selectedNames[] = $n;
  9498. }
  9499. }
  9500. $selectedNames = array_values(array_unique($selectedNames));
  9501. if ($selectedNames === []) {
  9502. $this->error('请选择要通知的业务员');
  9503. }
  9504. $optionMap = [];
  9505. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9506. $n = trim((string)($opt['name'] ?? ''));
  9507. if ($n === '') {
  9508. continue;
  9509. }
  9510. $optionMap[$n] = $opt;
  9511. }
  9512. $targets = [];
  9513. foreach ($selectedNames as $n) {
  9514. if (!isset($optionMap[$n])) {
  9515. $this->error('业务员不在可选名单中:' . $n);
  9516. }
  9517. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9518. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9519. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9520. }
  9521. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9522. $targets[] = $resolved[0] ?? [
  9523. 'admin_id' => 0,
  9524. 'name' => $n,
  9525. 'email' => $email,
  9526. ];
  9527. }
  9528. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9529. try {
  9530. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9531. 'notify_salesman' => $mergedStr,
  9532. ]);
  9533. } catch (\Throwable $e) {
  9534. $this->error('保存通知业务员失败:' . $e->getMessage());
  9535. }
  9536. $po['notify_salesman'] = $mergedStr;
  9537. $mailConfig = $this->loadMailerConfig();
  9538. if (empty($mailConfig['host'])) {
  9539. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9540. }
  9541. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9542. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9543. }
  9544. $this->ensureRfqSalesmanEmailTemplate();
  9545. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9546. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9547. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9548. $cdw = trim((string)($po['CDW'] ?? ''));
  9549. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9550. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9551. $mbz = trim((string)($po['MBZ'] ?? ''));
  9552. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9553. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9554. if ($supplier === '') {
  9555. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9556. }
  9557. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9558. try {
  9559. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  9560. } catch (\Throwable $e) {
  9561. $platformUrl = '';
  9562. }
  9563. try {
  9564. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9565. } catch (\Throwable $e) {
  9566. $this->error($e->getMessage());
  9567. }
  9568. $okNames = [];
  9569. $failMsgs = [];
  9570. foreach ($targets as $contact) {
  9571. $toEmail = trim((string)($contact['email'] ?? ''));
  9572. $toName = trim((string)($contact['name'] ?? ''));
  9573. $notifyVars = [
  9574. 'contact_name' => $toName,
  9575. 'salesman_name' => $toName,
  9576. 'company_name' => $toName,
  9577. 'email' => $toEmail,
  9578. 'ccydh' => $ccydh,
  9579. 'cyjmc' => $cyjmc,
  9580. 'cgymc' => $cgymc,
  9581. 'cdw' => $cdw,
  9582. 'this_quantity' => $qty,
  9583. 'ceilingPrice' => $ceiling,
  9584. 'MBZ' => $mbz,
  9585. 'supplier_name' => $supplier,
  9586. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9587. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9588. 'cywyxm' => $cywyxm,
  9589. 'platform_url' => $platformUrl,
  9590. ];
  9591. try {
  9592. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9593. $mailSubject = $mailSubjectTpl;
  9594. foreach ($notifyVars as $k => $v) {
  9595. if ($k === 'supplier_quotes') {
  9596. continue;
  9597. }
  9598. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9599. }
  9600. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9601. $mailSubject = trim((string)$mailSubject);
  9602. if ($mailSubject === '') {
  9603. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9604. }
  9605. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9606. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9607. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9608. $bundle = [
  9609. 'company_name' => $toName,
  9610. 'email' => $toEmail,
  9611. 'mail_plain' => $mailPlainForLog,
  9612. 'mail_body' => $mailBody,
  9613. 'ccydh' => $ccydh,
  9614. 'email_log_scene' => 'rfq_salesman',
  9615. 'email_log_scydgy_id' => $sid,
  9616. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9617. 'notify_vars' => $notifyVars,
  9618. ];
  9619. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9620. $okNames[] = $toName . '(' . $toEmail . ')';
  9621. } catch (\Throwable $e) {
  9622. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9623. }
  9624. }
  9625. if ($okNames === []) {
  9626. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9627. }
  9628. $now = date('Y-m-d H:i:s');
  9629. try {
  9630. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9631. 'rfq_salesman_notified' => 1,
  9632. 'rfq_salesman_notify_time' => $now,
  9633. ]);
  9634. } catch (\Throwable $e) {
  9635. // ignore
  9636. }
  9637. $this->addOrderLog(
  9638. $sid,
  9639. 'rfq_notify_salesman',
  9640. '邮箱通知业务员:' . implode('、', $okNames),
  9641. (int)($po['id'] ?? 0)
  9642. );
  9643. $msg = '已通知 ' . count($okNames) . ' 人';
  9644. if ($failMsgs !== []) {
  9645. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9646. }
  9647. $this->success($msg, null, [
  9648. 'scydgy_id' => $sid,
  9649. 'notify_salesman' => $mergedStr,
  9650. 'rfq_salesman_notified' => 1,
  9651. 'rfq_salesman_notify_time' => $now,
  9652. 'notify_time_text' => $now,
  9653. 'ok_count' => count($okNames),
  9654. 'fail_count' => count($failMsgs),
  9655. ]);
  9656. }
  9657. /**
  9658. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9659. */
  9660. public function rfqissuesuppliers()
  9661. {
  9662. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9663. $this->error(__('You have no permission'));
  9664. }
  9665. $sid = (int)$this->request->param('scydgy_id', 0);
  9666. if ($sid >= 0) {
  9667. $this->error('仅支持手工新增询价单');
  9668. }
  9669. $po = $this->loadManualRfqOrderForNotify($sid);
  9670. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9671. if ($supplierRaw === '') {
  9672. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9673. }
  9674. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9675. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9676. $notifiedMap = [];
  9677. try {
  9678. $this->ensurePurchaseEmailSendLogTableOnce();
  9679. $logRows = Db::table('purchase_email_send_log')
  9680. ->where('scydgy_id', $sid)
  9681. ->where('status', 1)
  9682. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9683. ->field('company_name')
  9684. ->select();
  9685. if (is_array($logRows)) {
  9686. foreach ($logRows as $lr) {
  9687. if (!is_array($lr)) {
  9688. continue;
  9689. }
  9690. $cn = trim((string)($lr['company_name'] ?? ''));
  9691. if ($cn !== '') {
  9692. $notifiedMap[$cn] = true;
  9693. }
  9694. }
  9695. }
  9696. } catch (\Throwable $e) {
  9697. }
  9698. // 兼容:明细已生成(曾下发)也视为已通知
  9699. try {
  9700. $detRows = Db::table('purchase_order_detail')
  9701. ->where('scydgy_id', $sid)
  9702. ->field('company_name')
  9703. ->select();
  9704. if (is_array($detRows)) {
  9705. foreach ($detRows as $dr) {
  9706. if (!is_array($dr)) {
  9707. continue;
  9708. }
  9709. $cn = trim((string)($dr['company_name'] ?? ''));
  9710. if ($cn !== '') {
  9711. $notifiedMap[$cn] = true;
  9712. }
  9713. }
  9714. }
  9715. } catch (\Throwable $e) {
  9716. }
  9717. $list = [];
  9718. foreach ($names as $name) {
  9719. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9720. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9721. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9722. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9723. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9724. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9725. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9726. $list[] = [
  9727. 'name' => $name,
  9728. 'username' => $username,
  9729. 'email' => $email,
  9730. 'phone' => $phone,
  9731. 'can_notify' => $okEmail ? 1 : 0,
  9732. 'found' => is_array($contact) ? 1 : 0,
  9733. 'notified' => $notified,
  9734. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9735. ];
  9736. }
  9737. $this->success('', null, [
  9738. 'scydgy_id' => $sid,
  9739. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9740. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9741. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9742. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9743. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9744. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9745. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9746. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9747. 'list' => $list,
  9748. ]);
  9749. }
  9750. /**
  9751. * 查询询价 — 补加供应商可选名单
  9752. */
  9753. public function rfqsupplieroptions()
  9754. {
  9755. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9756. $this->error(__('You have no permission'));
  9757. }
  9758. $names = array_values($this->loadRfqSupplierNameOptions());
  9759. $out = [];
  9760. foreach ($names as $name) {
  9761. $out[] = ['name' => $name];
  9762. }
  9763. $this->success('', null, ['list' => $out]);
  9764. }
  9765. /**
  9766. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9767. */
  9768. public function rfqappendsuppliers()
  9769. {
  9770. if (!$this->request->isPost()) {
  9771. $this->error(__('Invalid parameters'));
  9772. }
  9773. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9774. $this->error(__('You have no permission'));
  9775. }
  9776. $sid = (int)$this->request->post('scydgy_id', 0);
  9777. if ($sid >= 0) {
  9778. $this->error('仅支持手工新增询价单');
  9779. }
  9780. $po = $this->loadManualRfqOrderForNotify($sid);
  9781. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9782. $this->error('订单已完结,无法补加供应商');
  9783. }
  9784. $raw = $this->request->post('suppliers/a', []);
  9785. if (!is_array($raw) || $raw === []) {
  9786. $suppliersJson = $this->request->post('suppliers_json', '');
  9787. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9788. $decoded = json_decode($suppliersJson, true);
  9789. $raw = is_array($decoded) ? $decoded : [];
  9790. }
  9791. }
  9792. $addNames = [];
  9793. foreach ((array)$raw as $item) {
  9794. if (is_array($item)) {
  9795. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9796. } else {
  9797. $n = trim((string)$item);
  9798. }
  9799. if ($n !== '') {
  9800. $addNames[] = $n;
  9801. }
  9802. }
  9803. $addNames = array_values(array_unique($addNames));
  9804. if ($addNames === []) {
  9805. $this->error('请选择要补加的供应商');
  9806. }
  9807. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9808. if ($existingRaw === '') {
  9809. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9810. }
  9811. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9812. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9813. try {
  9814. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9815. } catch (\Throwable $e) {
  9816. $this->error('保存失败:' . $e->getMessage());
  9817. }
  9818. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9819. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9820. $this->success('已补加供应商', null, [
  9821. 'scydgy_id' => $sid,
  9822. 'cGzzxMc' => $mergedStr,
  9823. 'added_count' => count($addNames),
  9824. ]);
  9825. }
  9826. /**
  9827. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9828. */
  9829. public function rfqissue()
  9830. {
  9831. if (!$this->request->isPost()) {
  9832. $this->error(__('Invalid parameters'));
  9833. }
  9834. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9835. $this->error(__('You have no permission'));
  9836. }
  9837. $this->ensureRfqSupplierEmailTemplate();
  9838. $sid = (int)$this->request->post('scydgy_id', 0);
  9839. if ($sid >= 0) {
  9840. $this->error('仅支持手工新增询价单');
  9841. }
  9842. $po = $this->loadManualRfqOrderForNotify($sid);
  9843. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9844. $this->error('订单已完结,无法下发');
  9845. }
  9846. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9847. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9848. $this->error('订单已进入后续流程,无法再下发');
  9849. }
  9850. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9851. if ($supplierRaw === '') {
  9852. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9853. }
  9854. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9855. if ($supplierNames === []) {
  9856. $this->error('请先在新增询价时选择供应商');
  9857. }
  9858. $companies = [];
  9859. $missing = [];
  9860. $noEmail = [];
  9861. foreach ($supplierNames as $name) {
  9862. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9863. if ($contact === null) {
  9864. $missing[] = $name;
  9865. continue;
  9866. }
  9867. $em = trim((string)($contact['email'] ?? ''));
  9868. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9869. $noEmail[] = $name;
  9870. continue;
  9871. }
  9872. $companies[] = $contact;
  9873. }
  9874. if ($missing !== []) {
  9875. $this->error('未找到供应商档案:' . implode('、', $missing));
  9876. }
  9877. if ($noEmail !== []) {
  9878. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9879. }
  9880. if ($companies === []) {
  9881. $this->error('没有可通知的供应商');
  9882. }
  9883. $mailConfig = $this->loadMailerConfig();
  9884. if (empty($mailConfig['host'])) {
  9885. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9886. }
  9887. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9888. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9889. }
  9890. $mergeRow = $po;
  9891. $mergeRow['ID'] = $sid;
  9892. $mergeRow['id'] = $sid;
  9893. $mergeRows = [$mergeRow];
  9894. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9895. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9896. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9897. }
  9898. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9899. $issueTime = date('Y-m-d H:i:s');
  9900. $nameLabels = [];
  9901. foreach ($companies as $c) {
  9902. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9903. }
  9904. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9905. Db::startTrans();
  9906. try {
  9907. $this->upsertPurchaseOrderFromRow(
  9908. $mergeRow,
  9909. $sysRqDb,
  9910. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9911. $issueTime,
  9912. $po,
  9913. null,
  9914. $scoreRule
  9915. );
  9916. foreach ($companies as $c) {
  9917. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9918. }
  9919. Db::commit();
  9920. } catch (\Throwable $e) {
  9921. Db::rollback();
  9922. $this->error($e->getMessage());
  9923. }
  9924. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9925. if ($poId <= 0) {
  9926. try {
  9927. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9928. } catch (\Throwable $e) {
  9929. $poId = 0;
  9930. }
  9931. }
  9932. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9933. $posNotify = [];
  9934. try {
  9935. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9936. if (is_array($fresh)) {
  9937. $fresh['sys_rq'] = $sysRqDb;
  9938. $posNotify = [$fresh];
  9939. }
  9940. } catch (\Throwable $e) {
  9941. $posNotify = [$po];
  9942. $posNotify[0]['sys_rq'] = $sysRqDb;
  9943. }
  9944. $notifyBundle = [
  9945. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9946. 'pos' => $posNotify,
  9947. 'merge_rows' => $mergeRows,
  9948. ];
  9949. $notifyErrors = [];
  9950. foreach ($companies as $c) {
  9951. $cname = trim((string)($c['name'] ?? ''));
  9952. try {
  9953. // 询价下发:仅邮箱通知供应商
  9954. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9955. } catch (\Throwable $e) {
  9956. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9957. }
  9958. }
  9959. if ($notifyErrors !== []) {
  9960. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9961. }
  9962. $this->success('已询价并邮件通知供应商', null, [
  9963. 'scydgy_id' => $sid,
  9964. 'progress_text' => '待报价',
  9965. 'supplier_count' => count($companies),
  9966. ]);
  9967. }
  9968. /**
  9969. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9970. */
  9971. public function rfqissuesendmail()
  9972. {
  9973. if (!$this->request->isPost()) {
  9974. $this->error(__('Invalid parameters'));
  9975. }
  9976. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9977. $this->error(__('You have no permission'));
  9978. }
  9979. $this->ensureRfqSupplierEmailTemplate();
  9980. $sid = (int)$this->request->post('scydgy_id', 0);
  9981. $companyName = trim((string)$this->request->post('company_name', ''));
  9982. if ($sid >= 0) {
  9983. $this->error('仅支持手工新增询价单');
  9984. }
  9985. if ($companyName === '') {
  9986. $this->error('请选择供应商');
  9987. }
  9988. $po = $this->loadManualRfqOrderForNotify($sid);
  9989. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9990. $this->error('订单已完结,无法发送');
  9991. }
  9992. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9993. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9994. $this->error('订单已进入后续流程,无法再发送');
  9995. }
  9996. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9997. if ($contact === null) {
  9998. $this->error('未找到供应商档案:' . $companyName);
  9999. }
  10000. $email = trim((string)($contact['email'] ?? ''));
  10001. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  10002. $this->error('该供应商未填写有效邮箱');
  10003. }
  10004. $mailConfig = $this->loadMailerConfig();
  10005. if (empty($mailConfig['host'])) {
  10006. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  10007. }
  10008. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  10009. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  10010. }
  10011. $mergeRow = $po;
  10012. $mergeRow['ID'] = $sid;
  10013. $mergeRow['id'] = $sid;
  10014. $mergeRows = [$mergeRow];
  10015. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  10016. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  10017. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  10018. }
  10019. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  10020. $issueTime = date('Y-m-d H:i:s');
  10021. Db::startTrans();
  10022. try {
  10023. $this->upsertPurchaseOrderFromRow(
  10024. $mergeRow,
  10025. $sysRqDb,
  10026. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10027. $issueTime,
  10028. $po,
  10029. null,
  10030. $scoreRule
  10031. );
  10032. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  10033. Db::commit();
  10034. } catch (\Throwable $e) {
  10035. Db::rollback();
  10036. $this->error($e->getMessage());
  10037. }
  10038. $posNotify = [];
  10039. try {
  10040. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  10041. if (is_array($fresh)) {
  10042. $fresh['sys_rq'] = $sysRqDb;
  10043. $posNotify = [$fresh];
  10044. }
  10045. } catch (\Throwable $e) {
  10046. $posNotify = [$po];
  10047. $posNotify[0]['sys_rq'] = $sysRqDb;
  10048. }
  10049. $notifyBundle = [
  10050. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  10051. 'pos' => $posNotify,
  10052. 'merge_rows' => $mergeRows,
  10053. ];
  10054. try {
  10055. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  10056. } catch (\Throwable $e) {
  10057. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  10058. }
  10059. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10060. if ($poId <= 0) {
  10061. try {
  10062. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  10063. } catch (\Throwable $e) {
  10064. $poId = 0;
  10065. }
  10066. }
  10067. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  10068. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  10069. 'scydgy_id' => $sid,
  10070. 'company_name' => $companyName,
  10071. ]);
  10072. }
  10073. /**
  10074. * 查询询价 — 查看各供应商报价(单价)
  10075. */
  10076. public function rfqquotes()
  10077. {
  10078. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  10079. $this->error(__('You have no permission'));
  10080. }
  10081. $sid = (int)$this->request->param('scydgy_id', 0);
  10082. if ($sid >= 0) {
  10083. $this->error('仅支持手工新增询价单');
  10084. }
  10085. $po = $this->loadManualRfqOrderForNotify($sid);
  10086. $rows = [];
  10087. try {
  10088. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  10089. $q = Db::table('purchase_order_detail')
  10090. ->where('scydgy_id', $sid)
  10091. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  10092. ->order('id', 'asc');
  10093. $this->applyActivePurchaseOrderDetailWhere($q);
  10094. $rows = $q->select();
  10095. } catch (\Throwable $e) {
  10096. try {
  10097. $q = Db::table('purchase_order_detail')
  10098. ->where('scydgy_id', $sid)
  10099. ->order('id', 'asc');
  10100. $this->applyActivePurchaseOrderDetailWhere($q);
  10101. $rows = $q->select();
  10102. } catch (\Throwable $e2) {
  10103. $rows = [];
  10104. }
  10105. }
  10106. if (!is_array($rows)) {
  10107. $rows = [];
  10108. }
  10109. $list = [];
  10110. foreach ($rows as $row) {
  10111. if (!is_array($row)) {
  10112. continue;
  10113. }
  10114. $amount = trim((string)($row['amount'] ?? ''));
  10115. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  10116. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  10117. $oper = '';
  10118. if ($isQuoted) {
  10119. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  10120. if ($oper === '') {
  10121. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  10122. }
  10123. }
  10124. $list[] = [
  10125. 'id' => (int)($row['id'] ?? 0),
  10126. 'company_name' => trim((string)($row['company_name'] ?? '')),
  10127. 'amount' => $amount,
  10128. 'amount_text' => $isQuoted ? $amount : '',
  10129. 'is_quoted' => $isQuoted,
  10130. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  10131. 'status_name' => trim((string)($row['status_name'] ?? '')),
  10132. 'oper_time' => $oper,
  10133. ];
  10134. }
  10135. $this->success('', null, [
  10136. 'scydgy_id' => $sid,
  10137. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  10138. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  10139. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  10140. 'CDW' => trim((string)($po['CDW'] ?? '')),
  10141. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  10142. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  10143. 'CDF' => trim((string)($po['CDF'] ?? '')),
  10144. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  10145. 'list' => $list,
  10146. ]);
  10147. }
  10148. /**
  10149. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  10150. */
  10151. protected function isRfqOrderIssued(array $po): bool
  10152. {
  10153. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  10154. return true;
  10155. }
  10156. $sid = (int)($po['scydgy_id'] ?? 0);
  10157. if ($sid >= 0) {
  10158. return false;
  10159. }
  10160. try {
  10161. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10162. $this->applyActivePurchaseOrderDetailWhere($q);
  10163. return (int)$q->count() > 0;
  10164. } catch (\Throwable $e) {
  10165. return false;
  10166. }
  10167. }
  10168. /**
  10169. * 批量:已有下发明细的手工询价 scydgy_id
  10170. *
  10171. * @param int[] $scydgyIds
  10172. * @return array<int, bool>
  10173. */
  10174. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  10175. {
  10176. $set = [];
  10177. $ids = [];
  10178. foreach ($scydgyIds as $sid) {
  10179. $sid = (int)$sid;
  10180. if ($sid < 0) {
  10181. $ids[$sid] = true;
  10182. }
  10183. }
  10184. if ($ids === []) {
  10185. return $set;
  10186. }
  10187. try {
  10188. $q = Db::table('purchase_order_detail')
  10189. ->where('scydgy_id', 'in', array_keys($ids))
  10190. ->field('scydgy_id');
  10191. $this->applyActivePurchaseOrderDetailWhere($q);
  10192. $rows = $q->select();
  10193. } catch (\Throwable $e) {
  10194. return $set;
  10195. }
  10196. if (!is_array($rows)) {
  10197. return $set;
  10198. }
  10199. foreach ($rows as $row) {
  10200. if (!is_array($row)) {
  10201. continue;
  10202. }
  10203. $sid = (int)($row['scydgy_id'] ?? 0);
  10204. if ($sid < 0) {
  10205. $set[$sid] = true;
  10206. }
  10207. }
  10208. return $set;
  10209. }
  10210. /**
  10211. * 批量:已填单价(已报价)的手工询价 scydgy_id
  10212. *
  10213. * @param int[] $scydgyIds
  10214. * @return array<int, bool>
  10215. */
  10216. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  10217. {
  10218. $set = [];
  10219. $ids = [];
  10220. foreach ($scydgyIds as $sid) {
  10221. $sid = (int)$sid;
  10222. if ($sid < 0) {
  10223. $ids[$sid] = true;
  10224. }
  10225. }
  10226. if ($ids === []) {
  10227. return $set;
  10228. }
  10229. try {
  10230. $q = Db::table('purchase_order_detail')
  10231. ->where('scydgy_id', 'in', array_keys($ids))
  10232. ->field('scydgy_id,amount');
  10233. $this->applyActivePurchaseOrderDetailWhere($q);
  10234. $rows = $q->select();
  10235. } catch (\Throwable $e) {
  10236. return $set;
  10237. }
  10238. if (!is_array($rows)) {
  10239. return $set;
  10240. }
  10241. foreach ($rows as $row) {
  10242. if (!is_array($row)) {
  10243. continue;
  10244. }
  10245. $amount = trim((string)($row['amount'] ?? ''));
  10246. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10247. continue;
  10248. }
  10249. $sid = (int)($row['scydgy_id'] ?? 0);
  10250. if ($sid < 0) {
  10251. $set[$sid] = true;
  10252. }
  10253. }
  10254. return $set;
  10255. }
  10256. /**
  10257. * 已下发且至少一家供应商已报价,才允许通知业务员
  10258. */
  10259. protected function canRfqNotifySalesman(array $po): bool
  10260. {
  10261. if (!$this->isRfqOrderIssued($po)) {
  10262. return false;
  10263. }
  10264. $sid = (int)($po['scydgy_id'] ?? 0);
  10265. if ($sid >= 0) {
  10266. return false;
  10267. }
  10268. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10269. return isset($quoted[$sid]);
  10270. }
  10271. protected function assertRfqCanNotifySalesman(array $po): void
  10272. {
  10273. if (!$this->isRfqOrderIssued($po)) {
  10274. $this->error('请先询价并等待供应商报价后再通知业务员');
  10275. }
  10276. if (!$this->canRfqNotifySalesman($po)) {
  10277. $this->error('供应商尚未报价,暂不能通知业务员');
  10278. }
  10279. }
  10280. /**
  10281. * 加载手工询价单(含可见性校验)
  10282. *
  10283. * @return array<string, mixed>
  10284. */
  10285. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10286. {
  10287. try {
  10288. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10289. } catch (\Throwable $e) {
  10290. $po = null;
  10291. }
  10292. if (!is_array($po)) {
  10293. $this->error('订单不存在');
  10294. }
  10295. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10296. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10297. $this->error('订单不存在');
  10298. }
  10299. if ($this->auth->isSuperAdmin()) {
  10300. return $po;
  10301. }
  10302. if ($this->canViewManualRfqOrder($po)) {
  10303. return $po;
  10304. }
  10305. $this->error('无权操作该订单');
  10306. }
  10307. /**
  10308. * @return string[]
  10309. */
  10310. protected function splitRfqSalesmanNames(string $raw): array
  10311. {
  10312. $parts = [];
  10313. $raw = trim($raw);
  10314. if ($raw === '') {
  10315. return [];
  10316. }
  10317. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10318. $v = trim((string)$piece);
  10319. if ($v !== '' && !in_array($v, $parts, true)) {
  10320. $parts[] = $v;
  10321. }
  10322. }
  10323. return $parts;
  10324. }
  10325. /**
  10326. * 按姓名匹配 fa_admin 邮箱
  10327. *
  10328. * @param string[] $names
  10329. * @return array<int, array{admin_id:int,name:string,email:string}>
  10330. */
  10331. protected function resolveRfqSalesmanContactRows(array $names): array
  10332. {
  10333. $out = [];
  10334. foreach ($names as $name) {
  10335. $name = trim((string)$name);
  10336. if ($name === '') {
  10337. continue;
  10338. }
  10339. $adminId = 0;
  10340. $email = '';
  10341. try {
  10342. $row = Db::name('admin')
  10343. ->where(function ($q) use ($name) {
  10344. $q->where('nickname', $name)->whereOr('username', $name);
  10345. })
  10346. ->where('status', 'normal')
  10347. ->order('id', 'asc')
  10348. ->field('id,nickname,username,email')
  10349. ->find();
  10350. } catch (\Throwable $e) {
  10351. $row = null;
  10352. }
  10353. if (is_array($row)) {
  10354. $adminId = (int)($row['id'] ?? 0);
  10355. $email = trim((string)($row['email'] ?? ''));
  10356. $disp = trim((string)($row['nickname'] ?? ''));
  10357. if ($disp === '') {
  10358. $disp = trim((string)($row['username'] ?? ''));
  10359. }
  10360. if ($disp !== '') {
  10361. $name = $disp;
  10362. }
  10363. }
  10364. $out[] = [
  10365. 'admin_id' => $adminId,
  10366. 'name' => $name,
  10367. 'email' => $email,
  10368. ];
  10369. }
  10370. return $out;
  10371. }
  10372. /**
  10373. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10374. */
  10375. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10376. {
  10377. if ($scydgyId >= 0) {
  10378. return;
  10379. }
  10380. try {
  10381. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10382. } catch (\Throwable $e) {
  10383. $po = null;
  10384. }
  10385. if (!is_array($po)) {
  10386. $this->error('订单不存在');
  10387. }
  10388. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10389. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10390. $this->error('订单不存在');
  10391. }
  10392. if ($this->auth->isSuperAdmin()) {
  10393. return;
  10394. }
  10395. [, $adminName] = $this->GetUseName();
  10396. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10397. if ($cywy !== '' && $cywy === $adminName) {
  10398. return;
  10399. }
  10400. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10401. try {
  10402. if ($this->auth->check($rule)) {
  10403. return;
  10404. }
  10405. } catch (\Throwable $e) {
  10406. }
  10407. }
  10408. $this->error('无权查看该订单');
  10409. }
  10410. /**
  10411. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10412. */
  10413. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10414. {
  10415. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10416. return ProcuremenStatus::PO_COMPLETED;
  10417. }
  10418. $sid = (int)($row['scydgy_id'] ?? 0);
  10419. if ($sid < 0) {
  10420. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10421. return '已通知业务员';
  10422. }
  10423. if ($hasQuoted) {
  10424. return '供应商已报价';
  10425. }
  10426. if ($hasIssued
  10427. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10428. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10429. return '待报价';
  10430. }
  10431. try {
  10432. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10433. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10434. if ((int)$detCntQuery->count() > 0) {
  10435. return '待报价';
  10436. }
  10437. } catch (\Throwable $e) {
  10438. }
  10439. return '待询价';
  10440. }
  10441. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10442. return '待入库评分';
  10443. }
  10444. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10445. return '待采购确认';
  10446. }
  10447. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10448. return '待确认供应商';
  10449. }
  10450. return '待协助下发';
  10451. }
  10452. /**
  10453. * 协助初选列表 — 批量软删除
  10454. */
  10455. public function pickDelete()
  10456. {
  10457. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10458. $this->error(__('Invalid parameters'));
  10459. }
  10460. if (!$this->procuremenCanPickDelete()) {
  10461. $this->error(__('You have no permission'));
  10462. }
  10463. $rowsRaw = $this->request->post('rows_json', '[]');
  10464. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10465. if (!is_array($rows) || $rows === []) {
  10466. $this->error('请至少勾选一条工序');
  10467. }
  10468. $done = 0;
  10469. Db::startTrans();
  10470. try {
  10471. foreach ($rows as $row) {
  10472. if (!is_array($row)) {
  10473. continue;
  10474. }
  10475. $this->softDeleteProcuremenPickRow($row);
  10476. $done++;
  10477. }
  10478. if ($done < 1) {
  10479. throw new \Exception('没有可删除的工序');
  10480. }
  10481. Db::commit();
  10482. } catch (\InvalidArgumentException $e) {
  10483. Db::rollback();
  10484. $this->error($e->getMessage());
  10485. } catch (\Throwable $e) {
  10486. Db::rollback();
  10487. $this->error($e->getMessage());
  10488. }
  10489. $this->pickHiddenScydgySetCache = null;
  10490. $this->success('已删除 ' . $done . ' 条工序');
  10491. }
  10492. /**
  10493. * 下发 — 手工新增工序(弹窗)
  10494. */
  10495. public function pickAdd()
  10496. {
  10497. if ($this->request->isPost()) {
  10498. $params = $this->request->post('row/a');
  10499. if (!is_array($params)) {
  10500. $this->error(__('Parameter %s can not be empty', ''));
  10501. }
  10502. try {
  10503. $sid = $this->saveManualPickOrder($params);
  10504. } catch (\InvalidArgumentException $e) {
  10505. $this->error($e->getMessage());
  10506. } catch (\Throwable $e) {
  10507. $this->error($e->getMessage());
  10508. }
  10509. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10510. }
  10511. return $this->view->fetch('procuremen/pick_add');
  10512. }
  10513. /**
  10514. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10515. */
  10516. public function pickSubmit()
  10517. {
  10518. if (!$this->request->isPost()) {
  10519. $this->error(__('Invalid parameters'));
  10520. }
  10521. // ---------- 接口订单数据 ----------
  10522. $rowJson = $this->request->post('row_json', '');
  10523. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10524. $companiesJson = $this->request->post('companies_json', '[]');
  10525. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10526. $companies = json_decode($companiesJson, true);
  10527. if (!is_array($companies)) {
  10528. $this->error('供应商数据无效');
  10529. }
  10530. $issueCompanies = $this->normalizePickCompanies($companies);
  10531. if ($issueCompanies === []) {
  10532. $this->error('请至少选择一家合作供应商');
  10533. }
  10534. $issueNameLabels = [];
  10535. foreach ($issueCompanies as $pc) {
  10536. $issueNameLabels[] = $pc['name'];
  10537. }
  10538. $issueNamesSummary = implode('、', $issueNameLabels);
  10539. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10540. if ($sysRq === '') {
  10541. $this->error('请选择招标截止日期');
  10542. }
  10543. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10544. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10545. (string)$this->request->post('delivery_deadline', ''),
  10546. true
  10547. );
  10548. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10549. if ($scoreRuleId <= 0) {
  10550. $this->error('请选择订单类型');
  10551. }
  10552. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10553. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10554. $this->error('订单类型无效,请刷新后重选');
  10555. }
  10556. $scoreRuleId = (int)$scoreRule['id'];
  10557. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10558. $isMerge = count($mergeRows) > 1;
  10559. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10560. $logMsg = '下发' . $procPart
  10561. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10562. $issueTime = date('Y-m-d H:i:s');
  10563. $logSidList = [];
  10564. foreach ($mergeRows as $row) {
  10565. if (!is_array($row)) {
  10566. continue;
  10567. }
  10568. $sid = $this->extractScydgyRowId($row);
  10569. if ($this->isValidScydgyRowId($sid)) {
  10570. $logSidList[$sid] = true;
  10571. }
  10572. }
  10573. if ($logSidList === []) {
  10574. $this->error('未找到有效工序,无法下发');
  10575. }
  10576. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  10577. $sidKeys = array_keys($logSidList);
  10578. sort($sidKeys, SORT_NUMERIC);
  10579. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  10580. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  10581. $this->error('下发处理中,请勿重复点击');
  10582. }
  10583. $existingBySid = [];
  10584. try {
  10585. try {
  10586. $existingRows = Db::table('purchase_order')
  10587. ->where('scydgy_id', 'in', $sidKeys)
  10588. ->select();
  10589. if (is_array($existingRows)) {
  10590. foreach ($existingRows as $poRow) {
  10591. if (!is_array($poRow)) {
  10592. continue;
  10593. }
  10594. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10595. if ($this->isValidScydgyRowId($sid)) {
  10596. $existingBySid[$sid] = $poRow;
  10597. }
  10598. }
  10599. }
  10600. } catch (\Throwable $e) {
  10601. $existingBySid = [];
  10602. }
  10603. foreach ($sidKeys as $sid) {
  10604. $poRow = $existingBySid[$sid] ?? null;
  10605. if (!is_array($poRow)) {
  10606. continue;
  10607. }
  10608. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  10609. continue;
  10610. }
  10611. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  10612. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  10613. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  10614. }
  10615. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  10616. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  10617. }
  10618. }
  10619. Db::startTrans();
  10620. try {
  10621. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10622. foreach ($mergeRows as $row) {
  10623. if (!is_array($row)) {
  10624. continue;
  10625. }
  10626. $sid = $this->extractScydgyRowId($row);
  10627. $this->upsertPurchaseOrderFromRow(
  10628. $row,
  10629. $sysRqDb,
  10630. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10631. $issueTime,
  10632. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10633. $deliveryDeadlineDb,
  10634. $scoreRule
  10635. );
  10636. }
  10637. foreach ($issueCompanies as $c) {
  10638. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10639. }
  10640. Db::commit();
  10641. } catch (\Throwable $e) {
  10642. Db::rollback();
  10643. $this->error($e->getMessage());
  10644. }
  10645. } finally {
  10646. $this->releaseProcuremenNamedLock($pickLockName);
  10647. }
  10648. $poIdBySid = [];
  10649. if ($logSidList !== []) {
  10650. try {
  10651. $poIdBySid = Db::table('purchase_order')
  10652. ->where('scydgy_id', 'in', array_keys($logSidList))
  10653. ->column('id', 'scydgy_id');
  10654. } catch (\Throwable $e) {
  10655. $poIdBySid = [];
  10656. }
  10657. }
  10658. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10659. if ($logSidList !== []) {
  10660. list($adminId, $adminName) = $this->GetUseName();
  10661. $logRows = [];
  10662. $seenLogSid = [];
  10663. foreach ($mergeRows as $row) {
  10664. if (!is_array($row)) {
  10665. continue;
  10666. }
  10667. $ids = $this->extractScydgyRowId($row);
  10668. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10669. continue;
  10670. }
  10671. $seenLogSid[$ids] = true;
  10672. $poIdLog = null;
  10673. if (isset($poIdBySid[$ids])) {
  10674. $tid = (int)$poIdBySid[$ids];
  10675. $poIdLog = $tid > 0 ? $tid : null;
  10676. }
  10677. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10678. $ids,
  10679. 'issue_submit',
  10680. $logMsg,
  10681. $poIdLog,
  10682. (int)$adminId,
  10683. (string)$adminName
  10684. );
  10685. }
  10686. if ($logRows !== []) {
  10687. try {
  10688. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10689. } catch (\Throwable $e) {
  10690. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10691. }
  10692. }
  10693. }
  10694. $notifyErrors = [];
  10695. $posNotify = [];
  10696. if ($logSidList !== []) {
  10697. try {
  10698. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10699. } catch (\Throwable $e) {
  10700. $posNotify = [];
  10701. }
  10702. }
  10703. if (!is_array($posNotify)) {
  10704. $posNotify = [];
  10705. }
  10706. foreach ($posNotify as $i => $prow) {
  10707. if (is_array($posNotify[$i])) {
  10708. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10709. }
  10710. }
  10711. $ccydhPick = '';
  10712. foreach ($mergeRows as $row) {
  10713. if (!is_array($row)) {
  10714. continue;
  10715. }
  10716. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10717. if ($ccydhPick !== '') {
  10718. break;
  10719. }
  10720. }
  10721. $notifyBundleBase = [
  10722. 'ccydh' => $ccydhPick,
  10723. 'pos' => $posNotify,
  10724. 'merge_rows' => $mergeRows,
  10725. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10726. ];
  10727. try {
  10728. $this->notifyDryRunPreview = [];
  10729. foreach ($issueCompanies as $c) {
  10730. if (!is_array($c)) {
  10731. continue;
  10732. }
  10733. $cname = trim((string)($c['name'] ?? ''));
  10734. if ($cname === '') {
  10735. continue;
  10736. }
  10737. try {
  10738. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10739. } catch (\Throwable $e) {
  10740. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10741. }
  10742. }
  10743. } catch (\Throwable $e) {
  10744. $this->error('通知发送失败:' . $e->getMessage());
  10745. }
  10746. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10747. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10748. }
  10749. if ($this->isProcuremenNotifyDryRun()) {
  10750. $this->success('【演练模式】已保存并生成通知预览', '', [
  10751. 'notify_dry_run' => true,
  10752. 'notify_preview' => $this->notifyDryRunPreview,
  10753. ]);
  10754. }
  10755. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10756. }
  10757. /**
  10758. * 确认供应商弹窗
  10759. */
  10760. public function auditIssue()
  10761. {
  10762. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10763. if (is_array($ids)) {
  10764. $ids = isset($ids[0]) ? $ids[0] : '';
  10765. }
  10766. $ids = trim((string)$ids);
  10767. if ($ids === '') {
  10768. $this->error(__('Invalid parameters'));
  10769. }
  10770. if ($this->request->isPost()) {
  10771. $this->error('请使用弹窗内「确认」提交');
  10772. }
  10773. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10774. $pos = $bundle['pos'];
  10775. if ($pos === []) {
  10776. $this->error('该订单不在待确认供应商状态');
  10777. }
  10778. $po = $pos[0];
  10779. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10780. if ($quoteGroups === []) {
  10781. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10782. }
  10783. $pickedName = '';
  10784. foreach ($pos as $poRow) {
  10785. if (!is_array($poRow)) {
  10786. continue;
  10787. }
  10788. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10789. if ($pn !== '') {
  10790. $pickedName = $pn;
  10791. break;
  10792. }
  10793. }
  10794. $this->view->assign('po', $po);
  10795. $this->view->assign('scydgyId', $ids);
  10796. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10797. $mergeRows = $bundle['merge_rows'];
  10798. $this->view->assign('processRows', $mergeRows);
  10799. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10800. $this->view->assign('processCount', count($mergeRows));
  10801. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10802. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10803. $this->view->assign('pickedCompanyName', $pickedName);
  10804. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10805. if ($sysRqForView === '') {
  10806. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10807. }
  10808. $this->view->assign('sysRq', $sysRqForView);
  10809. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10810. if ($deliveryDeadlineForView === '') {
  10811. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10812. }
  10813. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10814. $this->ensurePurchaseOrderManualPickColumns();
  10815. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10816. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10817. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10818. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10819. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10820. $pickedName = $manualPickInfo['company'];
  10821. $this->view->assign('pickedCompanyName', $pickedName);
  10822. }
  10823. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10824. $this->view->assign('manualPicked', $manualPicked);
  10825. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10826. $this->view->assign('quoteVisible', $quoteVisible);
  10827. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10828. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10829. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10830. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10831. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10832. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10833. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10834. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10835. return $this->view->fetch('procuremen/audit_issue');
  10836. }
  10837. /**
  10838. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10839. *
  10840. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10841. */
  10842. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10843. {
  10844. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10845. return false;
  10846. }
  10847. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10848. return false;
  10849. }
  10850. return true;
  10851. }
  10852. /**
  10853. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10854. *
  10855. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10856. */
  10857. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10858. {
  10859. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10860. return false;
  10861. }
  10862. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10863. return false;
  10864. }
  10865. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10866. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10867. return true;
  10868. }
  10869. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10870. }
  10871. /**
  10872. * 确认页 — 补加供应商弹窗
  10873. */
  10874. public function auditAppend()
  10875. {
  10876. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10877. $this->error(__('You have no permission'));
  10878. }
  10879. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10880. if (is_array($ids)) {
  10881. $ids = isset($ids[0]) ? $ids[0] : '';
  10882. }
  10883. $ids = trim((string)$ids);
  10884. if ($ids === '') {
  10885. $this->error(__('Invalid parameters'));
  10886. }
  10887. if ($this->request->isPost()) {
  10888. $this->error('请使用弹窗内「确认」提交');
  10889. }
  10890. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10891. if (($bundle['pos'] ?? []) === []) {
  10892. $this->error('该订单不在待确认供应商状态');
  10893. }
  10894. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10895. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10896. $this->error('已开标验证,不能再补加供应商');
  10897. }
  10898. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10899. $this->error('已指定供应商,不能再补加供应商');
  10900. }
  10901. $this->error('已经超过了招标截止日期,不可操作');
  10902. }
  10903. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10904. $existingNames = [];
  10905. foreach ($quoteGroups as $g) {
  10906. if (!is_array($g)) {
  10907. continue;
  10908. }
  10909. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10910. if ($n !== '') {
  10911. $existingNames[$n] = true;
  10912. }
  10913. }
  10914. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10915. $mergeRows = $bundle['merge_rows'] ?? [];
  10916. $this->view->assign('scydgyId', $ids);
  10917. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10918. $this->view->assign('po', $po);
  10919. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10920. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10921. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10922. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10923. if ($sysRqForView === '') {
  10924. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10925. }
  10926. $this->view->assign('sysRq', $sysRqForView);
  10927. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10928. if ($deliveryDeadlineForView === '') {
  10929. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10930. }
  10931. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10932. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10933. }
  10934. /**
  10935. * 确认页 — 补加供应商提交
  10936. */
  10937. public function auditAppendSubmit()
  10938. {
  10939. if (!$this->request->isPost()) {
  10940. $this->error(__('Invalid parameters'));
  10941. }
  10942. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10943. $this->error(__('You have no permission'));
  10944. }
  10945. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10946. if ($ids === '') {
  10947. $this->error(__('Invalid parameters'));
  10948. }
  10949. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10950. if (($bundle['pos'] ?? []) === []) {
  10951. $this->error('该订单不在待确认供应商状态');
  10952. }
  10953. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10954. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10955. $this->error('已开标验证,不能再补加供应商');
  10956. }
  10957. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10958. $this->error('已指定供应商,不能再补加供应商');
  10959. }
  10960. $this->error('已经超过了招标截止日期,不可操作');
  10961. }
  10962. $companiesJson = $this->request->post('companies_json', '[]');
  10963. $companies = json_decode((string)$companiesJson, true);
  10964. if (!is_array($companies)) {
  10965. $this->error('供应商数据无效');
  10966. }
  10967. $issueCompanies = $this->normalizePickCompanies($companies);
  10968. if ($issueCompanies === []) {
  10969. $this->error('请至少选择一家合作供应商');
  10970. }
  10971. $mergeRows = $bundle['merge_rows'] ?? [];
  10972. if (!is_array($mergeRows) || $mergeRows === []) {
  10973. $this->error('未找到工序行,无法补加');
  10974. }
  10975. $existingNames = [];
  10976. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10977. if (!is_array($g)) {
  10978. continue;
  10979. }
  10980. $n = trim((string)($g['company_name'] ?? ''));
  10981. if ($n !== '') {
  10982. $existingNames[$n] = true;
  10983. }
  10984. }
  10985. $toAdd = [];
  10986. foreach ($issueCompanies as $c) {
  10987. if (!is_array($c)) {
  10988. continue;
  10989. }
  10990. $n = trim((string)($c['name'] ?? ''));
  10991. if ($n === '' || isset($existingNames[$n])) {
  10992. continue;
  10993. }
  10994. $toAdd[] = $c;
  10995. }
  10996. if ($toAdd === []) {
  10997. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10998. }
  10999. $addedNames = [];
  11000. Db::startTrans();
  11001. try {
  11002. foreach ($toAdd as $c) {
  11003. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  11004. $addedNames[] = trim((string)($c['name'] ?? ''));
  11005. }
  11006. Db::commit();
  11007. } catch (\Throwable $e) {
  11008. Db::rollback();
  11009. $this->error($e->getMessage());
  11010. }
  11011. $notifyErrors = [];
  11012. $notifyBundleBase = [
  11013. 'ccydh' => $bundle['ccydh'] ?? '',
  11014. 'pos' => $bundle['pos'] ?? [],
  11015. 'merge_rows' => $mergeRows,
  11016. ];
  11017. foreach ($toAdd as $c) {
  11018. if (!is_array($c)) {
  11019. continue;
  11020. }
  11021. $cname = trim((string)($c['name'] ?? ''));
  11022. if ($cname === '') {
  11023. continue;
  11024. }
  11025. try {
  11026. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  11027. } catch (\Throwable $e) {
  11028. $notifyErrors[] = $cname . ':' . $e->getMessage();
  11029. }
  11030. }
  11031. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  11032. $seenLogSid = [];
  11033. foreach ($bundle['pos'] ?? [] as $poRow) {
  11034. if (!is_array($poRow)) {
  11035. continue;
  11036. }
  11037. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11038. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  11039. continue;
  11040. }
  11041. $seenLogSid[$sid] = true;
  11042. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11043. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11044. }
  11045. if ($seenLogSid === []) {
  11046. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  11047. if ($this->isValidScydgyRowId($logSid)) {
  11048. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  11049. }
  11050. }
  11051. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  11052. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  11053. }
  11054. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  11055. }
  11056. /**
  11057. * 开标双重验证 — 可选验证人列表
  11058. */
  11059. public function bidOpenUsers()
  11060. {
  11061. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11062. $this->error('无权限');
  11063. }
  11064. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  11065. if ($scydgyId !== '') {
  11066. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11067. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11068. $this->success('已完成开标验证', null, [
  11069. 'verified' => 1,
  11070. 'users' => [],
  11071. ]);
  11072. }
  11073. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11074. $this->error('本单已指定供应商,无需再开标');
  11075. }
  11076. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11077. }
  11078. $this->success('', null, [
  11079. 'verified' => 0,
  11080. 'users' => $this->listBidOpenVerifierCandidates(),
  11081. ]);
  11082. }
  11083. /**
  11084. * 开标双重验证 — 向指定管理员发送短信验证码
  11085. */
  11086. public function bidOpenSendCode()
  11087. {
  11088. if (!$this->request->isPost()) {
  11089. $this->error(__('Invalid parameters'));
  11090. }
  11091. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11092. $this->error('无权限');
  11093. }
  11094. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11095. $adminId = (int)$this->request->post('admin_id', 0);
  11096. if ($scydgyId === '' || $adminId <= 0) {
  11097. $this->error('参数无效');
  11098. }
  11099. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11100. if ($bundle['pos'] === []) {
  11101. $this->error('该订单不在待确认供应商状态');
  11102. }
  11103. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11104. $this->success('已完成开标验证,无需重复发送');
  11105. }
  11106. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11107. $this->error('本单已指定供应商,无需再开标');
  11108. }
  11109. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11110. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11111. if ($ccydh === '') {
  11112. $this->error('订单号无效');
  11113. }
  11114. $admin = $this->loadBidOpenAdminUser($adminId);
  11115. if ($admin === null) {
  11116. $this->error('验证人无效或未绑定手机号');
  11117. }
  11118. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  11119. $cd = max(30, min(120, $cd));
  11120. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  11121. $this->error('发送过于频繁,请稍后再试');
  11122. }
  11123. $code = (string)random_int(100000, 999999);
  11124. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  11125. $ttl = max(60, min(600, $ttl));
  11126. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  11127. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  11128. try {
  11129. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  11130. } catch (\Throwable $e) {
  11131. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  11132. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  11133. $this->error($e->getMessage());
  11134. }
  11135. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  11136. }
  11137. /**
  11138. * 开标双重验证 — 两人验证码校验并记录
  11139. */
  11140. public function bidOpenVerify()
  11141. {
  11142. if (!$this->request->isPost()) {
  11143. $this->error(__('Invalid parameters'));
  11144. }
  11145. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11146. $this->error('无权限');
  11147. }
  11148. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11149. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  11150. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  11151. $code1 = trim((string)$this->request->post('code1', ''));
  11152. $code2 = trim((string)$this->request->post('code2', ''));
  11153. if ($scydgyId === '') {
  11154. $this->error('参数无效');
  11155. }
  11156. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  11157. $this->error('请选择两位验证人');
  11158. }
  11159. if ($verifier1Id === $verifier2Id) {
  11160. $this->error('两位验证人不能相同');
  11161. }
  11162. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  11163. $this->error('请输入6位短信验证码');
  11164. }
  11165. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11166. if ($bundle['pos'] === []) {
  11167. $this->error('该订单不在待确认供应商状态');
  11168. }
  11169. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11170. if ($ccydh === '') {
  11171. $this->error('订单号无效');
  11172. }
  11173. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11174. $this->success('已完成开标验证');
  11175. }
  11176. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11177. $this->error('本单已指定供应商,无需再开标');
  11178. }
  11179. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11180. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  11181. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  11182. if ($verifier1 === null || $verifier2 === null) {
  11183. $this->error('验证人无效或未绑定手机号');
  11184. }
  11185. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  11186. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  11187. }
  11188. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  11189. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  11190. }
  11191. try {
  11192. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  11193. } catch (\Throwable $e) {
  11194. $this->error($e->getMessage());
  11195. }
  11196. $this->success('开标验证成功,可查看供应商报价与交货日期');
  11197. }
  11198. /**
  11199. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  11200. */
  11201. public function auditManualPick()
  11202. {
  11203. if (!$this->request->isPost()) {
  11204. $this->error(__('Invalid parameters'));
  11205. }
  11206. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  11207. $this->error('无权限');
  11208. }
  11209. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11210. if ($scydgyId === '') {
  11211. $this->error('参数无效');
  11212. }
  11213. $companyName = trim((string)$this->request->post('selected_company', ''));
  11214. $reason = trim((string)$this->request->post('pick_reason', ''));
  11215. if ($companyName === '') {
  11216. $this->error('请选择一家供应商');
  11217. }
  11218. if ($reason === '') {
  11219. $this->error('请填写选择说明');
  11220. }
  11221. if (mb_strlen($reason) > 500) {
  11222. $this->error('选择说明不能超过500字');
  11223. }
  11224. $this->ensurePurchaseOrderManualPickColumns();
  11225. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11226. $pos = $bundle['pos'];
  11227. if ($pos === []) {
  11228. $this->error('该订单不在待确认供应商状态');
  11229. }
  11230. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11231. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  11232. }
  11233. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11234. if ($quoteGroups === []) {
  11235. $this->error('暂无供应商,请确认已完成协助初选通知');
  11236. }
  11237. $matched = null;
  11238. foreach ($quoteGroups as $g) {
  11239. if (!is_array($g)) {
  11240. continue;
  11241. }
  11242. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11243. $matched = $g;
  11244. break;
  11245. }
  11246. }
  11247. if ($matched === null) {
  11248. $this->error('所选供应商不在本单报价列表中');
  11249. }
  11250. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11251. Db::startTrans();
  11252. try {
  11253. foreach ($pos as $poRow) {
  11254. if (!is_array($poRow)) {
  11255. continue;
  11256. }
  11257. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11258. if (!$this->isValidScydgyRowId($sid)) {
  11259. continue;
  11260. }
  11261. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11262. 'pick_company_name' => $companyName,
  11263. 'manual_pick' => 1,
  11264. 'manual_pick_reason' => $reason,
  11265. ]);
  11266. }
  11267. Db::commit();
  11268. } catch (\Throwable $e) {
  11269. Db::rollback();
  11270. $this->error($e->getMessage());
  11271. }
  11272. foreach ($pos as $poRow) {
  11273. if (!is_array($poRow)) {
  11274. continue;
  11275. }
  11276. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11277. if (!$this->isValidScydgyRowId($sid)) {
  11278. continue;
  11279. }
  11280. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11281. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11282. }
  11283. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11284. try {
  11285. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11286. if ($ccydh !== '') {
  11287. // 重新加载以拿到未掩码报价参与计分
  11288. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11289. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11290. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11291. }
  11292. } catch (\Throwable $e) {
  11293. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11294. }
  11295. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11296. }
  11297. /**
  11298. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11299. */
  11300. public function auditSubmit()
  11301. {
  11302. if (!$this->request->isPost()) {
  11303. $this->error(__('Invalid parameters'));
  11304. }
  11305. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11306. if ($scydgyId === '') {
  11307. $this->error('参数无效');
  11308. }
  11309. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11310. $pos = $bundle['pos'];
  11311. $mergeRows = $bundle['merge_rows'];
  11312. if ($pos === [] || $mergeRows === []) {
  11313. $this->error('该订单不在待确认供应商状态');
  11314. }
  11315. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11316. if ($quoteGroups === []) {
  11317. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11318. }
  11319. $companyName = trim((string)$this->request->post('selected_company', ''));
  11320. if ($companyName === '') {
  11321. $this->error('请选择一家供应商');
  11322. }
  11323. $matched = null;
  11324. foreach ($quoteGroups as $g) {
  11325. if (!is_array($g)) {
  11326. continue;
  11327. }
  11328. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11329. $matched = $g;
  11330. break;
  11331. }
  11332. }
  11333. if ($matched === null) {
  11334. $this->error('所选供应商不在本单报价列表中');
  11335. }
  11336. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11337. if ($sysRqDb === '') {
  11338. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11339. } else {
  11340. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11341. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11342. }
  11343. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11344. $this->error('未到招标截止日期,暂不可确认');
  11345. }
  11346. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11347. && !$this->isProcuremenManualPickedForBundle($bundle)
  11348. ) {
  11349. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11350. }
  11351. $procCnt = count($mergeRows);
  11352. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11353. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11354. Db::startTrans();
  11355. try {
  11356. foreach ($pos as $poRow) {
  11357. if (!is_array($poRow)) {
  11358. continue;
  11359. }
  11360. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11361. if (!$this->isValidScydgyRowId($sid)) {
  11362. continue;
  11363. }
  11364. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11365. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11366. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11367. 'pick_company_name' => $companyName,
  11368. 'sys_rq' => $sysRqDb,
  11369. ]);
  11370. }
  11371. Db::commit();
  11372. } catch (\Throwable $e) {
  11373. Db::rollback();
  11374. $this->error($e->getMessage());
  11375. }
  11376. foreach ($pos as $poRow) {
  11377. if (!is_array($poRow)) {
  11378. continue;
  11379. }
  11380. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11381. if (!$this->isValidScydgyRowId($sid)) {
  11382. continue;
  11383. }
  11384. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11385. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11386. }
  11387. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11388. }
  11389. /**
  11390. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11391. */
  11392. public function auditResendSms()
  11393. {
  11394. if (!$this->request->isPost()) {
  11395. $this->error(__('Invalid parameters'));
  11396. }
  11397. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11398. if ($scydgyId === '') {
  11399. $this->error('参数无效');
  11400. }
  11401. $loaded = $this->loadAuditResendBundle($scydgyId);
  11402. $mergeRows = $loaded['merge_rows'];
  11403. $bundle = $loaded['bundle'];
  11404. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11405. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11406. if ($quoteGroups === []) {
  11407. $this->error('暂无可通知的供应商');
  11408. }
  11409. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11410. $companiesJson = (string)$this->request->post('companies_json', '');
  11411. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11412. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11413. }
  11414. /**
  11415. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11416. */
  11417. public function auditResendEmail()
  11418. {
  11419. if (!$this->request->isPost()) {
  11420. $this->error(__('Invalid parameters'));
  11421. }
  11422. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11423. if ($scydgyId === '') {
  11424. $this->error('参数无效');
  11425. }
  11426. $loaded = $this->loadAuditResendBundle($scydgyId);
  11427. $mergeRows = $loaded['merge_rows'];
  11428. $bundle = $loaded['bundle'];
  11429. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11430. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11431. if ($quoteGroups === []) {
  11432. $this->error('暂无可通知的供应商');
  11433. }
  11434. $companiesJson = (string)$this->request->post('companies_json', '');
  11435. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11436. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11437. if ($companiesJson === '' && $selectedCompany === '') {
  11438. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11439. }
  11440. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11441. }
  11442. /**
  11443. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11444. *
  11445. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11446. * @return array<int, true> 已处理的 scydgy_id 集合
  11447. */
  11448. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11449. {
  11450. $pos = $bundle['pos'] ?? [];
  11451. if (!is_array($pos) || $pos === []) {
  11452. return [];
  11453. }
  11454. $sids = [];
  11455. $poIdBySid = [];
  11456. foreach ($pos as $poRow) {
  11457. if (!is_array($poRow)) {
  11458. continue;
  11459. }
  11460. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11461. if ($this->isValidScydgyRowId($sid)) {
  11462. $sids[$sid] = true;
  11463. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11464. if ($poId > 0) {
  11465. $poIdBySid[$sid] = $poId;
  11466. }
  11467. }
  11468. }
  11469. if ($sids === []) {
  11470. return [];
  11471. }
  11472. $logMsg = '重新下发';
  11473. $suffix = trim((string)$logSuffix, ',, ');
  11474. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11475. $logMsg .= ':从历史存证退回协助初选';
  11476. } else {
  11477. $logMsg .= ':退回协助初选';
  11478. }
  11479. Db::table('purchase_order')
  11480. ->where('scydgy_id', 'in', array_keys($sids))
  11481. ->update([
  11482. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11483. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11484. 'pick_company_name' => '',
  11485. 'pick_time' => null,
  11486. 'sys_rq' => null,
  11487. 'mod_rq' => null,
  11488. ]);
  11489. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11490. foreach (array_keys($sids) as $sid) {
  11491. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11492. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11493. }
  11494. return $sids;
  11495. }
  11496. /**
  11497. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11498. *
  11499. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11500. */
  11501. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11502. {
  11503. $scydgyId = trim($scydgyId);
  11504. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11505. if ($scydgyId === '') {
  11506. return $empty;
  11507. }
  11508. try {
  11509. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11510. } catch (\Throwable $e) {
  11511. $anchor = null;
  11512. }
  11513. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11514. return $empty;
  11515. }
  11516. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11517. if ($ccydh === '') {
  11518. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11519. }
  11520. try {
  11521. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11522. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11523. $pos = $query->order('scydgy_id', 'asc')->select();
  11524. } catch (\Throwable $e) {
  11525. $pos = [$anchor];
  11526. }
  11527. if (!is_array($pos) || $pos === []) {
  11528. $pos = [$anchor];
  11529. }
  11530. return [
  11531. 'ccydh' => $ccydh,
  11532. 'pos' => $pos,
  11533. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11534. ];
  11535. }
  11536. protected function purchaseOrderRowIsCompleted(array $po): bool
  11537. {
  11538. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11539. }
  11540. /**
  11541. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11542. *
  11543. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11544. */
  11545. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11546. {
  11547. $scydgyId = trim($scydgyId);
  11548. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11549. if ($scydgyId === '') {
  11550. return $empty;
  11551. }
  11552. try {
  11553. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11554. } catch (\Throwable $e) {
  11555. $anchor = null;
  11556. }
  11557. if (!is_array($anchor)) {
  11558. return $empty;
  11559. }
  11560. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11561. if ($ccydh === '') {
  11562. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11563. }
  11564. try {
  11565. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11566. } catch (\Throwable $e) {
  11567. $pos = [$anchor];
  11568. }
  11569. if (!is_array($pos) || $pos === []) {
  11570. $pos = [$anchor];
  11571. }
  11572. return [
  11573. 'ccydh' => $ccydh,
  11574. 'pos' => $pos,
  11575. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11576. ];
  11577. }
  11578. /**
  11579. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11580. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11581. */
  11582. public function auditAbandon()
  11583. {
  11584. if (!$this->request->isPost()) {
  11585. $this->error(__('Invalid parameters'));
  11586. }
  11587. $anchorIds = [];
  11588. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11589. if ($batchRaw !== '') {
  11590. $decoded = json_decode($batchRaw, true);
  11591. if (is_array($decoded)) {
  11592. foreach ($decoded as $id) {
  11593. $s = trim((string)$id);
  11594. if ($s !== '') {
  11595. $anchorIds[] = $s;
  11596. }
  11597. }
  11598. }
  11599. }
  11600. if ($anchorIds === []) {
  11601. $single = trim((string)$this->request->post('scydgy_id', ''));
  11602. if ($single !== '') {
  11603. $anchorIds[] = $single;
  11604. }
  11605. }
  11606. if ($anchorIds === []) {
  11607. $this->error('请至少选择一条订单');
  11608. }
  11609. $processedCcydh = [];
  11610. $doneOrders = 0;
  11611. $allSids = [];
  11612. Db::startTrans();
  11613. try {
  11614. foreach ($anchorIds as $anchorId) {
  11615. $fromArchive = false;
  11616. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11617. if (($bundle['pos'] ?? []) === []) {
  11618. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11619. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11620. }
  11621. if (($bundle['pos'] ?? []) === []) {
  11622. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11623. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11624. }
  11625. if (($bundle['pos'] ?? []) === []) {
  11626. continue;
  11627. }
  11628. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11629. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11630. if (isset($processedCcydh[$dedupeKey])) {
  11631. continue;
  11632. }
  11633. $processedCcydh[$dedupeKey] = true;
  11634. $sids = $fromArchive
  11635. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11636. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11637. if ($sids === []) {
  11638. continue;
  11639. }
  11640. $doneOrders++;
  11641. foreach (array_keys($sids) as $sid) {
  11642. $allSids[(int)$sid] = true;
  11643. }
  11644. }
  11645. if ($doneOrders < 1) {
  11646. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11647. }
  11648. Db::commit();
  11649. } catch (\Throwable $e) {
  11650. Db::rollback();
  11651. $this->error($e->getMessage());
  11652. }
  11653. $this->pickHiddenScydgySetCache = null;
  11654. $msg = $doneOrders > 1
  11655. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11656. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11657. $this->success($msg);
  11658. }
  11659. /**
  11660. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11661. */
  11662. public function archiveAbandon()
  11663. {
  11664. return $this->auditAbandon();
  11665. }
  11666. /**
  11667. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11668. */
  11669. public function purchaseApprovalReject()
  11670. {
  11671. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11672. $this->error(__('Invalid parameters'));
  11673. }
  11674. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11675. $this->error(__('You have no permission'));
  11676. }
  11677. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11678. $decoded = json_decode($batchRaw, true);
  11679. if (!is_array($decoded) || $decoded === []) {
  11680. $this->error('提交数据无效');
  11681. }
  11682. $done = 0;
  11683. Db::startTrans();
  11684. try {
  11685. foreach ($decoded as $item) {
  11686. if (!is_array($item)) {
  11687. continue;
  11688. }
  11689. $sid = (int)($item['scydgy_id'] ?? 0);
  11690. if (!$this->isValidScydgyRowId($sid)) {
  11691. continue;
  11692. }
  11693. $this->runPurchaseApprovalRejectForSid($sid);
  11694. $done++;
  11695. }
  11696. if ($done < 1) {
  11697. throw new \Exception('所选订单均不在待审批状态');
  11698. }
  11699. Db::commit();
  11700. } catch (\Throwable $e) {
  11701. Db::rollback();
  11702. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11703. }
  11704. $this->pickHiddenScydgySetCache = null;
  11705. $this->success('已驳回并退回「协助审批下发」');
  11706. }
  11707. /**
  11708. * @throws \Exception
  11709. */
  11710. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11711. {
  11712. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11713. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11714. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11715. $allIds = $this->purchaseOrderDetail($sid);
  11716. if ($allIds === []) {
  11717. throw new \Exception('未找到下发明细');
  11718. }
  11719. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11720. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11721. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11722. 'pick_company_name' => '',
  11723. ]);
  11724. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11725. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11726. $poId = 0;
  11727. try {
  11728. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11729. if (is_array($po)) {
  11730. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11731. }
  11732. } catch (\Throwable $e) {
  11733. }
  11734. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11735. }
  11736. /**
  11737. * 审核弹窗(旧入口,POST 已关闭)
  11738. */
  11739. public function review()
  11740. {
  11741. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11742. $this->error(__('You have no permission'));
  11743. }
  11744. if ($this->request->isPost()) {
  11745. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11746. }
  11747. $this->view->assign('pickMode', 0);
  11748. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11749. }
  11750. /**
  11751. * 审核弹窗获取公司列表
  11752. */
  11753. public function reviewCompanies()
  11754. {
  11755. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11756. $this->error(__('You have no permission'));
  11757. }
  11758. if (!$this->request->isAjax()) {
  11759. $this->error(__('Invalid parameters'));
  11760. }
  11761. $list = [];
  11762. try {
  11763. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11764. $rows = Db::table('customer')
  11765. ->where(function ($q) {
  11766. $q->where('status', 1)
  11767. ->whereOr('status', '1')
  11768. ->whereOr('status', '')
  11769. ->whereNull('status');
  11770. })
  11771. ->order('id', 'desc')
  11772. ->select();
  11773. } catch (\Throwable $e) {
  11774. $this->success('', '', []);
  11775. return;
  11776. }
  11777. if (!is_array($rows)) {
  11778. $this->success('', '', []);
  11779. return;
  11780. }
  11781. $detailColCandidates = [
  11782. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11783. 'company_detail', 'company_desc', 'address',
  11784. ];
  11785. foreach ($rows as $row) {
  11786. if (!is_array($row)) {
  11787. continue;
  11788. }
  11789. $norm = [];
  11790. foreach ($row as $k => $v) {
  11791. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11792. }
  11793. $row = $norm;
  11794. $st = $row['status'] ?? '';
  11795. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11796. continue;
  11797. }
  11798. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11799. if ($payload === null) {
  11800. continue;
  11801. }
  11802. $detail = '';
  11803. foreach ($detailColCandidates as $dk) {
  11804. if (!isset($row[$dk])) {
  11805. continue;
  11806. }
  11807. $dv = trim((string)$row[$dk]);
  11808. if ($dv !== '') {
  11809. $detail = $dv;
  11810. break;
  11811. }
  11812. }
  11813. $payload['detail'] = $detail;
  11814. $list[] = $this->maskSupplierContactFields($payload);
  11815. }
  11816. $this->success('', '', $list);
  11817. }
  11818. /**
  11819. * 采购确认-下发明细弹窗:
  11820. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11821. */
  11822. public function outward_detail()
  11823. {
  11824. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11825. if (is_array($ids)) {
  11826. $ids = isset($ids[0]) ? $ids[0] : '';
  11827. }
  11828. $ids = trim((string)$ids);
  11829. if ($ids === '') {
  11830. $this->error(__('Invalid parameters'));
  11831. }
  11832. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11833. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11834. $wffTab = 'all';
  11835. }
  11836. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11837. $purchaseOrderId = 0;
  11838. $po = null;
  11839. try {
  11840. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11841. if (is_array($po)) {
  11842. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11843. }
  11844. } catch (\Throwable $e) {
  11845. $purchaseOrderId = 0;
  11846. $po = null;
  11847. }
  11848. if (!$isPurchaseConfirm && is_array($po)) {
  11849. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11850. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11851. $isPurchaseConfirm = true;
  11852. }
  11853. }
  11854. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11855. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11856. $confirmProcessCount = 1;
  11857. $confirmPickGroups = [];
  11858. $processDisplayRows = [];
  11859. $allDetailsBySid = [];
  11860. $requiredSidList = [];
  11861. $sidList = [$ids];
  11862. if ($isPurchaseConfirm) {
  11863. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11864. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11865. if ($mergeRows !== []) {
  11866. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11867. }
  11868. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11869. if ($confirmBundle['pos'] !== []) {
  11870. $sidList = [];
  11871. foreach ($confirmBundle['pos'] as $poRow) {
  11872. if (!is_array($poRow)) {
  11873. continue;
  11874. }
  11875. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11876. if (!$this->isValidScydgyRowId($sid)) {
  11877. continue;
  11878. }
  11879. $sidList[] = (string)$sid;
  11880. $requiredSidList[] = $sid;
  11881. }
  11882. }
  11883. if ($sidList === []) {
  11884. $sidList = [$ids];
  11885. $requiredSidList = [(int)$ids];
  11886. }
  11887. $confirmProcessCount = max(1, count($requiredSidList));
  11888. if (is_array($po) && $purchaseOrderId <= 0) {
  11889. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11890. }
  11891. }
  11892. $rows = [];
  11893. try {
  11894. if (count($sidList) === 1) {
  11895. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11896. } else {
  11897. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11898. }
  11899. } catch (\Throwable $e) {
  11900. $rows = [];
  11901. }
  11902. if ($isPurchaseConfirm) {
  11903. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11904. }
  11905. foreach ($rows as &$r) {
  11906. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11907. $r['id'] = $r['ID'];
  11908. }
  11909. if (isset($r['createtime'])) {
  11910. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11911. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11912. } else {
  11913. $r['createtime_text'] = (string)$r['createtime'];
  11914. }
  11915. } else {
  11916. $r['createtime_text'] = '';
  11917. }
  11918. if (is_array($r)) {
  11919. $r = $this->maskSupplierContactFields($r);
  11920. }
  11921. }
  11922. unset($r);
  11923. $pickedCompanyName = '';
  11924. $manualPicked = 0;
  11925. $manualPickReason = '';
  11926. $quoteVisible = 0;
  11927. $bidOpenVerified = 0;
  11928. if ($isPurchaseConfirm) {
  11929. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11930. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11931. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11932. }
  11933. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11934. $confirmBundle['pos'] = [$po];
  11935. }
  11936. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11937. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11938. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11939. if ($manualPickInfo['company'] !== '') {
  11940. $pickedCompanyName = $manualPickInfo['company'];
  11941. }
  11942. if ($pickedCompanyName === '') {
  11943. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11944. if (!is_array($poRow)) {
  11945. continue;
  11946. }
  11947. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11948. if ($pn !== '') {
  11949. $pickedCompanyName = $pn;
  11950. break;
  11951. }
  11952. }
  11953. }
  11954. // 再兜底:直接读当前主单字段
  11955. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11956. $manualPicked = 1;
  11957. if ($manualPickReason === '') {
  11958. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11959. }
  11960. if ($pickedCompanyName === '') {
  11961. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11962. }
  11963. }
  11964. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11965. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11966. }
  11967. $this->view->assign('rows', $rows ?: []);
  11968. $this->view->assign('rowCount', count($rows ?: []));
  11969. $this->view->assign('scydgyId', $ids);
  11970. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11971. $this->view->assign('headTitle', $headTitle);
  11972. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11973. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11974. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11975. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11976. $this->view->assign('processDisplayRows', $processDisplayRows);
  11977. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11978. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11979. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11980. $this->view->assign('manualPicked', $manualPicked);
  11981. $this->view->assign('manualPickReason', $manualPickReason);
  11982. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11983. $this->view->assign('quoteVisible', $quoteVisible);
  11984. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11985. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11986. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11987. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11988. $sysRqDisplay = '—';
  11989. if ($isPurchaseConfirm) {
  11990. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11991. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11992. );
  11993. }
  11994. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11995. $this->view->assign('sysRq', $isPurchaseConfirm
  11996. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11997. : '');
  11998. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11999. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  12000. : '');
  12001. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  12002. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  12003. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  12004. if ($isPurchaseConfirm) {
  12005. return $this->view->fetch();
  12006. }
  12007. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12008. $this->view->engine->layout(false);
  12009. try {
  12010. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  12011. $this->view->assign('dialogBody', $bodyHtml);
  12012. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  12013. } finally {
  12014. if ($restoreLayout) {
  12015. $this->view->engine->layout($restoreLayout);
  12016. }
  12017. }
  12018. }
  12019. /**
  12020. * 月度导出记录表(不存在时自动创建)
  12021. */
  12022. protected function ensurePurchaseMonthExportLogTable(): void
  12023. {
  12024. try {
  12025. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  12026. } catch (\Throwable $e) {
  12027. Db::execute(
  12028. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  12029. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  12030. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  12031. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  12032. `admin_name` varchar(64) NOT NULL DEFAULT '',
  12033. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  12034. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  12035. `createtime` int(10) unsigned DEFAULT NULL,
  12036. PRIMARY KEY (`id`),
  12037. KEY `idx_ym` (`ym`),
  12038. KEY `idx_ct` (`createtime`)
  12039. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  12040. );
  12041. }
  12042. }
  12043. /**
  12044. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  12045. *
  12046. * @param array<int, mixed> $dbRows
  12047. * @return array<int, array<string, mixed>>
  12048. */
  12049. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  12050. {
  12051. $keyword = trim((string)$this->request->get('search', ''));
  12052. if ($keyword === '') {
  12053. $keyword = trim((string)$this->request->request('search', ''));
  12054. }
  12055. $filter = $this->request->get('filter', '');
  12056. $op = $this->request->get('op', '');
  12057. if (is_string($filter) && $filter !== '') {
  12058. $filterArr = (array)json_decode($filter, true);
  12059. } else {
  12060. $filterArr = is_array($filter) ? $filter : [];
  12061. }
  12062. if (is_string($op) && $op !== '') {
  12063. $opArr = (array)json_decode($op, true);
  12064. } else {
  12065. $opArr = is_array($op) ? $op : [];
  12066. }
  12067. if ($keyword === '' && $filterArr === []) {
  12068. return array_values(array_filter($dbRows, 'is_array'));
  12069. }
  12070. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  12071. $out = [];
  12072. foreach ($dbRows as $row) {
  12073. if (!is_array($row)) {
  12074. continue;
  12075. }
  12076. if ($keyword !== '') {
  12077. $hit = false;
  12078. foreach ($searchFields as $f) {
  12079. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  12080. $hit = true;
  12081. break;
  12082. }
  12083. }
  12084. if (!$hit) {
  12085. continue;
  12086. }
  12087. }
  12088. $passFilter = true;
  12089. foreach ($filterArr as $field => $val) {
  12090. $field = (string)$field;
  12091. $val = trim((string)$val);
  12092. if ($field === '' || $val === '') {
  12093. continue;
  12094. }
  12095. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  12096. continue;
  12097. }
  12098. $cell = (string)($row[$field] ?? '');
  12099. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  12100. if ($mode === '=' || $mode === 'EQUAL') {
  12101. if (strcasecmp($cell, $val) !== 0) {
  12102. $passFilter = false;
  12103. break;
  12104. }
  12105. } elseif (mb_stripos($cell, $val) === false) {
  12106. $passFilter = false;
  12107. break;
  12108. }
  12109. }
  12110. if (!$passFilter) {
  12111. continue;
  12112. }
  12113. $out[] = $row;
  12114. }
  12115. return $out;
  12116. }
  12117. /**
  12118. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  12119. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  12120. */
  12121. public function export_month_outward()
  12122. {
  12123. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  12124. $this->error(__('You have no permission'));
  12125. }
  12126. $bundle = $this->prepareMonthOutwardExportBundle();
  12127. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12128. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  12129. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  12130. $spreadsheet = new Spreadsheet();
  12131. $sheet = $spreadsheet->getActiveSheet();
  12132. $sheet->setTitle('外协加工明细');
  12133. $mon = (int)substr($ym, 5, 2);
  12134. $sheet->mergeCells('A1:H1');
  12135. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  12136. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  12137. $sheet->getStyle('A1')->getAlignment()
  12138. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12139. ->setVertical(Alignment::VERTICAL_CENTER);
  12140. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  12141. $col = 'A';
  12142. foreach ($headers as $h) {
  12143. $sheet->setCellValue($col . '2', $h);
  12144. $col++;
  12145. }
  12146. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  12147. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12148. $rowNum = 3;
  12149. $sumSubtotalCounts = 0;
  12150. $grandAmount = 0.0;
  12151. $globalSeq = 0;
  12152. if ($groups === []) {
  12153. $sheet->mergeCells('A3:H3');
  12154. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  12155. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12156. $rowNum = 4;
  12157. } else {
  12158. foreach ($groups as $items) {
  12159. if ($items === []) {
  12160. continue;
  12161. }
  12162. $groupLineCount = count($items);
  12163. $subAmount = 0.0;
  12164. foreach ($items as $line) {
  12165. $globalSeq++;
  12166. $dr = $line['detail'];
  12167. $amt = $this->procuremenExportAmount($dr);
  12168. $subAmount += $amt;
  12169. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  12170. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  12171. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  12172. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  12173. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  12174. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  12175. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  12176. $sheet->setCellValue('H' . $rowNum, $amt);
  12177. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  12178. $rowNum++;
  12179. }
  12180. $sumSubtotalCounts += $groupLineCount;
  12181. $grandAmount += $subAmount;
  12182. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12183. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  12184. $sheet->getStyle('G' . $rowNum)->getAlignment()
  12185. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12186. ->setVertical(Alignment::VERTICAL_CENTER);
  12187. $rowNum++;
  12188. }
  12189. }
  12190. $sheet->setCellValue('A' . $rowNum, '总计');
  12191. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  12192. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12193. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  12194. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12195. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  12196. $lastRow = $rowNum;
  12197. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  12198. 'borders' => [
  12199. 'allBorders' => [
  12200. 'borderStyle' => Border::BORDER_THIN,
  12201. 'color' => ['rgb' => '000000'],
  12202. ],
  12203. ],
  12204. ]);
  12205. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12206. if ($lastRow >= 3) {
  12207. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12208. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12209. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12210. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12211. }
  12212. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  12213. $sheet->getColumnDimension('A')->setWidth(7);
  12214. $sheet->getColumnDimension('B')->setWidth(16);
  12215. $sheet->getColumnDimension('C')->setWidth(52);
  12216. $sheet->getColumnDimension('D')->setWidth(32);
  12217. $sheet->getColumnDimension('E')->setWidth(12);
  12218. $sheet->getColumnDimension('F')->setWidth(44);
  12219. $sheet->getColumnDimension('G')->setWidth(26);
  12220. $sheet->getColumnDimension('H')->setWidth(13);
  12221. $sheet->getRowDimension(1)->setRowHeight(28);
  12222. $ymCompact = str_replace('-', '', $ym);
  12223. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  12224. $filename = $fileBase . '.xlsx';
  12225. try {
  12226. $this->ensurePurchaseMonthExportLogTable();
  12227. list($adminId, $adminName) = $this->GetUseName();
  12228. Db::table('purchase_month_export_log')->insert([
  12229. 'ym' => $ym,
  12230. 'admin_id' => (int)$adminId,
  12231. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  12232. 'row_count' => count($exportLines),
  12233. 'total_amount' => round($grandAmount, 2),
  12234. 'createtime' => time(),
  12235. ]);
  12236. } catch (\Throwable $e) {
  12237. Log::write('month export log: ' . $e->getMessage(), 'error');
  12238. }
  12239. if (ob_get_length()) {
  12240. ob_end_clean();
  12241. }
  12242. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  12243. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12244. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12245. header('Cache-Control: max-age=0');
  12246. $writer = new Xlsx($spreadsheet);
  12247. $writer->save('php://output');
  12248. $spreadsheet->disconnectWorksheets();
  12249. unset($spreadsheet);
  12250. exit;
  12251. }
  12252. /**
  12253. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12254. */
  12255. public function export_month_quote()
  12256. {
  12257. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12258. $this->error(__('You have no permission'));
  12259. }
  12260. $bundle = $this->prepareMonthOutwardExportBundle();
  12261. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12262. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12263. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12264. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12265. $spreadsheet = new Spreadsheet();
  12266. $sheet = $spreadsheet->getActiveSheet();
  12267. $sheet->setTitle('供应商报价明细');
  12268. $mon = (int)substr($ym, 5, 2);
  12269. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12270. $sheet->getColumnDimension('A')->setWidth(7);
  12271. $sheet->getColumnDimension('B')->setWidth(16);
  12272. $sheet->getColumnDimension('C')->setWidth(52);
  12273. $sheet->getColumnDimension('D')->setWidth(26);
  12274. $sheet->getColumnDimension('E')->setWidth(32);
  12275. $sheet->getColumnDimension('F')->setWidth(12);
  12276. $sheet->getColumnDimension('G')->setWidth(14);
  12277. $sheet->getColumnDimension('H')->setWidth(12);
  12278. if ($quoteLastRow < 1) {
  12279. $quoteLastRow = 3;
  12280. }
  12281. $ymCompact = str_replace('-', '', $ym);
  12282. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12283. if (ob_get_length()) {
  12284. ob_end_clean();
  12285. }
  12286. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12287. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12288. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12289. header('Cache-Control: max-age=0');
  12290. $writer = new Xlsx($spreadsheet);
  12291. $writer->save('php://output');
  12292. $spreadsheet->disconnectWorksheets();
  12293. unset($spreadsheet);
  12294. exit;
  12295. }
  12296. /**
  12297. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12298. *
  12299. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12300. */
  12301. protected function prepareMonthOutwardExportBundle(): array
  12302. {
  12303. $this->request->filter(['strip_tags', 'trim']);
  12304. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12305. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12306. $ym = date('Y-m');
  12307. }
  12308. $dbRows = [];
  12309. try {
  12310. $query = Db::table('purchase_order');
  12311. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12312. $dbRows = $query->select();
  12313. } catch (\Throwable $e) {
  12314. $dbRows = [];
  12315. }
  12316. if (!is_array($dbRows)) {
  12317. $dbRows = [];
  12318. }
  12319. $completeTsMap = [];
  12320. $sidList = [];
  12321. foreach ($dbRows as $dbRow) {
  12322. if (!is_array($dbRow)) {
  12323. continue;
  12324. }
  12325. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12326. if ($sid > 0) {
  12327. $sidList[$sid] = true;
  12328. }
  12329. }
  12330. if ($sidList !== []) {
  12331. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12332. }
  12333. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12334. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12335. if (!is_array($dbRow)) {
  12336. return false;
  12337. }
  12338. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12339. if ($done['ts'] <= 0) {
  12340. return false;
  12341. }
  12342. return date('Y-m', $done['ts']) === $ym;
  12343. }));
  12344. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12345. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12346. $mainBySid = [];
  12347. foreach ($pool as $rw) {
  12348. if (!is_array($rw)) {
  12349. continue;
  12350. }
  12351. $rid = (int)($rw['ID'] ?? 0);
  12352. if ($rid > 0) {
  12353. $mainBySid[$rid] = $rw;
  12354. }
  12355. }
  12356. if ($mainBySid === []) {
  12357. $detailRows = [];
  12358. } else {
  12359. try {
  12360. $detailRows = Db::table('purchase_order_detail')
  12361. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12362. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12363. ->order('status', 'desc')
  12364. ->order('CCYDH', 'asc')
  12365. ->order('company_name', 'asc')
  12366. ->order('id', 'asc')
  12367. ->select();
  12368. } catch (\Throwable $e) {
  12369. try {
  12370. $detailRows = Db::table('purchase_order_detail')
  12371. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12372. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12373. ->order('status', 'desc')
  12374. ->order('CCYDH', 'asc')
  12375. ->order('company_name', 'asc')
  12376. ->order('ID', 'asc')
  12377. ->select();
  12378. } catch (\Throwable $e2) {
  12379. $detailRows = [];
  12380. }
  12381. }
  12382. }
  12383. if (!is_array($detailRows)) {
  12384. $detailRows = [];
  12385. }
  12386. $exportLines = [];
  12387. $detailSidSeen = [];
  12388. foreach ($detailRows as $dr) {
  12389. if (!is_array($dr)) {
  12390. continue;
  12391. }
  12392. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12393. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12394. continue;
  12395. }
  12396. if (isset($detailSidSeen[$sid])) {
  12397. continue;
  12398. }
  12399. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12400. continue;
  12401. }
  12402. $detailSidSeen[$sid] = true;
  12403. $m = $mainBySid[$sid];
  12404. $exportLines[] = [
  12405. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12406. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12407. 'company_name' => (string)($dr['company_name'] ?? ''),
  12408. 'CDF' => (string)($m['CDF'] ?? ''),
  12409. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12410. 'gx' => $this->procuremenExportGxText($m),
  12411. 'detail' => $dr,
  12412. ];
  12413. }
  12414. foreach ($detailRows as $dr) {
  12415. if (!is_array($dr)) {
  12416. continue;
  12417. }
  12418. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12419. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12420. continue;
  12421. }
  12422. $detailSidSeen[$sid] = true;
  12423. $m = $mainBySid[$sid];
  12424. $exportLines[] = [
  12425. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12426. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12427. 'company_name' => (string)($dr['company_name'] ?? ''),
  12428. 'CDF' => (string)($m['CDF'] ?? ''),
  12429. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12430. 'gx' => $this->procuremenExportGxText($m),
  12431. 'detail' => $dr,
  12432. ];
  12433. }
  12434. foreach ($mainBySid as $sid => $m) {
  12435. if (isset($detailSidSeen[$sid])) {
  12436. continue;
  12437. }
  12438. $company = trim((string)($m['pick_company_name'] ?? ''));
  12439. $exportLines[] = [
  12440. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12441. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12442. 'company_name' => $company,
  12443. 'CDF' => (string)($m['CDF'] ?? ''),
  12444. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12445. 'gx' => $this->procuremenExportGxText($m),
  12446. 'detail' => [],
  12447. ];
  12448. }
  12449. $groups = [];
  12450. foreach ($exportLines as $line) {
  12451. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12452. if (!isset($groups[$k])) {
  12453. $groups[$k] = [];
  12454. }
  12455. $groups[$k][] = $line;
  12456. }
  12457. ksort($groups, SORT_STRING);
  12458. return [
  12459. 'ym' => $ym,
  12460. 'mainBySid' => $mainBySid,
  12461. 'detailRows' => $detailRows,
  12462. 'exportLines' => $exportLines,
  12463. 'groups' => $groups,
  12464. ];
  12465. }
  12466. /**
  12467. * 导出用:工序列文案
  12468. */
  12469. protected function procuremenExportGxText(array $r)
  12470. {
  12471. $a = trim((string)($r['CDXMC'] ?? ''));
  12472. $b = trim((string)($r['CGYMC'] ?? ''));
  12473. if ($a !== '' && $b !== '') {
  12474. return $a . ':' . $b;
  12475. }
  12476. return $a !== '' ? $a : $b;
  12477. }
  12478. /**
  12479. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12480. */
  12481. protected function procuremenExportAmount(array $r)
  12482. {
  12483. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12484. if (!array_key_exists($k, $r)) {
  12485. continue;
  12486. }
  12487. $v = $r[$k];
  12488. if ($v === null || $v === '') {
  12489. continue;
  12490. }
  12491. if (is_numeric($v)) {
  12492. return (float)$v;
  12493. }
  12494. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12495. if ($v !== '' && is_numeric($v)) {
  12496. return (float)$v;
  12497. }
  12498. }
  12499. return 0.0;
  12500. }
  12501. /**
  12502. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12503. *
  12504. * @param array<int, array<string, mixed>> $detailRows
  12505. * @param array<int, array<string, mixed>> $mainBySid
  12506. * @return array<int, array<string, mixed>>
  12507. */
  12508. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12509. {
  12510. $lines = [];
  12511. foreach ($detailRows as $dr) {
  12512. if (!is_array($dr)) {
  12513. continue;
  12514. }
  12515. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12516. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12517. continue;
  12518. }
  12519. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12520. continue;
  12521. }
  12522. $cn = trim((string)($dr['company_name'] ?? ''));
  12523. if ($cn === '') {
  12524. continue;
  12525. }
  12526. $m = $mainBySid[$sid];
  12527. $am = trim((string)($dr['amount'] ?? ''));
  12528. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12529. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12530. $amountText = $amountFilled
  12531. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12532. : '未填写';
  12533. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12534. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12535. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12536. $deliveryShow = $deliveryRaw;
  12537. }
  12538. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12539. ? $deliveryShow
  12540. : '未填写';
  12541. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12542. $lines[] = [
  12543. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12544. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12545. 'gx' => $this->procuremenExportGxText($m),
  12546. 'company_name' => $cn,
  12547. 'amount_text' => $amountText,
  12548. 'amount_num' => $amountFilled ? $amountNum : null,
  12549. 'delivery_text' => $deliveryText,
  12550. 'picked_text' => $picked ? '中标' : '未中标',
  12551. 'picked' => $picked,
  12552. ];
  12553. }
  12554. $winnerSupplierByOrder = [];
  12555. foreach ($lines as $line) {
  12556. $dh = trim((string)($line['CCYDH'] ?? ''));
  12557. $cn = trim((string)($line['company_name'] ?? ''));
  12558. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12559. $winnerSupplierByOrder[$dh][$cn] = true;
  12560. }
  12561. }
  12562. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12563. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12564. if ($c !== 0) {
  12565. return $c;
  12566. }
  12567. $dh = trim((string)($a['CCYDH'] ?? ''));
  12568. $aCn = trim((string)($a['company_name'] ?? ''));
  12569. $bCn = trim((string)($b['company_name'] ?? ''));
  12570. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12571. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12572. if ($aSupplierWin !== $bSupplierWin) {
  12573. return $aSupplierWin ? -1 : 1;
  12574. }
  12575. $c = strcmp($aCn, $bCn);
  12576. if ($c !== 0) {
  12577. return $c;
  12578. }
  12579. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12580. return !empty($a['picked']) ? -1 : 1;
  12581. }
  12582. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12583. if ($c !== 0) {
  12584. return $c;
  12585. }
  12586. return 0;
  12587. });
  12588. return $lines;
  12589. }
  12590. /**
  12591. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12592. *
  12593. * @param array<int, array<string, mixed>> $quoteLines
  12594. */
  12595. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12596. {
  12597. $mon = (int)substr($ym, 5, 2);
  12598. $titleRow = $startRow;
  12599. $headerRow = $startRow + 1;
  12600. $dataStartRow = $startRow + 2;
  12601. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12602. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12603. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12604. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12605. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12606. ->setVertical(Alignment::VERTICAL_CENTER);
  12607. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12608. $col = 'A';
  12609. foreach ($headers as $h) {
  12610. $sheet->setCellValue($col . $headerRow, $h);
  12611. $col++;
  12612. }
  12613. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12614. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12615. $rowNum = $dataStartRow;
  12616. if ($quoteLines === []) {
  12617. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12618. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12619. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12620. $rowNum = $dataStartRow + 1;
  12621. } else {
  12622. $i = 0;
  12623. foreach ($quoteLines as $line) {
  12624. $i++;
  12625. $sheet->setCellValue('A' . $rowNum, $i);
  12626. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12627. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12628. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12629. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12630. if ($line['amount_num'] !== null) {
  12631. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12632. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12633. } else {
  12634. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12635. }
  12636. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12637. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12638. if (!empty($line['picked'])) {
  12639. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12640. }
  12641. $rowNum++;
  12642. }
  12643. }
  12644. $lastRow = $rowNum - 1;
  12645. if ($lastRow >= $headerRow) {
  12646. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12647. 'borders' => [
  12648. 'allBorders' => [
  12649. 'borderStyle' => Border::BORDER_THIN,
  12650. 'color' => ['rgb' => '000000'],
  12651. ],
  12652. ],
  12653. ]);
  12654. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12655. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12656. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12657. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12658. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12659. if ($lastRow >= $dataStartRow) {
  12660. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12661. }
  12662. }
  12663. return $lastRow;
  12664. }
  12665. /**
  12666. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12667. */
  12668. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12669. {
  12670. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12671. return;
  12672. }
  12673. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12674. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12675. ->setVertical(Alignment::VERTICAL_CENTER);
  12676. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12677. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12678. ->setVertical(Alignment::VERTICAL_CENTER);
  12679. if ($lastCol > 'B') {
  12680. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12681. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12682. ->setVertical(Alignment::VERTICAL_CENTER);
  12683. }
  12684. }
  12685. /**
  12686. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12687. */
  12688. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12689. {
  12690. $s = trim($ccydh);
  12691. if ($s === '') {
  12692. return 'ORDER';
  12693. }
  12694. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12695. $s = trim($s, '._-');
  12696. if ($s === '') {
  12697. return 'ORDER';
  12698. }
  12699. if (function_exists('mb_substr')) {
  12700. return mb_substr($s, 0, 80, 'UTF-8');
  12701. }
  12702. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12703. }
  12704. /**
  12705. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12706. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12707. *
  12708. * @return array{objectKey: string, webPath: string}
  12709. */
  12710. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12711. {
  12712. $sid = (int)$scydgyId;
  12713. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12714. $y = date('Y');
  12715. $m = date('m');
  12716. $d = date('d');
  12717. $basename = $safeOrder . '_' . $sid . '.pdf';
  12718. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12719. return [
  12720. 'objectKey' => $objectKey,
  12721. 'webPath' => '/' . $objectKey,
  12722. ];
  12723. }
  12724. /**
  12725. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12726. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12727. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12728. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  12729. *
  12730. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12731. */
  12732. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12733. {
  12734. if (!$this->isValidScydgyRowId($scydgyId)) {
  12735. return '';
  12736. }
  12737. $ids = trim((string)$scydgyId);
  12738. $prep = $this->prepareProcuremenDetailsView($ids);
  12739. if (!$prep['ok']) {
  12740. return '';
  12741. }
  12742. $ccydh = $prep['ccydh'];
  12743. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12744. $objectKey = $paths['objectKey'];
  12745. $webPath = $paths['webPath'];
  12746. $cyjmc = '';
  12747. try {
  12748. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  12749. if (is_array($poMeta)) {
  12750. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  12751. }
  12752. } catch (\Throwable $e) {
  12753. $cyjmc = '';
  12754. }
  12755. $genTime = date('Y-m-d H:i:s');
  12756. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  12757. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  12758. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  12759. $pdfSteps = [];
  12760. $viewSteps = $prep['steps'] ?? [];
  12761. if (is_array($viewSteps)) {
  12762. foreach ($viewSteps as $st) {
  12763. if (!is_array($st)) {
  12764. continue;
  12765. }
  12766. if (trim((string)($st['title'] ?? '')) === '未发') {
  12767. continue;
  12768. }
  12769. $pdfSteps[] = $st;
  12770. }
  12771. }
  12772. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  12773. $nPdf = count($pdfSteps);
  12774. foreach ($pdfSteps as $idx => &$pst) {
  12775. if ($idx === 0) {
  12776. $pst['pdf_left_bg'] = '';
  12777. } else {
  12778. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  12779. }
  12780. if ($idx >= $nPdf - 1) {
  12781. $pst['pdf_right_bg'] = '';
  12782. } else {
  12783. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  12784. }
  12785. }
  12786. unset($pst);
  12787. $this->view->assign([
  12788. 'pdf_export' => 1,
  12789. 'pdfMetaLine' => $metaLeft,
  12790. 'pdfMetaLeft' => $metaLeft,
  12791. 'pdfMetaIds' => $metaIds,
  12792. 'pdfMetaTitle' => $cyjmc,
  12793. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  12794. 'pdfSteps' => $pdfSteps,
  12795. 'pdfStepWidth' => $pdfStepW,
  12796. ]);
  12797. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12798. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12799. $this->view->engine->layout(false);
  12800. try {
  12801. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12802. } catch (\Throwable $e) {
  12803. if ($restoreLayout) {
  12804. $this->view->engine->layout($restoreLayout);
  12805. }
  12806. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12807. $this->view->assign([
  12808. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  12809. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  12810. 'pdfSteps' => [], 'pdfStepWidth' => '',
  12811. ]);
  12812. return '';
  12813. }
  12814. if ($restoreLayout) {
  12815. $this->view->engine->layout($restoreLayout);
  12816. }
  12817. $this->view->assign([
  12818. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  12819. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  12820. 'pdfSteps' => [], 'pdfStepWidth' => '',
  12821. ]);
  12822. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12823. if (!is_dir($tempDir)) {
  12824. @mkdir($tempDir, 0755, true);
  12825. }
  12826. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12827. try {
  12828. $mpdf = new \Mpdf\Mpdf([
  12829. 'mode' => 'utf-8',
  12830. 'format' => 'A4',
  12831. 'margin_left' => 12,
  12832. 'margin_right' => 12,
  12833. 'margin_top' => 14,
  12834. 'margin_bottom' => 14,
  12835. 'tempDir' => $tempDir,
  12836. 'autoScriptToLang' => true,
  12837. 'autoLangToFont' => true,
  12838. ]);
  12839. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12840. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12841. $mpdf->SetBasePath('http://127.0.0.1/');
  12842. $mpdf->WriteHTML($html);
  12843. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12844. } catch (\Throwable $e) {
  12845. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12846. if (is_file($tempPdf)) {
  12847. @unlink($tempPdf);
  12848. }
  12849. return '';
  12850. }
  12851. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12852. if ($ossUrl !== '') {
  12853. @unlink($tempPdf);
  12854. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12855. return $ossUrl;
  12856. }
  12857. $pi = pathinfo($objectKey);
  12858. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12859. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12860. if ($baseFile === '') {
  12861. @unlink($tempPdf);
  12862. return '';
  12863. }
  12864. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12865. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12866. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12867. @unlink($tempPdf);
  12868. return '';
  12869. }
  12870. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12871. if (!@copy($tempPdf, $fullPath)) {
  12872. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12873. @unlink($tempPdf);
  12874. return '';
  12875. }
  12876. @unlink($tempPdf);
  12877. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12878. return $webPath;
  12879. }
  12880. /**
  12881. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12882. */
  12883. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12884. {
  12885. if ($scydgyId <= 0 || $webPath === '') {
  12886. return;
  12887. }
  12888. try {
  12889. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12890. } catch (\Throwable $e) {
  12891. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12892. }
  12893. }
  12894. /**
  12895. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12896. *
  12897. * @param array<string, string> $vars
  12898. * @return array<string, string>
  12899. */
  12900. protected function normalizeSmsTemplateVars(array $vars): array
  12901. {
  12902. $out = [];
  12903. foreach ($vars as $k => $v) {
  12904. $out[(string)$k] = trim((string)$v);
  12905. }
  12906. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12907. $out['contact_name'] = $out['company_name'];
  12908. }
  12909. return $out;
  12910. }
  12911. /**
  12912. * 按手机号或公司名称查 customer 表联系人姓名
  12913. */
  12914. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12915. {
  12916. $phone = trim($phone);
  12917. $companyName = trim($companyName);
  12918. try {
  12919. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12920. $row = Db::table('customer')
  12921. ->where(function ($q) use ($phone) {
  12922. $q->where('phone', $phone)->whereOr('account', $phone);
  12923. })
  12924. ->order('id', 'asc')
  12925. ->find();
  12926. if (is_array($row)) {
  12927. $nm = trim((string)($row['username'] ?? ''));
  12928. if ($nm !== '') {
  12929. return $nm;
  12930. }
  12931. }
  12932. }
  12933. if ($companyName !== '') {
  12934. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12935. if (is_array($row)) {
  12936. return trim((string)($row['username'] ?? ''));
  12937. }
  12938. }
  12939. } catch (\Throwable $e) {
  12940. }
  12941. return '';
  12942. }
  12943. /**
  12944. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  12945. */
  12946. protected function plainTextToHtmlEmailBody(string $text): string
  12947. {
  12948. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12949. $parts = explode("\n", $text);
  12950. $out = [];
  12951. foreach ($parts as $line) {
  12952. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12953. $out[] = $line;
  12954. } else {
  12955. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12956. $esc = preg_replace(
  12957. '#(https?://[^\s<>"\']+)#iu',
  12958. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  12959. $esc
  12960. );
  12961. $out[] = $esc;
  12962. }
  12963. }
  12964. return implode("<br>\n", $out);
  12965. }
  12966. /**
  12967. * 短信场景:去掉链接类变量,避免误填 URL
  12968. *
  12969. * @param array<string, string> $vars
  12970. * @return array<string, string>
  12971. */
  12972. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12973. {
  12974. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12975. return $vars;
  12976. }
  12977. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12978. $vars[$k] = '';
  12979. }
  12980. return $vars;
  12981. }
  12982. /**
  12983. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12984. *
  12985. * @param array<string, string> $vars
  12986. */
  12987. protected function renderNotifyTemplate(string $scene, array $vars): string
  12988. {
  12989. $vars = $this->normalizeSmsTemplateVars($vars);
  12990. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12991. $row = $this->loadNotifyTemplateRow($scene);
  12992. if ($row === null) {
  12993. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12994. }
  12995. $tpl = trim((string)($row['content'] ?? ''));
  12996. if ($tpl === '') {
  12997. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12998. }
  12999. foreach ($vars as $k => $v) {
  13000. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  13001. }
  13002. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  13003. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  13004. return $tpl;
  13005. }
  13006. protected function resolveProcuremenEmailSubject(string $scene): string
  13007. {
  13008. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  13009. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  13010. $row = $this->loadNotifyTemplateRow($scene);
  13011. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  13012. if ($title !== '') {
  13013. return $title;
  13014. }
  13015. $fallback = [
  13016. 'rfq_supplier_email' => '供应商询价通知',
  13017. 'rfq_salesman_email' => '协助采购询价通知',
  13018. 'confirm_ok_email' => '采购确认结果:已通过',
  13019. 'confirm_fail_email' => '采购确认结果:未通过',
  13020. ];
  13021. return $fallback[$scene] ?? '协助采购通知';
  13022. }
  13023. $map = [
  13024. 'review_email' => '您有新的协助加工订单',
  13025. ];
  13026. $subject = trim((string)($map[$scene] ?? ''));
  13027. if ($subject === '') {
  13028. $this->error('未配置邮件主题:' . $scene);
  13029. }
  13030. return $subject;
  13031. }
  13032. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  13033. {
  13034. $map = [
  13035. 'review_email' => '协助下发-邮箱',
  13036. 'review_sms' => '协助下发-短信',
  13037. 'confirm_ok' => '采购确认-通过',
  13038. 'confirm_fail' => '采购确认-未通过',
  13039. 'confirm_ok_email' => '采购确认通过-邮箱',
  13040. 'confirm_fail_email' => '采购确认未通过-邮箱',
  13041. 'bid_open' => '开标双重验证',
  13042. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  13043. 'rfq_supplier_email' => '供应商询价通知',
  13044. ];
  13045. $label = $map[$scene] ?? $scene;
  13046. if ($titleRequired) {
  13047. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  13048. }
  13049. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  13050. }
  13051. /**
  13052. * 是否开启协助通知演练(不发真实短信/邮件)
  13053. */
  13054. protected function isProcuremenNotifyDryRun(): bool
  13055. {
  13056. return (bool)Config::get('procuremen_notify_dry_run');
  13057. }
  13058. /**
  13059. * @param array<string, mixed> $payload
  13060. */
  13061. protected function recordNotifyDryRunPreview(array $payload): void
  13062. {
  13063. $this->notifyDryRunPreview[] = $payload;
  13064. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  13065. }
  13066. /**
  13067. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  13068. * @throws \Exception
  13069. */
  13070. protected function smsbao($phone, $content)
  13071. {
  13072. if ($this->isProcuremenNotifyDryRun()) {
  13073. $this->recordNotifyDryRunPreview([
  13074. 'scene' => 'sms_only',
  13075. 'phone' => $phone,
  13076. 'sms_content' => $content,
  13077. ]);
  13078. return;
  13079. }
  13080. $statusStr = [
  13081. '0' => '短信发送成功',
  13082. '-1' => '参数不全',
  13083. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  13084. '30' => '密码错误',
  13085. '40' => '账号不存在',
  13086. '41' => '余额不足',
  13087. '42' => '帐户已过期',
  13088. '43' => 'IP地址限制',
  13089. '50' => '内容含有敏感词',
  13090. ];
  13091. $smsapi = 'http://api.smsbao.com/';
  13092. $user = 'zhuwei123';
  13093. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  13094. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  13095. $result = @file_get_contents($sendurl);
  13096. if ($result === false) {
  13097. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  13098. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  13099. }
  13100. $result = trim((string)$result);
  13101. if ($result !== '0') {
  13102. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  13103. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  13104. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  13105. }
  13106. }
  13107. }