Procuremen.php 518 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692
  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. *
  263. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  264. */
  265. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  266. {
  267. static $mprocCfgLoaded = false;
  268. if (!$mprocCfgLoaded) {
  269. $mprocCfgLoaded = true;
  270. if (is_file(APP_PATH . 'extra/mproc.php')) {
  271. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  272. }
  273. }
  274. $eid = (int)$purchaseOrderDetailId;
  275. $base = $this->resolveMprocMobilePublicBaseUrl();
  276. if ($base === '') {
  277. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  278. }
  279. $path = trim((string)Config::get('mproc.mobile_index_path'));
  280. if ($path === '') {
  281. $path = '/index.php/index/index/index';
  282. } else {
  283. $path = '/' . ltrim($path, '/');
  284. }
  285. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  286. if ($eid > 0) {
  287. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  288. }
  289. return $base . $path . '?main_tab=orders';
  290. }
  291. /**
  292. * 邮件/短信外链:须为带点的公网域名
  293. */
  294. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  295. {
  296. $u = trim((string)$baseUrl);
  297. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  298. return false;
  299. }
  300. $host = parse_url($u, PHP_URL_HOST);
  301. if (!is_string($host) || $host === '') {
  302. return false;
  303. }
  304. if (strcasecmp($host, 'localhost') === 0) {
  305. return false;
  306. }
  307. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  308. return false;
  309. }
  310. if (strpos($host, '.') === false) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. /**
  316. * 解析用于协助邮件/短信的手机端站点根
  317. */
  318. protected function resolveMprocMobilePublicBaseUrl()
  319. {
  320. $candidates = [];
  321. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  322. $candidates[] = trim((string)Config::get('site.indexurl'));
  323. $cdn = trim((string)Config::get('site.cdnurl'));
  324. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  325. $candidates[] = rtrim($cdn, '/');
  326. }
  327. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  328. $candidates[] = $reqBase;
  329. foreach ($candidates as $c) {
  330. if ($c === '') {
  331. continue;
  332. }
  333. $c = rtrim($c, '/');
  334. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  335. return $c;
  336. }
  337. }
  338. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  339. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  340. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  341. return $reqBase;
  342. }
  343. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  344. return '';
  345. }
  346. /**
  347. * 获取 Redis 中 procuremen_redis
  348. */
  349. protected function ProcuremenRedis(): array
  350. {
  351. if ($this->procuremenRedisCache !== null) {
  352. return $this->procuremenRedisCache;
  353. }
  354. try {
  355. $redis = redis();
  356. $raw = $redis->get('procuremen_redis');
  357. if ($raw === false || $raw === '') {
  358. $this->procuremenRedisCache = [];
  359. return $this->procuremenRedisCache;
  360. }
  361. $decoded = json_decode($raw, true);
  362. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  363. $this->procuremenRedisCache = [];
  364. return $this->procuremenRedisCache;
  365. }
  366. $this->procuremenRedisCache = $decoded['data'];
  367. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  368. if ($this->loadProcuremenSidebarYmList() === []) {
  369. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  370. }
  371. return $this->procuremenRedisCache;
  372. } catch (\Throwable $e) {
  373. $this->procuremenRedisCache = [];
  374. return $this->procuremenRedisCache;
  375. }
  376. }
  377. /**
  378. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  379. *
  380. * @return array<int, array<string, mixed>>
  381. */
  382. protected function procuremenFetchErpPoolFromDb(): array
  383. {
  384. try {
  385. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  386. $endTime = date('Y-m-d 23:59:59');
  387. $list = Db::table('scydgy')
  388. ->alias('a')
  389. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  390. ->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')
  391. ->where([
  392. 'a.bwjg' => 1,
  393. 'a.iEndBz' => 0,
  394. 'a.iType' => 0,
  395. 'a.iStatus' => 10,
  396. ])
  397. ->where('a.dStamp', '>=', $startTime)
  398. ->where('a.dStamp', '<=', $endTime)
  399. ->order('a.dStamp', 'desc')
  400. ->select();
  401. if (!is_array($list)) {
  402. return [];
  403. }
  404. try {
  405. $redis = redis();
  406. $payload = [
  407. 'code' => 200,
  408. 'msg' => 'success',
  409. 'data' => $list,
  410. ];
  411. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  412. $this->procuremenRedisCache = $list;
  413. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  414. $this->clearPickMonthPoolCaches();
  415. $this->warmPickMonthPoolCachesFromPool($list);
  416. } catch (\Throwable $e) {
  417. }
  418. return $list;
  419. } catch (\Throwable $e) {
  420. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  421. return [];
  422. }
  423. }
  424. /**
  425. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  426. *
  427. * @return array<int, array<string, mixed>>
  428. */
  429. protected function procuremenEnsureRedisPool(): array
  430. {
  431. $pool = $this->ProcuremenRedis();
  432. if (is_array($pool) && $pool !== []) {
  433. return $pool;
  434. }
  435. static $warmed = false;
  436. if ($warmed) {
  437. return is_array($pool) ? $pool : [];
  438. }
  439. $warmed = true;
  440. return $this->procuremenFetchErpPoolFromDb();
  441. }
  442. /**
  443. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  444. *
  445. * @param array<string, mixed> $row
  446. */
  447. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  448. {
  449. $t = $this->procuremenRowListSortTime($row, $primary);
  450. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  451. return null;
  452. }
  453. $mo = (int)$m[2];
  454. if ($mo < 1 || $mo > 12) {
  455. return null;
  456. }
  457. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  458. }
  459. /**
  460. * @param array<int, array{year:string, months:array}> $sidebar
  461. * @return array<int, array{year:string, months:array}>
  462. */
  463. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  464. {
  465. $ym = trim($ym);
  466. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  467. return $sidebar;
  468. }
  469. foreach ($sidebar as $block) {
  470. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  471. continue;
  472. }
  473. foreach ($block['months'] as $item) {
  474. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  475. return $sidebar;
  476. }
  477. }
  478. }
  479. $y = substr($ym, 0, 4);
  480. $mo = (int)substr($ym, 5, 2);
  481. $sidebar[] = [
  482. 'year' => $y,
  483. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  484. ];
  485. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  486. }
  487. /**
  488. * @param array<int, array{year:string, months:array}> $sidebar
  489. * @return string[]
  490. */
  491. protected function flattenProcuremenSidebarYms(array $sidebar): array
  492. {
  493. $yms = [];
  494. foreach ($sidebar as $block) {
  495. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  496. continue;
  497. }
  498. foreach ($block['months'] as $item) {
  499. if (!is_array($item)) {
  500. continue;
  501. }
  502. $ym = trim((string)($item['ym'] ?? ''));
  503. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  504. $yms[$ym] = true;
  505. }
  506. }
  507. }
  508. return array_keys($yms);
  509. }
  510. /**
  511. * 左侧菜单(协助初选)
  512. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  513. */
  514. protected function GetIndexYearMonths()
  515. {
  516. $ymList = $this->ensureProcuremenPickSidebarYmList();
  517. if ($ymList === []) {
  518. $def = date('Y-m');
  519. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  520. }
  521. return $this->buildYearMonthSidebar($ymList);
  522. }
  523. /**
  524. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  525. *
  526. * @return string[]
  527. */
  528. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  529. {
  530. static $memo = null;
  531. if (!$forceRefresh && is_array($memo)) {
  532. return $memo;
  533. }
  534. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  535. if ($fromDb !== []) {
  536. $this->saveProcuremenSidebarYmList($fromDb);
  537. $memo = $fromDb;
  538. return $memo;
  539. }
  540. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  541. $cached = $this->loadProcuremenSidebarYmList();
  542. if ($cached !== []) {
  543. $memo = $cached;
  544. return $memo;
  545. }
  546. $memo = [date('Y-m')];
  547. return $memo;
  548. }
  549. /**
  550. * @return string[] 形如 2026-07
  551. */
  552. protected function loadProcuremenSidebarYmList(): array
  553. {
  554. try {
  555. $raw = redis()->get('procuremen_redis_yms');
  556. if ($raw === false || $raw === null || $raw === '') {
  557. return [];
  558. }
  559. $decoded = json_decode((string)$raw, true);
  560. if (!is_array($decoded)) {
  561. return [];
  562. }
  563. $out = [];
  564. foreach ($decoded as $ym) {
  565. $ym = trim((string)$ym);
  566. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  567. $out[$ym] = true;
  568. }
  569. }
  570. return array_keys($out);
  571. } catch (\Throwable $e) {
  572. return [];
  573. }
  574. }
  575. /**
  576. * @param string[] $ymList
  577. */
  578. protected function saveProcuremenSidebarYmList(array $ymList): void
  579. {
  580. $out = [];
  581. foreach ($ymList as $ym) {
  582. $ym = trim((string)$ym);
  583. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  584. $out[$ym] = true;
  585. }
  586. }
  587. if ($out === []) {
  588. return;
  589. }
  590. try {
  591. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  592. } catch (\Throwable $e) {
  593. }
  594. }
  595. /**
  596. * @param array<int, array<string, mixed>> $pool
  597. * @return string[]
  598. */
  599. protected function extractYearMonthsFromPoolRows(array $pool): array
  600. {
  601. $ymSet = [];
  602. foreach ($pool as $r) {
  603. if (!is_array($r)) {
  604. continue;
  605. }
  606. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  607. continue;
  608. }
  609. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  610. if ($ym !== null) {
  611. $ymSet[$ym] = true;
  612. }
  613. }
  614. return array_keys($ymSet);
  615. }
  616. /**
  617. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  618. *
  619. * @return string[]
  620. */
  621. protected function queryProcuremenPickSidebarYmListLight(): array
  622. {
  623. try {
  624. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  625. $endTime = date('Y-m-d 23:59:59');
  626. $sql = 'SELECT DISTINCT DATE_FORMAT('
  627. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  628. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  629. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  630. . ' FROM scydgy a'
  631. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  632. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  633. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  634. $rows = Db::query($sql, [$startTime, $endTime]);
  635. if (!is_array($rows)) {
  636. return [];
  637. }
  638. $out = [];
  639. foreach ($rows as $r) {
  640. $ym = trim((string)($r['ym'] ?? ''));
  641. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  642. $out[$ym] = true;
  643. }
  644. }
  645. return array_keys($out);
  646. } catch (\Throwable $e) {
  647. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  648. return [];
  649. }
  650. }
  651. /**
  652. * @return string[] 含当月在内的近 N 个自然月
  653. */
  654. protected function buildRecentCalendarYmList(int $months = 12): array
  655. {
  656. $months = max(1, min(24, $months));
  657. $out = [];
  658. $base = strtotime(date('Y-m-01'));
  659. for ($i = 0; $i < $months; $i++) {
  660. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  661. }
  662. return $out;
  663. }
  664. /**
  665. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  666. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  667. *
  668. * @return array<int, array<string, mixed>>
  669. */
  670. protected function loadPickPoolForYm(string $ym): array
  671. {
  672. $ym = trim($ym);
  673. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  674. return [];
  675. }
  676. $hit = $this->readPickMonthPoolCache($ym);
  677. if ($hit !== null) {
  678. return $hit;
  679. }
  680. return $this->queryPickPoolForYmFromDb($ym);
  681. }
  682. /**
  683. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  684. */
  685. protected function readPickMonthPoolCache(string $ym): ?array
  686. {
  687. try {
  688. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  689. if ($raw === false || $raw === null || $raw === '') {
  690. return null;
  691. }
  692. $decoded = json_decode((string)$raw, true);
  693. if (!is_array($decoded)) {
  694. return null;
  695. }
  696. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  697. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  698. return $decoded['rows'];
  699. }
  700. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  701. if ($decoded === []) {
  702. try {
  703. redis()->del('procuremen_pick_pool:' . $ym);
  704. } catch (\Throwable $e) {
  705. }
  706. return null;
  707. }
  708. if (isset($decoded[0]) && is_array($decoded[0])) {
  709. return $decoded;
  710. }
  711. return null;
  712. } catch (\Throwable $e) {
  713. return null;
  714. }
  715. }
  716. /**
  717. * @param array<int, array<string, mixed>> $rows
  718. */
  719. protected function writePickMonthPoolCache(string $ym, array $rows): void
  720. {
  721. try {
  722. redis()->setex(
  723. 'procuremen_pick_pool:' . $ym,
  724. 600,
  725. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  726. );
  727. } catch (\Throwable $e) {
  728. }
  729. }
  730. /**
  731. * @param array<int, array<string, mixed>> $pool
  732. * @return array<int, array<string, mixed>>
  733. */
  734. protected function filterPoolRowsByYm(array $pool, string $ym): array
  735. {
  736. $out = [];
  737. foreach ($pool as $r) {
  738. if (!is_array($r)) {
  739. continue;
  740. }
  741. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  742. continue;
  743. }
  744. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  745. $out[] = $r;
  746. }
  747. }
  748. return $out;
  749. }
  750. /**
  751. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  752. *
  753. * @return array<int, array<string, mixed>>
  754. */
  755. protected function queryPickPoolForYmFromDb(string $ym): array
  756. {
  757. $monthStart = $ym . '-01 00:00:00';
  758. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  759. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  760. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  761. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  762. try {
  763. $list = Db::table('scydgy')
  764. ->alias('a')
  765. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  766. ->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')
  767. ->where([
  768. 'a.bwjg' => 1,
  769. 'a.iEndBz' => 0,
  770. 'a.iType' => 0,
  771. 'a.iStatus' => 10,
  772. ])
  773. ->where('a.dStamp', '>=', $queryStart)
  774. ->where('a.dStamp', '<=', $queryEnd)
  775. ->order('a.dStamp', 'desc')
  776. ->select();
  777. } catch (\Throwable $e) {
  778. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  779. return [];
  780. }
  781. if (!is_array($list)) {
  782. $list = [];
  783. }
  784. $out = $this->filterPoolRowsByYm($list, $ym);
  785. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  786. $this->writePickMonthPoolCache($ym, $out);
  787. try {
  788. $yms = $this->loadProcuremenSidebarYmList();
  789. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  790. $yms[] = $ym;
  791. $this->saveProcuremenSidebarYmList($yms);
  792. }
  793. } catch (\Throwable $e) {
  794. }
  795. return $out;
  796. }
  797. /**
  798. * 整包写入后拆成按月小缓存,供初选列表秒开
  799. *
  800. * @param array<int, array<string, mixed>> $pool
  801. */
  802. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  803. {
  804. if ($pool === []) {
  805. return;
  806. }
  807. $byYm = [];
  808. foreach ($pool as $r) {
  809. if (!is_array($r)) {
  810. continue;
  811. }
  812. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  813. continue;
  814. }
  815. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  816. if ($rowYm === null) {
  817. continue;
  818. }
  819. $byYm[$rowYm][] = $r;
  820. }
  821. if ($byYm === []) {
  822. return;
  823. }
  824. try {
  825. $redis = redis();
  826. foreach ($byYm as $rowYm => $rows) {
  827. $redis->setex(
  828. 'procuremen_pick_pool:' . $rowYm,
  829. 600,
  830. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  831. );
  832. }
  833. try {
  834. $redis->del('procuremen_pick_hidden_scydgy_v1');
  835. } catch (\Throwable $e) {
  836. }
  837. } catch (\Throwable $e) {
  838. }
  839. }
  840. /**
  841. * 刷新整包后清理近月缓存,避免脏读
  842. */
  843. protected function clearPickMonthPoolCaches(int $months = 24): void
  844. {
  845. try {
  846. $redis = redis();
  847. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  848. try {
  849. $redis->del('procuremen_pick_pool:' . $ym);
  850. } catch (\Throwable $e) {
  851. }
  852. }
  853. } catch (\Throwable $e) {
  854. }
  855. $this->invalidatePickHiddenScydgyCache();
  856. }
  857. /**
  858. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  859. */
  860. protected function invalidatePickHiddenScydgyCache(): void
  861. {
  862. $this->pickHiddenScydgySetCache = null;
  863. try {
  864. redis()->del('procuremen_pick_hidden_scydgy_v1');
  865. } catch (\Throwable $e) {
  866. }
  867. }
  868. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  869. protected function procuremenReleaseSessionLock(): void
  870. {
  871. if (session_status() === PHP_SESSION_ACTIVE) {
  872. @session_write_close();
  873. }
  874. }
  875. /**
  876. * @param string[] $ymList 形如 2026-06
  877. * @return array<int, array{year:string, months:array}>
  878. */
  879. protected function buildYearMonthSidebar(array $ymList): array
  880. {
  881. rsort($ymList, SORT_STRING);
  882. $byYear = [];
  883. foreach ($ymList as $ym) {
  884. $y = substr($ym, 0, 4);
  885. $mo = (int)substr($ym, 5, 2);
  886. if (!isset($byYear[$y])) {
  887. $byYear[$y] = [];
  888. }
  889. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  890. }
  891. krsort($byYear, SORT_NUMERIC);
  892. foreach ($byYear as $y => $items) {
  893. usort($byYear[$y], function ($a, $b) {
  894. return strcmp($b['ym'], $a['ym']);
  895. });
  896. }
  897. $sidebar = [];
  898. foreach ($byYear as $y => $months) {
  899. $sidebar[] = ['year' => $y, 'months' => $months];
  900. }
  901. return $sidebar;
  902. }
  903. /**
  904. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  905. */
  906. protected function GetIssuedOrderYearMonths(string $stage): array
  907. {
  908. $ymSet = [];
  909. try {
  910. $query = Db::table('purchase_order');
  911. $this->applyPurchaseOrderNotDeletedWhere($query);
  912. if ($stage === 'audit') {
  913. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  914. } elseif ($stage === 'confirm') {
  915. $this->applyPurchaseOrderConfirmStageWhere($query);
  916. } else {
  917. return $this->GetIndexYearMonths();
  918. }
  919. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  920. if (is_array($rows)) {
  921. foreach ($rows as $r) {
  922. if (!is_array($r)) {
  923. continue;
  924. }
  925. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  926. if ($ym !== null) {
  927. $ymSet[$ym] = true;
  928. }
  929. }
  930. }
  931. } catch (\Throwable $e) {
  932. $ymSet = [];
  933. }
  934. $ymList = array_keys($ymSet);
  935. if ($ymList === []) {
  936. $def = $this->resolveProcuremenDefaultYm($stage);
  937. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  938. }
  939. return $this->buildYearMonthSidebar($ymList);
  940. }
  941. /**
  942. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  943. */
  944. protected function resolveProcuremenDefaultYm(string $stage): string
  945. {
  946. if ($stage === 'pick') {
  947. $yms = $this->ensureProcuremenPickSidebarYmList();
  948. if ($yms !== []) {
  949. rsort($yms, SORT_STRING);
  950. return $yms[0];
  951. }
  952. return date('Y-m');
  953. }
  954. try {
  955. $query = Db::table('purchase_order');
  956. $this->applyPurchaseOrderNotDeletedWhere($query);
  957. if ($stage === 'audit') {
  958. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  959. } elseif ($stage === 'confirm') {
  960. $this->applyPurchaseOrderConfirmStageWhere($query);
  961. } else {
  962. return date('Y-m');
  963. }
  964. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  965. if ($latest === null || $latest === '') {
  966. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  967. }
  968. $t = $this->formatProcuremenDetailTime($latest);
  969. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  970. return $m[1] . '-' . $m[2];
  971. }
  972. } catch (\Throwable $e) {
  973. }
  974. return date('Y-m');
  975. }
  976. protected function applyPurchaseOrderNotDeletedWhere($query): void
  977. {
  978. $query->whereRaw(
  979. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  980. );
  981. }
  982. /**
  983. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  984. */
  985. protected function applyPurchaseOrderConfirmStageWhere($query): void
  986. {
  987. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  988. $quoted = [];
  989. foreach ($vals as $v) {
  990. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  991. }
  992. if ($quoted === []) {
  993. $query->whereRaw('1 = 0');
  994. return;
  995. }
  996. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  997. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  998. }
  999. /**
  1000. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1001. *
  1002. * @param array<string, mixed> $row
  1003. * @return array<string, mixed>
  1004. */
  1005. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1006. {
  1007. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1008. $pick = trim((string)($row['pick_time'] ?? ''));
  1009. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1010. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1011. $t = trim((string)($row[$key] ?? ''));
  1012. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1013. $row['pick_time'] = $t;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. return $row;
  1019. }
  1020. /**
  1021. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1022. */
  1023. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1024. {
  1025. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1026. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1027. }
  1028. if ($pool === []) {
  1029. $def = $this->resolveProcuremenDefaultYm($stage);
  1030. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1031. }
  1032. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1033. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1034. return false;
  1035. }
  1036. $monthStart = $ym . '-01 00:00:00';
  1037. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1038. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1039. return $probe !== [];
  1040. };
  1041. if ($tryYm($requestedYm)) {
  1042. return $requestedYm;
  1043. }
  1044. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1045. if ($tryYm($fallback)) {
  1046. return $fallback;
  1047. }
  1048. $bestYm = '';
  1049. $bestTime = '';
  1050. foreach ($pool as $row) {
  1051. if (!is_array($row)) {
  1052. continue;
  1053. }
  1054. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1055. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1056. continue;
  1057. }
  1058. $ymRow = $m[1];
  1059. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1060. $bestTime = $t;
  1061. $bestYm = $ymRow;
  1062. }
  1063. }
  1064. if ($bestYm !== '') {
  1065. return $bestYm;
  1066. }
  1067. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1068. }
  1069. protected function isPurchaseOrderDetailVoid(array $row): bool
  1070. {
  1071. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1072. return true;
  1073. }
  1074. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1075. }
  1076. /**
  1077. * 仅当前有效下发明细(排除废弃归档)
  1078. */
  1079. protected function applyActivePurchaseOrderDetailWhere($query): void
  1080. {
  1081. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1082. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1083. }
  1084. /**
  1085. * @param array<string, mixed> $detailRow
  1086. */
  1087. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1088. {
  1089. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1090. return false;
  1091. }
  1092. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1093. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1094. }
  1095. /**
  1096. * 废弃退回初选:下发明细标记归档,不物理删除
  1097. *
  1098. * @param array<int, int|string> $scydgyIds
  1099. */
  1100. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1101. {
  1102. $ids = [];
  1103. foreach ($scydgyIds as $sid) {
  1104. $n = (int)$sid;
  1105. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1106. $ids[$n] = true;
  1107. }
  1108. }
  1109. if ($ids === []) {
  1110. return;
  1111. }
  1112. $void = ProcuremenStatus::POD_VOID;
  1113. Db::table('purchase_order_detail')
  1114. ->where('scydgy_id', 'in', array_keys($ids))
  1115. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1116. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1117. ->update([
  1118. 'status' => $void,
  1119. 'status_name' => $void,
  1120. ]);
  1121. }
  1122. /**
  1123. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1124. */
  1125. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1126. {
  1127. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1128. $norm = function (string $col) use ($p): string {
  1129. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1130. };
  1131. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1132. $parts = [];
  1133. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1134. if ($key === 'createtime') {
  1135. $parts[] = $createtime;
  1136. } else {
  1137. $parts[] = $norm($key);
  1138. }
  1139. }
  1140. return 'COALESCE(' . implode(', ', $parts) . ')';
  1141. }
  1142. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1143. {
  1144. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1145. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1146. }
  1147. /**
  1148. * @return array<int, array<string, mixed>>
  1149. */
  1150. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1151. {
  1152. $this->ensurePurchaseOrderCzlyqColumn();
  1153. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1154. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1155. try {
  1156. $query = Db::table('purchase_order')->field($fields);
  1157. $this->applyPurchaseOrderNotDeletedWhere($query);
  1158. if ($stage === 'audit') {
  1159. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1160. } elseif ($stage === 'confirm') {
  1161. $this->applyPurchaseOrderConfirmStageWhere($query);
  1162. } else {
  1163. return [];
  1164. }
  1165. $query->order('pick_time', 'desc')->order('id', 'desc');
  1166. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1167. $monthStart = $ym . '-01 00:00:00';
  1168. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1169. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1170. }
  1171. $rows = $query->select();
  1172. } catch (\Throwable $e) {
  1173. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1174. $rows = [];
  1175. }
  1176. return is_array($rows) ? $rows : [];
  1177. }
  1178. /**
  1179. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1180. */
  1181. protected function resolveProcuremenListStage(): string
  1182. {
  1183. $tab = trim((string)$this->request->request('wff_tab', ''));
  1184. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1185. return $tab;
  1186. }
  1187. $action = strtolower((string)$this->request->action());
  1188. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1189. return $action;
  1190. }
  1191. return 'pick';
  1192. }
  1193. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1194. {
  1195. $this->procuremenReleaseSessionLock();
  1196. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1197. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1198. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1199. $indexPhpRoot = $rootTrue . '/index.php';
  1200. }
  1201. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1202. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1203. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1204. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1205. $this->view->assign('defaultYm', $defaultYm);
  1206. $this->view->assign('sidebarYearMonths', $sidebar);
  1207. $this->view->assign('procuremenStage', $stage);
  1208. $this->view->assign('procuremenPageTitle', $pageTitle);
  1209. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1210. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1211. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1212. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1213. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1214. }
  1215. /**
  1216. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1217. *
  1218. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1219. */
  1220. protected function buildProcuremenFilterOptions(string $stage): array
  1221. {
  1222. $buckets = [
  1223. 'czlyq' => [],
  1224. 'CCLBMMC' => [],
  1225. 'cywyxm' => [],
  1226. 'CGYMC' => [],
  1227. ];
  1228. $maxPerField = 300;
  1229. try {
  1230. if ($stage === 'pick') {
  1231. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1232. return $buckets;
  1233. }
  1234. if (in_array($stage, ['audit', 'confirm'], true)) {
  1235. $this->ensurePurchaseOrderCzlyqColumn();
  1236. foreach (array_keys($buckets) as $field) {
  1237. try {
  1238. $query = Db::table('purchase_order')->field($field);
  1239. $this->applyPurchaseOrderNotDeletedWhere($query);
  1240. if ($stage === 'audit') {
  1241. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1242. } else {
  1243. $this->applyPurchaseOrderConfirmStageWhere($query);
  1244. }
  1245. $query->where($field, '<>', '')->whereNotNull($field);
  1246. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1247. if (!is_array($vals)) {
  1248. continue;
  1249. }
  1250. foreach ($vals as $v) {
  1251. $v = trim((string)$v);
  1252. if ($v !== '') {
  1253. $buckets[$field][$v] = $v;
  1254. }
  1255. }
  1256. } catch (\Throwable $e) {
  1257. // 单字段失败不影响其它
  1258. }
  1259. }
  1260. }
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1263. }
  1264. foreach ($buckets as &$set) {
  1265. if ($set !== []) {
  1266. ksort($set, SORT_STRING);
  1267. }
  1268. }
  1269. unset($set);
  1270. return $buckets;
  1271. }
  1272. /**
  1273. * filter JSON 是否含有效条件
  1274. *
  1275. * @param array<string, mixed> $filterArr
  1276. */
  1277. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1278. {
  1279. foreach ($filterArr as $v) {
  1280. if (is_array($v)) {
  1281. if (array_filter($v, function ($x) {
  1282. return $x !== '' && $x !== null;
  1283. })) {
  1284. return true;
  1285. }
  1286. } elseif ($v !== '' && $v !== null) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1294. *
  1295. * @param array<string, mixed> $filterArr
  1296. * @param array<string, mixed> $opArr
  1297. */
  1298. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1299. {
  1300. if ($search !== '') {
  1301. return false;
  1302. }
  1303. foreach ($filterArr as $fk => $fv) {
  1304. if (is_array($fv)) {
  1305. continue;
  1306. }
  1307. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1308. continue;
  1309. }
  1310. if ($fv === null) {
  1311. continue;
  1312. }
  1313. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1314. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1315. if ($sym === '' || $sym === '=') {
  1316. continue;
  1317. }
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. /**
  1323. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1324. *
  1325. * @param array<int, mixed> $rows
  1326. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1327. */
  1328. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1329. {
  1330. $buckets = [
  1331. 'czlyq' => [],
  1332. 'CCLBMMC' => [],
  1333. 'cywyxm' => [],
  1334. 'CGYMC' => [],
  1335. ];
  1336. foreach ($rows as $r) {
  1337. if (!is_array($r)) {
  1338. continue;
  1339. }
  1340. foreach ($buckets as $field => &$set) {
  1341. if (count($set) >= $maxPerField) {
  1342. continue;
  1343. }
  1344. $v = trim((string)($r[$field] ?? ''));
  1345. if ($v !== '') {
  1346. $set[$v] = $v;
  1347. }
  1348. }
  1349. unset($set);
  1350. $full = true;
  1351. foreach ($buckets as $set) {
  1352. if (count($set) < $maxPerField) {
  1353. $full = false;
  1354. break;
  1355. }
  1356. }
  1357. if ($full) {
  1358. break;
  1359. }
  1360. }
  1361. foreach ($buckets as &$set) {
  1362. if ($set !== []) {
  1363. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1364. $normalized = [];
  1365. foreach ($set as $k => $v) {
  1366. $s = trim((string)(is_scalar($v) ? $v : $k));
  1367. if ($s === '') {
  1368. continue;
  1369. }
  1370. $normalized[$s] = $s;
  1371. }
  1372. ksort($normalized, SORT_STRING);
  1373. $set = $normalized;
  1374. }
  1375. }
  1376. unset($set);
  1377. return $buckets;
  1378. }
  1379. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1380. public function pick()
  1381. {
  1382. $this->request->filter(['strip_tags', 'trim']);
  1383. if (!$this->request->isAjax()) {
  1384. $this->assignProcuremenListPage('pick', '协助下发');
  1385. return $this->view->fetch('procuremen/index');
  1386. }
  1387. return $this->index();
  1388. }
  1389. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1390. public function audit()
  1391. {
  1392. $this->request->filter(['strip_tags', 'trim']);
  1393. if (!$this->request->isAjax()) {
  1394. $this->assignProcuremenListPage('audit', '确认供应商');
  1395. return $this->view->fetch('procuremen/index');
  1396. }
  1397. return $this->index();
  1398. }
  1399. /** 采购确认(定标) */
  1400. public function confirm()
  1401. {
  1402. $this->request->filter(['strip_tags', 'trim']);
  1403. if (!$this->request->isAjax()) {
  1404. $this->assignProcuremenListPage('confirm', '采购确认');
  1405. return $this->view->fetch('procuremen/index');
  1406. }
  1407. return $this->index();
  1408. }
  1409. /**
  1410. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1411. */
  1412. public function index()
  1413. {
  1414. $this->request->filter(['strip_tags', 'trim']);
  1415. if (!$this->request->isAjax()) {
  1416. $this->assignProcuremenListPage('pick', '协助下发');
  1417. return $this->view->fetch('procuremen/index');
  1418. }
  1419. if ($this->request->request('keyField')) {
  1420. return $this->selectpage();
  1421. }
  1422. $this->procuremenReleaseSessionLock();
  1423. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1424. $limit = max(10, min(500, (int)$limit));
  1425. $ym = $this->request->request('ym', '');
  1426. $ym = is_string($ym) ? trim($ym) : '';
  1427. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1428. $wffTab = $this->resolveProcuremenListStage();
  1429. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1430. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1431. ? $this->resolveProcuremenDefaultYm($wffTab)
  1432. : date('Y-m');
  1433. }
  1434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1435. $ym = date('Y-m');
  1436. }
  1437. $monthStart = $ym . '-01 00:00:00';
  1438. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1439. $search = trim((string)$this->request->get('search', ''));
  1440. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1441. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1442. if (!is_array($filterArr)) {
  1443. $filterArr = [];
  1444. }
  1445. if (!is_array($opArr)) {
  1446. $opArr = [];
  1447. }
  1448. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1449. $bidOpenStatusFilter = '';
  1450. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1451. if (!array_key_exists($bidFk, $filterArr)) {
  1452. continue;
  1453. }
  1454. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1455. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1456. }
  1457. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1458. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1459. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1460. try {
  1461. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1462. if ($wffTab === 'audit') {
  1463. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1464. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1465. );
  1466. } elseif ($wffTab === 'confirm') {
  1467. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1468. if ($dbRows === []) {
  1469. try {
  1470. $dbRows = Db::table('purchase_order')
  1471. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1472. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1473. ->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%\')')
  1474. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1475. ->order('pick_time', 'desc')->order('id', 'desc')
  1476. ->select();
  1477. } catch (\Throwable $e) {
  1478. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1479. $dbRows = [];
  1480. }
  1481. }
  1482. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1483. if ($pool === []) {
  1484. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1485. }
  1486. } else {
  1487. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1488. if ($applyMonthRange) {
  1489. $pool = $this->loadPickPoolForYm($ym);
  1490. } else {
  1491. $pool = $this->procuremenEnsureRedisPool();
  1492. }
  1493. if (!is_array($pool)) {
  1494. $pool = [];
  1495. }
  1496. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1497. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1498. if ($pool !== [] && $hideSet !== []) {
  1499. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1500. if (!is_array($r)) {
  1501. return false;
  1502. }
  1503. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1504. return $id <= 0 || !isset($hideSet[$id]);
  1505. }));
  1506. }
  1507. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1508. if ($pool === []) {
  1509. return json([
  1510. 'total' => 0,
  1511. 'rows' => [],
  1512. 'activeYm' => $ym,
  1513. 'filterOptions' => (
  1514. (int)$offset === 0
  1515. && !$hasActiveSearch
  1516. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1517. )
  1518. ? $this->extractProcuremenFilterOptionsFromRows([])
  1519. : new \stdClass(),
  1520. ]);
  1521. }
  1522. }
  1523. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1524. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1525. $monthStart = $ym . '-01 00:00:00';
  1526. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1527. }
  1528. $filtered = $this->filterProcuremenIndexPool(
  1529. $pool,
  1530. $monthStart,
  1531. $monthEnd,
  1532. $applyMonthRange,
  1533. $search,
  1534. $filterArr,
  1535. $opArr,
  1536. $listTimePrimary
  1537. );
  1538. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1539. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1540. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1541. }
  1542. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1543. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1544. }
  1545. $sortField = 'ID';
  1546. if (is_string($sort) && $sort !== '') {
  1547. $parts = explode(',', $sort);
  1548. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1549. if ($sortField === '') {
  1550. $sortField = 'ID';
  1551. }
  1552. }
  1553. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1554. $nFiltered = count($filtered);
  1555. if ($nFiltered > 1) {
  1556. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1557. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1558. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1559. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1560. if ($ta === $tb) {
  1561. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1562. }
  1563. if ($ta === '') {
  1564. return 1;
  1565. }
  1566. if ($tb === '') {
  1567. return -1;
  1568. }
  1569. return strcmp($ta, $tb) * $ord;
  1570. });
  1571. } elseif ($sortField === 'ID') {
  1572. $sortKeys = [];
  1573. foreach ($filtered as $i => $row) {
  1574. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1575. }
  1576. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1577. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1578. } elseif ($sortField === 'CCYDH') {
  1579. usort($filtered, function ($a, $b) use ($ord) {
  1580. $sa = trim((string)($a['CCYDH'] ?? ''));
  1581. $sb = trim((string)($b['CCYDH'] ?? ''));
  1582. if ($sa === $sb) {
  1583. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1584. }
  1585. if ($sa === '') {
  1586. return 1;
  1587. }
  1588. if ($sb === '') {
  1589. return -1;
  1590. }
  1591. return strcmp($sa, $sb) * $ord;
  1592. });
  1593. } else {
  1594. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1595. $va = $a[$sortField] ?? null;
  1596. $vb = $b[$sortField] ?? null;
  1597. $sa = (string)$va;
  1598. $sb = (string)$vb;
  1599. if ($sa === $sb) {
  1600. return 0;
  1601. }
  1602. return strcmp($sa, $sb) * $ord;
  1603. });
  1604. }
  1605. }
  1606. $offset = max(0, (int)$offset);
  1607. $limit = max(1, (int)$limit);
  1608. $rows = array_slice($filtered, $offset, $limit);
  1609. foreach ($rows as &$rw) {
  1610. if (!is_array($rw)) {
  1611. continue;
  1612. }
  1613. $rid = (int)($rw['ID'] ?? 0);
  1614. $rw['_iss_out'] = ($wffTab !== 'pick');
  1615. }
  1616. unset($rw);
  1617. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1618. $idList = [];
  1619. foreach ($rows as $rw) {
  1620. if (!is_array($rw)) {
  1621. continue;
  1622. }
  1623. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1624. foreach ($rw['_order_merge_rows'] as $mr) {
  1625. $mid = (int)($mr['ID'] ?? 0);
  1626. if ($this->isValidScydgyRowId($mid)) {
  1627. $idList[$mid] = true;
  1628. }
  1629. }
  1630. }
  1631. $id = (int)($rw['ID'] ?? 0);
  1632. if ($this->isValidScydgyRowId($id)) {
  1633. $idList[$id] = true;
  1634. }
  1635. }
  1636. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1637. foreach ($rows as &$rw) {
  1638. if (!is_array($rw)) {
  1639. continue;
  1640. }
  1641. $mergeIds = [];
  1642. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1643. foreach ($rw['_order_merge_rows'] as $mr) {
  1644. $mid = (int)($mr['ID'] ?? 0);
  1645. if ($this->isValidScydgyRowId($mid)) {
  1646. $mergeIds[$mid] = true;
  1647. }
  1648. }
  1649. }
  1650. $rid = (int)($rw['ID'] ?? 0);
  1651. if ($this->isValidScydgyRowId($rid)) {
  1652. $mergeIds[$rid] = true;
  1653. }
  1654. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1655. $rw['po_detail_count'] = $s['cnt'];
  1656. $rw['po_amount_fill_cnt'] = $s['amt'];
  1657. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1658. }
  1659. unset($rw);
  1660. }
  1661. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1662. $idList = [];
  1663. foreach ($rows as $rw) {
  1664. if (!is_array($rw)) {
  1665. continue;
  1666. }
  1667. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1668. foreach ($rw['_order_merge_rows'] as $mr) {
  1669. $mid = (int)($mr['ID'] ?? 0);
  1670. if ($this->isValidScydgyRowId($mid)) {
  1671. $idList[$mid] = true;
  1672. }
  1673. }
  1674. }
  1675. $id = (int)($rw['ID'] ?? 0);
  1676. if ($this->isValidScydgyRowId($id)) {
  1677. $idList[$id] = true;
  1678. }
  1679. }
  1680. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1681. $bidOpenSet = [];
  1682. $manualPickSet = [];
  1683. if ($wffTab === 'audit') {
  1684. $ccydhList = [];
  1685. foreach ($rows as $rw0) {
  1686. if (!is_array($rw0)) {
  1687. continue;
  1688. }
  1689. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1690. if ($c0 !== '') {
  1691. $ccydhList[] = $c0;
  1692. }
  1693. }
  1694. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1695. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1696. }
  1697. foreach ($rows as &$rw) {
  1698. if (!is_array($rw)) {
  1699. continue;
  1700. }
  1701. $mergeIds = [];
  1702. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1703. foreach ($rw['_order_merge_rows'] as $mr) {
  1704. $mid = (int)($mr['ID'] ?? 0);
  1705. if ($this->isValidScydgyRowId($mid)) {
  1706. $mergeIds[$mid] = true;
  1707. }
  1708. }
  1709. }
  1710. $rid = (int)($rw['ID'] ?? 0);
  1711. if ($this->isValidScydgyRowId($rid)) {
  1712. $mergeIds[$rid] = true;
  1713. }
  1714. $buckets = [];
  1715. foreach (array_keys($mergeIds) as $mid) {
  1716. if (isset($quoteBucket[$mid])) {
  1717. $buckets[] = $quoteBucket[$mid];
  1718. }
  1719. }
  1720. $supplierText = $buckets !== []
  1721. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1722. : '';
  1723. if ($wffTab === 'confirm') {
  1724. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1725. if ($picked === '') {
  1726. // 兜底:从合并工序行取
  1727. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1728. foreach ($rw['_order_merge_rows'] as $mr) {
  1729. if (!is_array($mr)) {
  1730. continue;
  1731. }
  1732. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1733. if ($pn !== '') {
  1734. $picked = $pn;
  1735. break;
  1736. }
  1737. }
  1738. }
  1739. }
  1740. $rw['picked_supplier_name'] = $picked;
  1741. } else {
  1742. $rw['notify_supplier_text'] = $supplierText;
  1743. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1744. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1745. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1746. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1747. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1748. if ($verified) {
  1749. $rw['bid_open_status_text'] = '已开标';
  1750. } elseif ($manualPicked) {
  1751. $rw['bid_open_status_text'] = '已指定供应商';
  1752. } else {
  1753. $rw['bid_open_status_text'] = '待开标';
  1754. }
  1755. }
  1756. }
  1757. unset($rw);
  1758. }
  1759. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1760. $this->enrichProcuremenListMilestoneTimes($rows);
  1761. $this->syncCollapsedOrderQtyPriceForList($rows);
  1762. }
  1763. if ($wffTab === 'all' && count($rows) > 0) {
  1764. $this->mergePurchaseOrder($rows);
  1765. }
  1766. if ($wffTab === 'pick' && count($rows) > 0) {
  1767. $this->mergePurchaseOrder($rows);
  1768. }
  1769. foreach ($rows as &$rwClean) {
  1770. if (is_array($rwClean)) {
  1771. unset($rwClean['_order_merge_rows']);
  1772. if (array_key_exists('NGZL', $rwClean)) {
  1773. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1774. }
  1775. }
  1776. }
  1777. unset($rwClean);
  1778. return json([
  1779. 'total' => count($filtered),
  1780. 'rows' => $rows,
  1781. 'activeYm' => $ym,
  1782. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1783. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1784. ? $this->ensureProcuremenPickSidebarYmList()
  1785. : [],
  1786. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1787. 'filterOptions' => (
  1788. (int)$offset === 0
  1789. && !$hasActiveSearch
  1790. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1791. )
  1792. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1793. : new \stdClass(),
  1794. ]);
  1795. } catch (\Throwable $e) {
  1796. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1797. return json([
  1798. 'total' => 0,
  1799. 'rows' => [],
  1800. ]);
  1801. }
  1802. }
  1803. /**
  1804. * @param array<int, array<string, mixed>> $pool
  1805. * @return int[]
  1806. */
  1807. protected function extractScydgyIdsFromPool(array $pool): array
  1808. {
  1809. $ids = [];
  1810. foreach ($pool as $r) {
  1811. if (!is_array($r)) {
  1812. continue;
  1813. }
  1814. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1815. if ($id > 0) {
  1816. $ids[$id] = $id;
  1817. }
  1818. }
  1819. return array_values($ids);
  1820. }
  1821. /**
  1822. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1823. *
  1824. * @param int[] $scydgyIds
  1825. * @return array<int, true>
  1826. */
  1827. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1828. {
  1829. $hideSet = [];
  1830. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1831. return $id > 0;
  1832. }));
  1833. if ($scydgyIds === []) {
  1834. return $hideSet;
  1835. }
  1836. // 分批,避免 whereIn 过长
  1837. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1838. try {
  1839. $poIds = Db::table('purchase_order')
  1840. ->where('scydgy_id', 'in', $chunk)
  1841. ->where(function ($q) {
  1842. $q->whereIn('wflow_status', array_merge(
  1843. ProcuremenStatus::wflowPendingConfirmValues(),
  1844. ProcuremenStatus::wflowPendingApprovalValues()
  1845. ))
  1846. ->whereOr(function ($q1) {
  1847. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1848. })
  1849. ->whereOr(function ($q2) {
  1850. $q2->whereNotNull('pick_time')
  1851. ->where('pick_time', '<>', '')
  1852. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1853. })
  1854. ->whereOr(function ($q3) {
  1855. $q3->whereNotNull('mod_rq')
  1856. ->where('mod_rq', '<>', '')
  1857. ->where('mod_rq', 'not like', '0000-00-00%');
  1858. });
  1859. })
  1860. ->column('scydgy_id');
  1861. if (is_array($poIds)) {
  1862. foreach ($poIds as $pid) {
  1863. $k = (int)$pid;
  1864. if ($k !== 0) {
  1865. $hideSet[$k] = true;
  1866. }
  1867. }
  1868. }
  1869. } catch (\Throwable $e) {
  1870. }
  1871. try {
  1872. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1873. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1874. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1875. if (is_array($detIds)) {
  1876. foreach ($detIds as $pid) {
  1877. $k = (int)$pid;
  1878. if ($this->isValidScydgyRowId($k)) {
  1879. $hideSet[$k] = true;
  1880. }
  1881. }
  1882. }
  1883. } catch (\Throwable $e) {
  1884. }
  1885. }
  1886. return $hideSet;
  1887. }
  1888. /**
  1889. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1890. *
  1891. * @return array<int, true>
  1892. */
  1893. protected function loadPickHiddenScydgySet(): array
  1894. {
  1895. if ($this->pickHiddenScydgySetCache !== null) {
  1896. return $this->pickHiddenScydgySetCache;
  1897. }
  1898. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1899. try {
  1900. $raw = redis()->get($cacheKey);
  1901. if ($raw !== false && $raw !== null && $raw !== '') {
  1902. $ids = json_decode((string)$raw, true);
  1903. if (is_array($ids)) {
  1904. $hideSet = [];
  1905. foreach ($ids as $pid) {
  1906. $k = (int)$pid;
  1907. if ($k !== 0) {
  1908. $hideSet[$k] = true;
  1909. }
  1910. }
  1911. $this->pickHiddenScydgySetCache = $hideSet;
  1912. return $hideSet;
  1913. }
  1914. }
  1915. } catch (\Throwable $e) {
  1916. }
  1917. $hideSet = [];
  1918. try {
  1919. $poIds = Db::table('purchase_order')
  1920. ->where(function ($q) {
  1921. $q->whereIn('wflow_status', array_merge(
  1922. ProcuremenStatus::wflowPendingConfirmValues(),
  1923. ProcuremenStatus::wflowPendingApprovalValues()
  1924. ))
  1925. ->whereOr(function ($q1) {
  1926. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1927. })
  1928. ->whereOr(function ($q2) {
  1929. $q2->whereNotNull('pick_time')
  1930. ->where('pick_time', '<>', '')
  1931. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1932. })
  1933. ->whereOr(function ($q3) {
  1934. $q3->whereNotNull('mod_rq')
  1935. ->where('mod_rq', '<>', '')
  1936. ->where('mod_rq', 'not like', '0000-00-00%');
  1937. });
  1938. })
  1939. ->column('scydgy_id');
  1940. if (is_array($poIds)) {
  1941. foreach ($poIds as $pid) {
  1942. $k = (int)$pid;
  1943. if ($k !== 0) {
  1944. $hideSet[$k] = true;
  1945. }
  1946. }
  1947. }
  1948. } catch (\Throwable $e) {
  1949. }
  1950. try {
  1951. $detIdsQuery = Db::table('purchase_order_detail');
  1952. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1953. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1954. if (is_array($detIds)) {
  1955. foreach ($detIds as $pid) {
  1956. $k = (int)$pid;
  1957. if ($this->isValidScydgyRowId($k)) {
  1958. $hideSet[$k] = true;
  1959. }
  1960. }
  1961. }
  1962. } catch (\Throwable $e) {
  1963. }
  1964. $this->pickHiddenScydgySetCache = $hideSet;
  1965. try {
  1966. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1967. } catch (\Throwable $e) {
  1968. }
  1969. return $hideSet;
  1970. }
  1971. /**
  1972. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1973. *
  1974. * @return array<int, array<string, mixed>>
  1975. */
  1976. protected function loadPickManualOrderRows(): array
  1977. {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')
  1980. ->where('scydgy_id', '<', 0)
  1981. ->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%\')')
  1982. ->order('scydgy_id', 'asc')
  1983. ->select();
  1984. } catch (\Throwable $e) {
  1985. try {
  1986. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1987. } catch (\Throwable $e2) {
  1988. return [];
  1989. }
  1990. }
  1991. if (!is_array($dbRows) || $dbRows === []) {
  1992. return [];
  1993. }
  1994. $detailSidSet = [];
  1995. try {
  1996. $negIds = [];
  1997. foreach ($dbRows as $dbRow) {
  1998. if (!is_array($dbRow)) {
  1999. continue;
  2000. }
  2001. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2002. if ($sid < 0) {
  2003. $negIds[$sid] = true;
  2004. }
  2005. }
  2006. if ($negIds !== []) {
  2007. $detQuery = Db::table('purchase_order_detail')
  2008. ->where('scydgy_id', 'in', array_keys($negIds));
  2009. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2010. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2011. if (is_array($detRows)) {
  2012. foreach ($detRows as $did) {
  2013. $detailSidSet[(int)$did] = true;
  2014. }
  2015. }
  2016. }
  2017. } catch (\Throwable $e) {
  2018. }
  2019. $pool = [];
  2020. foreach ($dbRows as $dbRow) {
  2021. if (!is_array($dbRow)) {
  2022. continue;
  2023. }
  2024. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2025. if ($sid >= 0) {
  2026. continue;
  2027. }
  2028. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2029. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2030. continue;
  2031. }
  2032. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2033. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2034. continue;
  2035. }
  2036. if (isset($detailSidSet[$sid])) {
  2037. continue;
  2038. }
  2039. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2040. $r['_is_manual'] = 1;
  2041. $pool[] = $r;
  2042. }
  2043. return $pool;
  2044. }
  2045. /**
  2046. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2047. */
  2048. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2049. {
  2050. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2051. foreach ($keys as $k) {
  2052. $t = trim((string)($row[$k] ?? ''));
  2053. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2054. return $t;
  2055. }
  2056. }
  2057. return '';
  2058. }
  2059. /**
  2060. * 分配手工新增工序行 ID(负数递减)
  2061. * 调用方须在命名锁内执行,避免并发重复
  2062. */
  2063. protected function allocateManualScydgyId(): int
  2064. {
  2065. try {
  2066. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2067. $min = (int)$min;
  2068. return $min < 0 ? $min - 1 : -1;
  2069. } catch (\Throwable $e) {
  2070. return -1;
  2071. }
  2072. }
  2073. /**
  2074. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2075. * 调用方须在命名锁内执行,避免并发重复
  2076. */
  2077. protected function allocateManualOrderCcydh(): string
  2078. {
  2079. $prefix = 'YW' . date('Ymd');
  2080. $maxSeq = 0;
  2081. try {
  2082. $rows = Db::table('purchase_order')
  2083. ->where('CCYDH', 'like', $prefix . '%')
  2084. ->column('CCYDH');
  2085. if (is_array($rows)) {
  2086. foreach ($rows as $ccydh) {
  2087. $ccydh = trim((string)$ccydh);
  2088. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2089. $maxSeq = max($maxSeq, (int)$m[1]);
  2090. }
  2091. }
  2092. }
  2093. } catch (\Throwable $e) {
  2094. }
  2095. $next = $maxSeq + 1;
  2096. $width = $next > 999 ? strlen((string)$next) : 3;
  2097. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2098. }
  2099. /**
  2100. * MySQL 命名锁(跨连接防并发撞号)
  2101. */
  2102. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2103. {
  2104. $name = trim($name);
  2105. if ($name === '') {
  2106. return false;
  2107. }
  2108. try {
  2109. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2110. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2111. if (!is_array($rows) || $rows === []) {
  2112. return false;
  2113. }
  2114. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2115. return (int)$v === 1;
  2116. } catch (\Throwable $e) {
  2117. return false;
  2118. }
  2119. }
  2120. protected function releaseProcuremenNamedLock(string $name): void
  2121. {
  2122. $name = trim($name);
  2123. if ($name === '') {
  2124. return;
  2125. }
  2126. try {
  2127. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2128. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2129. } catch (\Throwable $e) {
  2130. }
  2131. }
  2132. /**
  2133. * purchase_order.mod_rq 是否有有效软删除时间
  2134. */
  2135. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2136. {
  2137. $t = trim((string)$modRq);
  2138. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2139. }
  2140. /**
  2141. * 列表行 → purchase_order 写入字段
  2142. *
  2143. * @return array<string, mixed>
  2144. */
  2145. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2146. {
  2147. return [
  2148. 'scydgy_id' => $scydgyId,
  2149. 'CCYDH' => $row['CCYDH'] ?? null,
  2150. 'CYJMC' => $row['CYJMC'] ?? null,
  2151. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2152. 'CDXMC' => $row['CDXMC'] ?? null,
  2153. 'CGYBH' => $row['CGYBH'] ?? null,
  2154. 'CGYMC' => $row['CGYMC'] ?? null,
  2155. 'CDW' => $row['CDW'] ?? null,
  2156. 'czlyq' => $row['czlyq'] ?? null,
  2157. 'NGZL' => $row['NGZL'] ?? null,
  2158. 'CDF' => $row['CDF'] ?? null,
  2159. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2160. 'MBZ' => $row['MBZ'] ?? null,
  2161. 'bwjg' => $row['bwjg'] ?? null,
  2162. 'iStatus' => $row['iStatus'] ?? null,
  2163. 'dStamp' => $row['dStamp'] ?? null,
  2164. 'dputrecord' => $row['dputrecord'] ?? null,
  2165. 'cywyxm' => $row['cywyxm'] ?? null,
  2166. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2167. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2168. ];
  2169. }
  2170. /**
  2171. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2172. *
  2173. * @return array{po:?array<string,mixed>, hidden:bool}
  2174. */
  2175. protected function resolvePickRowPoContext(int $sid): array
  2176. {
  2177. $po = null;
  2178. try {
  2179. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2180. if (is_array($found)) {
  2181. $po = $found;
  2182. }
  2183. } catch (\Throwable $e) {
  2184. }
  2185. $hideSet = $this->loadPickHiddenScydgySet();
  2186. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2187. }
  2188. /**
  2189. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2190. */
  2191. protected function assertPickRowCanDelete(int $sid, array $row): void
  2192. {
  2193. $ctx = $this->resolvePickRowPoContext($sid);
  2194. $po = $ctx['po'];
  2195. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2196. return;
  2197. }
  2198. if (is_array($po)) {
  2199. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2200. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2201. }
  2202. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2203. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2204. }
  2205. }
  2206. if ($ctx['hidden']) {
  2207. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2208. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2209. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2210. }
  2211. }
  2212. /**
  2213. * 初选直接完结前校验
  2214. */
  2215. protected function assertPickRowCanComplete(int $sid, array $row): void
  2216. {
  2217. $ctx = $this->resolvePickRowPoContext($sid);
  2218. $po = $ctx['po'];
  2219. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2220. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2221. }
  2222. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2223. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2224. }
  2225. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2226. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2227. }
  2228. }
  2229. /**
  2230. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2231. */
  2232. protected function softDeleteProcuremenPickRow(array $row): void
  2233. {
  2234. $sid = $this->extractScydgyRowId($row);
  2235. if (!$this->isValidScydgyRowId($sid)) {
  2236. throw new \InvalidArgumentException('无效的行主键');
  2237. }
  2238. $this->assertPickRowCanDelete($sid, $row);
  2239. $po = $this->resolvePickRowPoContext($sid)['po'];
  2240. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2241. return;
  2242. }
  2243. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2244. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2245. }
  2246. $now = date('Y-m-d H:i:s');
  2247. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2248. if (is_array($exists)) {
  2249. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2250. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2251. } else {
  2252. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2253. $data['mod_rq'] = $now;
  2254. $data['createtime'] = $now;
  2255. Db::table('purchase_order')->insert($data);
  2256. $poIdLog = (int)Db::getLastInsID();
  2257. }
  2258. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2259. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2260. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2261. if ($gymcLog !== '') {
  2262. $logTail .= ' / ' . $gymcLog;
  2263. }
  2264. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2265. }
  2266. /**
  2267. * 手工新增协助工序(写入 purchase_order)
  2268. *
  2269. * @param array<string, mixed> $params
  2270. * @return int scydgy_id
  2271. */
  2272. protected function saveManualPickOrder(array $params): int
  2273. {
  2274. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2275. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2276. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2277. $lockName = 'procuremen_manual_order_alloc';
  2278. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2279. throw new \RuntimeException('系统繁忙,请稍后重试');
  2280. }
  2281. try {
  2282. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2283. $now = date('Y-m-d H:i:s');
  2284. $sid = $this->allocateManualScydgyId();
  2285. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2286. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2287. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2288. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2289. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2290. $data = [
  2291. 'scydgy_id' => $sid,
  2292. 'CCYDH' => $ccydh,
  2293. 'CYJMC' => $cyjmc,
  2294. 'CGYMC' => $cgymc,
  2295. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2296. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2297. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2298. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2299. 'cGzzxMc' => $supplierName,
  2300. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2301. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2302. 'notify_salesman' => $notifySalesman,
  2303. 'rfq_salesman_notified' => 0,
  2304. 'rfq_salesman_notify_time' => null,
  2305. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2306. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2307. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2308. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2309. 'createtime' => $now,
  2310. 'dStamp' => $now,
  2311. 'dputrecord' => $now,
  2312. ];
  2313. Db::table('purchase_order')->insert($data);
  2314. $poId = (int)Db::getLastInsID();
  2315. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2316. return $sid;
  2317. } finally {
  2318. $this->releaseProcuremenNamedLock($lockName);
  2319. }
  2320. }
  2321. protected function formatProcuremenRowLabel(array $row): string
  2322. {
  2323. $dh = trim((string)($row['CCYDH'] ?? ''));
  2324. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2325. if ($dh !== '' && $gymc !== '') {
  2326. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2327. }
  2328. if ($dh !== '') {
  2329. return '订单「' . $dh . '」';
  2330. }
  2331. if ($gymc !== '') {
  2332. return '工序「' . $gymc . '」';
  2333. }
  2334. $id = $this->extractScydgyRowId($row);
  2335. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2336. }
  2337. /**
  2338. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2339. */
  2340. protected function extractScydgyRowId(array $row): int
  2341. {
  2342. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2343. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2344. return (int)$row['scydgy_id'];
  2345. }
  2346. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2347. return (int)$row['SCYDGY_ID'];
  2348. }
  2349. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2350. }
  2351. protected function isValidScydgyRowId(int $id): bool
  2352. {
  2353. return ProcuremenGuard::isValidScydgyId($id);
  2354. }
  2355. protected function isManualScydgyRowId(int $id): bool
  2356. {
  2357. return $id < 0;
  2358. }
  2359. /**
  2360. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2361. *
  2362. * @param int[] $scydgyIds
  2363. * @return array<int, string[]>
  2364. */
  2365. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2366. {
  2367. $out = [];
  2368. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2369. if ($scydgyIds === []) {
  2370. return $out;
  2371. }
  2372. try {
  2373. $rows = Db::table('purchase_order_detail')
  2374. ->where('scydgy_id', 'in', $scydgyIds)
  2375. ->field('scydgy_id,company_name')
  2376. ->order('company_name', 'asc')
  2377. ->select();
  2378. } catch (\Throwable $e) {
  2379. $rows = [];
  2380. }
  2381. if (!is_array($rows)) {
  2382. return $out;
  2383. }
  2384. foreach ($rows as $r) {
  2385. if (!is_array($r)) {
  2386. continue;
  2387. }
  2388. $sid = (int)($r['scydgy_id'] ?? 0);
  2389. $cn = trim((string)($r['company_name'] ?? ''));
  2390. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2391. continue;
  2392. }
  2393. if (!isset($out[$sid])) {
  2394. $out[$sid] = [];
  2395. }
  2396. if (!in_array($cn, $out[$sid], true)) {
  2397. $out[$sid][] = $cn;
  2398. }
  2399. }
  2400. return $out;
  2401. }
  2402. /**
  2403. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2404. *
  2405. * @param string[] $names
  2406. */
  2407. protected function formatNotifySupplierDisplay(array $names): string
  2408. {
  2409. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2410. return trim((string)$n);
  2411. }, $names))));
  2412. if ($names === []) {
  2413. return '';
  2414. }
  2415. sort($names, SORT_STRING);
  2416. return implode("\n", $names);
  2417. }
  2418. /**
  2419. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2420. *
  2421. * @param int[] $scydgyIds
  2422. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2423. */
  2424. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2425. {
  2426. $out = [];
  2427. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2428. if ($scydgyIds === []) {
  2429. return $out;
  2430. }
  2431. try {
  2432. $rows = Db::table('purchase_order_detail')
  2433. ->where('scydgy_id', 'in', $scydgyIds)
  2434. ->field('scydgy_id,company_name,amount')
  2435. ->select();
  2436. } catch (\Throwable $e) {
  2437. $rows = [];
  2438. }
  2439. if (!is_array($rows)) {
  2440. return $out;
  2441. }
  2442. foreach ($rows as $r) {
  2443. if (!is_array($r)) {
  2444. continue;
  2445. }
  2446. $sid = (int)($r['scydgy_id'] ?? 0);
  2447. $cn = trim((string)($r['company_name'] ?? ''));
  2448. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2449. continue;
  2450. }
  2451. if (!isset($out[$sid])) {
  2452. $out[$sid] = ['all' => [], 'quoted' => []];
  2453. }
  2454. $out[$sid]['all'][$cn] = true;
  2455. $am = trim((string)($r['amount'] ?? ''));
  2456. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2457. $out[$sid]['quoted'][$cn] = true;
  2458. }
  2459. }
  2460. return $out;
  2461. }
  2462. /**
  2463. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2464. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2465. */
  2466. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2467. {
  2468. $merged = ['all' => [], 'quoted' => []];
  2469. foreach ($buckets as $b) {
  2470. if (!is_array($b)) {
  2471. continue;
  2472. }
  2473. foreach ($b['all'] ?? [] as $cn => $_) {
  2474. $merged['all'][$cn] = true;
  2475. }
  2476. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2477. $merged['quoted'][$cn] = true;
  2478. }
  2479. }
  2480. return $merged;
  2481. }
  2482. /**
  2483. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2484. */
  2485. protected function formatQuotedSupplierLines(array $bucket): string
  2486. {
  2487. $all = array_keys($bucket['all'] ?? []);
  2488. if ($all === []) {
  2489. return '';
  2490. }
  2491. sort($all, SORT_STRING);
  2492. $lines = [];
  2493. foreach ($all as $cn) {
  2494. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2495. $lines[] = $cn . '(' . $status . ')';
  2496. }
  2497. return implode("\n", $lines);
  2498. }
  2499. /**
  2500. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2501. */
  2502. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2503. {
  2504. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2505. $this->view->engine->layout(false);
  2506. try {
  2507. $bodyHtml = $this->view->fetch($view);
  2508. $this->view->assign('dialogBody', $bodyHtml);
  2509. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2510. return $this->view->fetch('procuremen/dialog_lite_shell');
  2511. } finally {
  2512. if ($restoreLayout) {
  2513. $this->view->engine->layout($restoreLayout);
  2514. }
  2515. }
  2516. }
  2517. /**
  2518. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2519. */
  2520. protected function resolveBundleSysRq(array $bundle): string
  2521. {
  2522. foreach ($bundle['pos'] ?? [] as $po) {
  2523. if (!is_array($po)) {
  2524. continue;
  2525. }
  2526. $sr = trim((string)($po['sys_rq'] ?? ''));
  2527. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2528. return $sr;
  2529. }
  2530. }
  2531. return '';
  2532. }
  2533. /**
  2534. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2535. */
  2536. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2537. {
  2538. $raw = trim((string)$sysRq);
  2539. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2540. return true;
  2541. }
  2542. $ts = strtotime(str_replace('T', ' ', $raw));
  2543. if ($ts === false || $ts <= 0) {
  2544. return true;
  2545. }
  2546. return time() >= $ts;
  2547. }
  2548. /**
  2549. * 开标前校验:必须已过报价截止时间
  2550. *
  2551. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2552. */
  2553. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2554. {
  2555. $sysRq = $this->resolveBundleSysRq($bundle);
  2556. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2557. $this->error('未到招标截止日期');
  2558. }
  2559. }
  2560. /**
  2561. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2562. *
  2563. * @param array<string, mixed> $d
  2564. * @param string $deliveryYmd
  2565. */
  2566. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2567. {
  2568. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2569. return max(0, (int)$d['lead_days']);
  2570. }
  2571. if ($deliveryYmd === '') {
  2572. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2573. }
  2574. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2575. return null;
  2576. }
  2577. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2578. $t2 = strtotime($m[1] . ' 00:00:00');
  2579. if ($t1 === false || $t2 === false) {
  2580. return null;
  2581. }
  2582. return max(0, (int)round(($t2 - $t1) / 86400));
  2583. }
  2584. /**
  2585. * @param int|null $days
  2586. */
  2587. protected function formatProcuremenLeadDaysText($days): string
  2588. {
  2589. if ($days === null || $days === '') {
  2590. return '未填写';
  2591. }
  2592. if (!is_numeric($days)) {
  2593. return '未填写';
  2594. }
  2595. return ((int)$days) . '天';
  2596. }
  2597. /**
  2598. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2599. *
  2600. * @param array<string, mixed> $line
  2601. */
  2602. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2603. {
  2604. $amountFilled = !empty($line['amount_filled']);
  2605. $deliveryFilled = !empty($line['delivery_filled']);
  2606. $leadFilled = !empty($line['lead_days_filled']);
  2607. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2608. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2609. $line['amount_show'] = '';
  2610. if (array_key_exists('amount_text', $line)) {
  2611. $line['amount_text'] = $line['unit_price_text'];
  2612. }
  2613. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2614. $line['delivery_show'] = $deliveryText;
  2615. if (array_key_exists('delivery_text', $line)) {
  2616. $line['delivery_text'] = $deliveryText;
  2617. }
  2618. $line['delivery_ymd'] = '';
  2619. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2620. $line['lead_days_show'] = $leadText;
  2621. $line['lead_days_text'] = $leadText;
  2622. $line['lead_days'] = '';
  2623. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2624. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2625. $line['subtotal_num'] = null;
  2626. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2627. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2628. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2629. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2630. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2631. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2632. $line['amount_filled'] = false;
  2633. $line['delivery_filled'] = false;
  2634. $line['lead_days_filled'] = false;
  2635. $line['is_quoted'] = false;
  2636. if (array_key_exists('quote_label', $line)) {
  2637. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2638. }
  2639. }
  2640. protected function ensurePurchaseOrderBidOpenTable(): void
  2641. {
  2642. static $ready = false;
  2643. if ($ready) {
  2644. return;
  2645. }
  2646. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2647. try {
  2648. if (Cache::get($cacheKey)) {
  2649. $ready = true;
  2650. return;
  2651. }
  2652. } catch (\Throwable $e) {
  2653. }
  2654. try {
  2655. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2656. $ready = true;
  2657. try {
  2658. Cache::set($cacheKey, 1, 86400);
  2659. } catch (\Throwable $e) {
  2660. }
  2661. } catch (\Throwable $e) {
  2662. Db::execute(
  2663. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2664. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2665. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2666. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2667. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2668. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2669. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2670. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2671. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2672. `createtime` datetime DEFAULT NULL,
  2673. PRIMARY KEY (`id`),
  2674. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2675. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2676. );
  2677. $ready = true;
  2678. try {
  2679. Cache::set($cacheKey, 1, 86400);
  2680. } catch (\Throwable $e2) {
  2681. }
  2682. }
  2683. }
  2684. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2685. {
  2686. $ccydh = trim($ccydh);
  2687. if ($ccydh === '') {
  2688. return false;
  2689. }
  2690. $this->ensurePurchaseOrderBidOpenTable();
  2691. try {
  2692. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2693. return is_array($row);
  2694. } catch (\Throwable $e) {
  2695. return false;
  2696. }
  2697. }
  2698. /**
  2699. * 批量查询订单是否已开标验证
  2700. *
  2701. * @param array<int, string> $ccydhs
  2702. * @return array<string, bool> ccydh => true
  2703. */
  2704. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2705. {
  2706. $set = [];
  2707. $list = [];
  2708. foreach ($ccydhs as $c) {
  2709. $c = trim((string)$c);
  2710. if ($c !== '') {
  2711. $list[$c] = true;
  2712. }
  2713. }
  2714. if ($list === []) {
  2715. return $set;
  2716. }
  2717. $this->ensurePurchaseOrderBidOpenTable();
  2718. try {
  2719. $rows = Db::table('purchase_order_bid_open')
  2720. ->where('ccydh', 'in', array_keys($list))
  2721. ->field('ccydh')
  2722. ->select();
  2723. foreach ($rows as $row) {
  2724. if (!is_array($row)) {
  2725. continue;
  2726. }
  2727. $c = trim((string)($row['ccydh'] ?? ''));
  2728. if ($c !== '') {
  2729. $set[$c] = true;
  2730. }
  2731. }
  2732. } catch (\Throwable $e) {
  2733. return [];
  2734. }
  2735. return $set;
  2736. }
  2737. /**
  2738. * 批量查询订单是否已指定供应商(免开标)
  2739. *
  2740. * @param array<int, string> $ccydhs
  2741. * @return array<string, bool> ccydh => true
  2742. */
  2743. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2744. {
  2745. $set = [];
  2746. $list = [];
  2747. foreach ($ccydhs as $c) {
  2748. $c = trim((string)$c);
  2749. if ($c !== '') {
  2750. $list[$c] = true;
  2751. }
  2752. }
  2753. if ($list === []) {
  2754. return $set;
  2755. }
  2756. $this->ensurePurchaseOrderManualPickColumns();
  2757. try {
  2758. $rows = Db::table('purchase_order')
  2759. ->where('CCYDH', 'in', array_keys($list))
  2760. ->where('manual_pick', 1)
  2761. ->field('CCYDH')
  2762. ->select();
  2763. foreach ($rows as $row) {
  2764. if (!is_array($row)) {
  2765. continue;
  2766. }
  2767. $c = trim((string)($row['CCYDH'] ?? ''));
  2768. if ($c !== '') {
  2769. $set[$c] = true;
  2770. }
  2771. }
  2772. } catch (\Throwable $e) {
  2773. return [];
  2774. }
  2775. return $set;
  2776. }
  2777. /**
  2778. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2779. *
  2780. * @param array<int, array<string, mixed>> $pool
  2781. * @return array<int, array<string, mixed>>
  2782. */
  2783. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2784. {
  2785. $status = trim($status);
  2786. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2787. return $pool;
  2788. }
  2789. $ccydhList = [];
  2790. foreach ($pool as $rw) {
  2791. if (!is_array($rw)) {
  2792. continue;
  2793. }
  2794. $c = trim((string)($rw['CCYDH'] ?? ''));
  2795. if ($c !== '') {
  2796. $ccydhList[] = $c;
  2797. }
  2798. }
  2799. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2800. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2801. $out = [];
  2802. foreach ($pool as $rw) {
  2803. if (!is_array($rw)) {
  2804. continue;
  2805. }
  2806. $c = trim((string)($rw['CCYDH'] ?? ''));
  2807. if ($c !== '' && isset($bidOpenSet[$c])) {
  2808. $t = '已开标';
  2809. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2810. $t = '已指定供应商';
  2811. } else {
  2812. $t = '待开标';
  2813. }
  2814. if ($t === $status) {
  2815. $out[] = $rw;
  2816. }
  2817. }
  2818. return $out;
  2819. }
  2820. /**
  2821. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2822. *
  2823. * @param array<string, mixed> $group
  2824. */
  2825. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2826. {
  2827. if ($quoteVisible) {
  2828. $group['remark_quote_pending'] = 0;
  2829. return;
  2830. }
  2831. $group['remark'] = '';
  2832. $group['remark_quote_pending'] = 0;
  2833. }
  2834. /**
  2835. * @param array{ccydh?:string} $bundle
  2836. */
  2837. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2838. {
  2839. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2840. }
  2841. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2842. {
  2843. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2844. return true;
  2845. }
  2846. return $this->isProcuremenManualPickedForBundle($bundle);
  2847. }
  2848. /**
  2849. * 确保 purchase_order 自选供应商字段
  2850. */
  2851. protected function ensurePurchaseOrderManualPickColumns(): void
  2852. {
  2853. static $done = false;
  2854. if ($done) {
  2855. return;
  2856. }
  2857. $done = true;
  2858. $adds = [
  2859. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2860. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2861. ];
  2862. foreach ($adds as $col => $ddl) {
  2863. try {
  2864. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2865. if (!is_array($cols) || $cols === []) {
  2866. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2867. }
  2868. } catch (\Throwable $e) {
  2869. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2870. }
  2871. }
  2872. }
  2873. /**
  2874. * 是否已自选供应商(免开标查看报价)
  2875. *
  2876. * @param array{pos?:array} $bundle
  2877. */
  2878. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2879. {
  2880. $this->ensurePurchaseOrderManualPickColumns();
  2881. foreach ($bundle['pos'] ?? [] as $poRow) {
  2882. if (!is_array($poRow)) {
  2883. continue;
  2884. }
  2885. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2886. return true;
  2887. }
  2888. }
  2889. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2890. if ($ccydh === '') {
  2891. return false;
  2892. }
  2893. try {
  2894. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2895. return $v !== null && $v !== false && (int)$v > 0;
  2896. } catch (\Throwable $e) {
  2897. return false;
  2898. }
  2899. }
  2900. /**
  2901. * @param array{pos?:array} $bundle
  2902. * @return array{company:string,reason:string}
  2903. */
  2904. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2905. {
  2906. $this->ensurePurchaseOrderManualPickColumns();
  2907. foreach ($bundle['pos'] ?? [] as $poRow) {
  2908. if (!is_array($poRow)) {
  2909. continue;
  2910. }
  2911. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2912. continue;
  2913. }
  2914. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2915. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2916. return ['company' => $cn, 'reason' => $reason];
  2917. }
  2918. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2919. if ($ccydh === '') {
  2920. return ['company' => '', 'reason' => ''];
  2921. }
  2922. try {
  2923. $row = Db::table('purchase_order')
  2924. ->where('CCYDH', $ccydh)
  2925. ->where('manual_pick', 1)
  2926. ->field('pick_company_name,manual_pick_reason')
  2927. ->order('id', 'asc')
  2928. ->find();
  2929. } catch (\Throwable $e) {
  2930. $row = null;
  2931. }
  2932. if (!is_array($row)) {
  2933. return ['company' => '', 'reason' => ''];
  2934. }
  2935. return [
  2936. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2937. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2938. ];
  2939. }
  2940. protected function loadBidOpenAdminUser(int $adminId): ?array
  2941. {
  2942. if ($adminId <= 0) {
  2943. return null;
  2944. }
  2945. try {
  2946. $row = Db::name('admin')->where('id', $adminId)->find();
  2947. } catch (\Throwable $e) {
  2948. return null;
  2949. }
  2950. if (!is_array($row)) {
  2951. return null;
  2952. }
  2953. $status = strtolower(trim((string)($row['status'] ?? '')));
  2954. if ($status !== '' && $status !== 'normal') {
  2955. return null;
  2956. }
  2957. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2958. return null;
  2959. }
  2960. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2961. if (!preg_match('/^1\d{10}$/', $phone)) {
  2962. return null;
  2963. }
  2964. $name = trim((string)($row['nickname'] ?? ''));
  2965. if ($name === '') {
  2966. $name = trim((string)($row['username'] ?? ''));
  2967. }
  2968. return [
  2969. 'id' => (int)$row['id'],
  2970. 'username' => trim((string)($row['username'] ?? '')),
  2971. 'nickname' => $name,
  2972. 'mobile' => $phone,
  2973. ];
  2974. }
  2975. /**
  2976. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2977. */
  2978. protected function bidOpenVerifierAuthGroupRootId(): int
  2979. {
  2980. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2981. return $id > 0 ? $id : 10;
  2982. }
  2983. /**
  2984. * @return int[]
  2985. */
  2986. protected function loadBidOpenVerifierAuthGroupIds(): array
  2987. {
  2988. static $memo = [];
  2989. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2990. if (isset($memo[$rootId])) {
  2991. return $memo[$rootId];
  2992. }
  2993. try {
  2994. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2995. } catch (\Throwable $e) {
  2996. $memo[$rootId] = [$rootId];
  2997. return $memo[$rootId];
  2998. }
  2999. if (!is_array($groups) || $groups === []) {
  3000. $memo[$rootId] = [$rootId];
  3001. return $memo[$rootId];
  3002. }
  3003. $groupList = [];
  3004. foreach ($groups as $g) {
  3005. if (is_array($g)) {
  3006. $groupList[] = $g;
  3007. }
  3008. }
  3009. if ($groupList === []) {
  3010. $memo[$rootId] = [$rootId];
  3011. return $memo[$rootId];
  3012. }
  3013. $tree = \fast\Tree::instance();
  3014. $tree->init($groupList);
  3015. $ids = $tree->getChildrenIds($rootId, true);
  3016. if (!is_array($ids) || $ids === []) {
  3017. $memo[$rootId] = [$rootId];
  3018. return $memo[$rootId];
  3019. }
  3020. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3021. return $memo[$rootId];
  3022. }
  3023. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3024. {
  3025. if ($adminId <= 0) {
  3026. return false;
  3027. }
  3028. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3029. if ($groupIds === []) {
  3030. return false;
  3031. }
  3032. try {
  3033. return (bool)Db::name('auth_group_access')
  3034. ->where('uid', $adminId)
  3035. ->where('group_id', 'in', $groupIds)
  3036. ->count();
  3037. } catch (\Throwable $e) {
  3038. return false;
  3039. }
  3040. }
  3041. /**
  3042. * @return array<int, array<string, mixed>>
  3043. */
  3044. protected function listBidOpenVerifierCandidates(): array
  3045. {
  3046. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3047. if ($groupIds === []) {
  3048. return [];
  3049. }
  3050. try {
  3051. $adminIds = Db::name('auth_group_access')
  3052. ->where('group_id', 'in', $groupIds)
  3053. ->column('uid');
  3054. } catch (\Throwable $e) {
  3055. $adminIds = [];
  3056. }
  3057. $adminIds = is_array($adminIds)
  3058. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3059. : [];
  3060. if ($adminIds === []) {
  3061. return [];
  3062. }
  3063. try {
  3064. $rows = Db::name('admin')
  3065. ->where('status', 'normal')
  3066. ->where('id', 'in', $adminIds)
  3067. ->where('mobile', '<>', '')
  3068. ->order('id', 'asc')
  3069. ->select();
  3070. } catch (\Throwable $e) {
  3071. return [];
  3072. }
  3073. if (!is_array($rows)) {
  3074. return [];
  3075. }
  3076. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3077. $out = [];
  3078. foreach ($rows as $row) {
  3079. if (!is_array($row)) {
  3080. continue;
  3081. }
  3082. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3083. if ($one === null) {
  3084. continue;
  3085. }
  3086. $out[] = [
  3087. 'id' => $one['id'],
  3088. 'username' => $one['username'],
  3089. 'nickname' => $one['nickname'],
  3090. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3091. 'mobile' => mask_phone($one['mobile']),
  3092. 'mobile_plain' => (string)$one['mobile'],
  3093. ];
  3094. }
  3095. return $out;
  3096. }
  3097. /**
  3098. * @param int[] $adminIds
  3099. * @return array<int, string>
  3100. */
  3101. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3102. {
  3103. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3104. if ($adminIds === []) {
  3105. return [];
  3106. }
  3107. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3108. try {
  3109. $rows = Db::name('auth_group_access')
  3110. ->alias('aga')
  3111. ->join('auth_group ag', 'aga.group_id = ag.id')
  3112. ->where('aga.uid', 'in', $adminIds)
  3113. ->where('aga.group_id', 'in', $groupIds)
  3114. ->field('aga.uid,ag.name')
  3115. ->order('aga.uid', 'asc')
  3116. ->order('aga.group_id', 'asc')
  3117. ->select();
  3118. } catch (\Throwable $e) {
  3119. return [];
  3120. }
  3121. if (!is_array($rows)) {
  3122. return [];
  3123. }
  3124. $out = [];
  3125. foreach ($rows as $row) {
  3126. if (!is_array($row)) {
  3127. continue;
  3128. }
  3129. $uid = (int)($row['uid'] ?? 0);
  3130. $name = trim((string)($row['name'] ?? ''));
  3131. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3132. continue;
  3133. }
  3134. $out[$uid] = $name;
  3135. }
  3136. return $out;
  3137. }
  3138. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3139. {
  3140. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3141. }
  3142. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3143. {
  3144. return 'procuremen_bidopen_wait_' . $adminId;
  3145. }
  3146. protected function renderBidOpenVerifySms(string $code): string
  3147. {
  3148. $tpl = '';
  3149. try {
  3150. $row = $this->loadNotifyTemplateRow('bid_open');
  3151. if (is_array($row)) {
  3152. $tpl = trim((string)($row['content'] ?? ''));
  3153. }
  3154. } catch (\Throwable $e) {
  3155. $tpl = '';
  3156. }
  3157. if ($tpl === '') {
  3158. $tpl = '【可集达】您的短信验证码是{code}';
  3159. }
  3160. return str_replace('{code}', $code, $tpl);
  3161. }
  3162. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3163. {
  3164. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3165. }
  3166. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3167. {
  3168. $code = trim($code);
  3169. if (!preg_match('/^\d{6}$/', $code)) {
  3170. return false;
  3171. }
  3172. $mock = Config::get('mproc.mock_sms_code');
  3173. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3174. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3175. return true;
  3176. }
  3177. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3178. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3179. return false;
  3180. }
  3181. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3182. return true;
  3183. }
  3184. /**
  3185. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3186. */
  3187. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3188. {
  3189. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3190. if ($ccydh === '') {
  3191. throw new \InvalidArgumentException('订单号无效');
  3192. }
  3193. $this->ensurePurchaseOrderBidOpenTable();
  3194. list($operatorId, $operatorName) = $this->GetUseName();
  3195. $now = date('Y-m-d H:i:s');
  3196. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3197. $payload = [
  3198. 'ccydh' => $ccydh,
  3199. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3200. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3201. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3202. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3203. 'operator_id' => (int)$operatorId,
  3204. 'operator_name' => trim((string)$operatorName),
  3205. 'createtime' => $now,
  3206. ];
  3207. if (is_array($exists)) {
  3208. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3209. } else {
  3210. Db::table('purchase_order_bid_open')->insert($payload);
  3211. }
  3212. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3213. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3214. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3215. (int)$payload['verifier1_id'],
  3216. (int)$payload['verifier2_id'],
  3217. ]);
  3218. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3219. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3220. }
  3221. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3222. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3223. }
  3224. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3225. $seenSid = [];
  3226. foreach ($bundle['pos'] ?? [] as $poRow) {
  3227. if (!is_array($poRow)) {
  3228. continue;
  3229. }
  3230. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3231. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3232. continue;
  3233. }
  3234. $seenSid[$sid] = true;
  3235. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3236. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3237. }
  3238. if ($seenSid === []) {
  3239. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3240. if ($this->isValidScydgyRowId($anchor)) {
  3241. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3242. }
  3243. }
  3244. // 开标通过后计算并写入供应商服务评分
  3245. try {
  3246. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3247. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3248. } catch (\Throwable $e) {
  3249. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3250. }
  3251. }
  3252. /**
  3253. * 报价行展示字段默认值(模板安全访问)
  3254. *
  3255. * @param array<string, mixed> $line
  3256. * @return array<string, mixed>
  3257. */
  3258. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3259. {
  3260. if (!array_key_exists('amount_quote_pending', $line)) {
  3261. $line['amount_quote_pending'] = 0;
  3262. }
  3263. if (!array_key_exists('delivery_quote_pending', $line)) {
  3264. $line['delivery_quote_pending'] = 0;
  3265. }
  3266. if (!array_key_exists('quote_before_deadline', $line)) {
  3267. $line['quote_before_deadline'] = 0;
  3268. }
  3269. if (!array_key_exists('amount_filled', $line)) {
  3270. $line['amount_filled'] = 0;
  3271. }
  3272. if (!array_key_exists('delivery_filled', $line)) {
  3273. $line['delivery_filled'] = 0;
  3274. }
  3275. if (!array_key_exists('lead_days_filled', $line)) {
  3276. $line['lead_days_filled'] = 0;
  3277. }
  3278. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3279. $line['lead_days_quote_pending'] = 0;
  3280. }
  3281. if (!array_key_exists('lead_days_show', $line)) {
  3282. $line['lead_days_show'] = '未填写';
  3283. }
  3284. if (!array_key_exists('lead_days_text', $line)) {
  3285. $line['lead_days_text'] = $line['lead_days_show'];
  3286. }
  3287. return $line;
  3288. }
  3289. /**
  3290. * 审核弹窗:按供应商汇总报价明细
  3291. *
  3292. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3293. * @return array<int, array<string, mixed>>
  3294. */
  3295. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3296. {
  3297. $sids = [];
  3298. foreach ($bundle['pos'] ?? [] as $po) {
  3299. if (!is_array($po)) {
  3300. continue;
  3301. }
  3302. $sid = (int)($po['scydgy_id'] ?? 0);
  3303. if ($this->isValidScydgyRowId($sid)) {
  3304. $sids[$sid] = true;
  3305. }
  3306. }
  3307. if ($sids === []) {
  3308. return [];
  3309. }
  3310. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3311. $gymcMap = [];
  3312. $qtyBySid = [];
  3313. $orderedSids = [];
  3314. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3315. if (!is_array($mr)) {
  3316. continue;
  3317. }
  3318. $gid = $this->extractScydgyRowId($mr);
  3319. if ($this->isValidScydgyRowId($gid)) {
  3320. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3321. $orderedSids[] = $gid;
  3322. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3323. if ($qty === '') {
  3324. $qty = trim((string)($mr['NGZL'] ?? ''));
  3325. }
  3326. $qtyBySid[$gid] = $qty;
  3327. }
  3328. }
  3329. foreach ($bundle['pos'] ?? [] as $po) {
  3330. if (!is_array($po)) {
  3331. continue;
  3332. }
  3333. $gid = (int)($po['scydgy_id'] ?? 0);
  3334. if ($this->isValidScydgyRowId($gid)) {
  3335. $nm = trim((string)($po['CGYMC'] ?? ''));
  3336. if ($nm !== '') {
  3337. $gymcMap[$gid] = $nm;
  3338. }
  3339. if (!in_array($gid, $orderedSids, true)) {
  3340. $orderedSids[] = $gid;
  3341. }
  3342. }
  3343. }
  3344. try {
  3345. $detailsQuery = Db::table('purchase_order_detail')
  3346. ->where('scydgy_id', 'in', array_keys($sids));
  3347. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3348. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3349. } catch (\Throwable $e) {
  3350. try {
  3351. $detailsQuery = Db::table('purchase_order_detail')
  3352. ->where('scydgy_id', 'in', array_keys($sids));
  3353. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3354. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3355. } catch (\Throwable $e2) {
  3356. $details = [];
  3357. }
  3358. }
  3359. if (!is_array($details)) {
  3360. $details = [];
  3361. }
  3362. $byCompany = [];
  3363. foreach ($details as $d) {
  3364. if (!is_array($d)) {
  3365. continue;
  3366. }
  3367. $cn = trim((string)($d['company_name'] ?? ''));
  3368. if ($cn === '') {
  3369. continue;
  3370. }
  3371. if (!isset($byCompany[$cn])) {
  3372. $ph = trim((string)($d['phone'] ?? ''));
  3373. $username = trim((string)($d['username'] ?? ''));
  3374. if ($username === '') {
  3375. $username = $this->resolveCustomerContactName($ph, $cn);
  3376. }
  3377. $byCompany[$cn] = [
  3378. 'name' => $cn,
  3379. 'email' => trim((string)($d['email'] ?? '')),
  3380. 'phone' => $ph,
  3381. 'username' => $username,
  3382. 'remark' => '',
  3383. 'has_quote' => false,
  3384. 'lines_map' => [],
  3385. ];
  3386. }
  3387. if ($byCompany[$cn]['remark'] === '') {
  3388. $rm = '';
  3389. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3390. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3391. $rm = trim((string)$d[$rk]);
  3392. break;
  3393. }
  3394. }
  3395. if ($rm !== '') {
  3396. $byCompany[$cn]['remark'] = $rm;
  3397. }
  3398. }
  3399. $sid = (int)($d['scydgy_id'] ?? 0);
  3400. $am = trim((string)($d['amount'] ?? ''));
  3401. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3402. if ($gymc === '') {
  3403. $gymc = '工序';
  3404. }
  3405. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3406. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3407. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3408. $deliveryShow = $deliveryRaw;
  3409. }
  3410. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3411. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3412. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3413. $subtotal = null;
  3414. if ($amountNum !== null) {
  3415. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3416. }
  3417. $unitPriceText = $amountFilled
  3418. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3419. : '未填写';
  3420. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3421. $leadFilled = ($leadDays !== null);
  3422. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3423. $lineRow = [
  3424. 'cgymc' => $gymc,
  3425. 'amount' => $am,
  3426. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3427. 'amount_filled' => $amountFilled,
  3428. 'unit_price_text' => $unitPriceText,
  3429. 'delivery' => $deliveryRaw,
  3430. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3431. 'delivery_filled' => $deliveryFilled,
  3432. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3433. 'lead_days' => $leadFilled ? $leadDays : '',
  3434. 'lead_days_filled'=> $leadFilled,
  3435. 'lead_days_show' => $leadText,
  3436. 'lead_days_text' => $leadText,
  3437. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3438. 'subtotal_num' => $subtotal,
  3439. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3440. 'is_quoted' => $amountFilled,
  3441. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3442. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3443. ];
  3444. if (!$quoteVisible) {
  3445. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3446. }
  3447. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3448. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3449. }
  3450. foreach ($byCompany as $cn => $g) {
  3451. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3452. $lines = [];
  3453. $usedSids = [];
  3454. foreach ($orderedSids as $sid) {
  3455. if (!isset($linesMap[$sid])) {
  3456. continue;
  3457. }
  3458. $lines[] = $linesMap[$sid];
  3459. $usedSids[$sid] = true;
  3460. }
  3461. foreach ($linesMap as $sid => $ln) {
  3462. if (isset($usedSids[$sid])) {
  3463. continue;
  3464. }
  3465. $lines[] = $ln;
  3466. }
  3467. $total = count($lines);
  3468. $quoted = 0;
  3469. $groupTotal = 0.0;
  3470. $groupHasTotal = false;
  3471. if ($quoteVisible) {
  3472. foreach ($lines as $ln) {
  3473. $am = trim((string)($ln['amount'] ?? ''));
  3474. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3475. $quoted++;
  3476. }
  3477. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3478. $groupTotal += (float)$ln['subtotal_num'];
  3479. $groupHasTotal = true;
  3480. }
  3481. }
  3482. }
  3483. unset($byCompany[$cn]['lines_map']);
  3484. $byCompany[$cn]['lines'] = $lines;
  3485. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3486. $byCompany[$cn]['line_count'] = $total;
  3487. $byCompany[$cn]['has_total'] = $total > 0;
  3488. $byCompany[$cn]['has_remark'] = $total > 0;
  3489. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3490. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3491. // 工序行 + 备注行 + 总计行
  3492. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3493. }
  3494. $groups = array_values($byCompany);
  3495. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3496. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3497. }
  3498. /**
  3499. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3500. *
  3501. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3502. * @return array<int, array<string, mixed>>
  3503. */
  3504. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3505. {
  3506. $sids = [];
  3507. $poIdMap = [];
  3508. foreach ($bundle['pos'] ?? [] as $po) {
  3509. if (!is_array($po)) {
  3510. continue;
  3511. }
  3512. $sid = (int)($po['scydgy_id'] ?? 0);
  3513. if ($this->isValidScydgyRowId($sid)) {
  3514. $sids[$sid] = true;
  3515. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3516. }
  3517. }
  3518. if ($sids === []) {
  3519. return [];
  3520. }
  3521. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3522. $gymcMap = [];
  3523. $qtyBySid = [];
  3524. $orderedSids = [];
  3525. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3526. if (!is_array($mr)) {
  3527. continue;
  3528. }
  3529. $gid = $this->extractScydgyRowId($mr);
  3530. if ($this->isValidScydgyRowId($gid)) {
  3531. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3532. $orderedSids[] = $gid;
  3533. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3534. if ($qty === '') {
  3535. $qty = trim((string)($mr['NGZL'] ?? ''));
  3536. }
  3537. $qtyBySid[$gid] = $qty;
  3538. }
  3539. }
  3540. foreach ($bundle['pos'] ?? [] as $po) {
  3541. if (!is_array($po)) {
  3542. continue;
  3543. }
  3544. $gid = (int)($po['scydgy_id'] ?? 0);
  3545. if ($this->isValidScydgyRowId($gid)) {
  3546. $nm = trim((string)($po['CGYMC'] ?? ''));
  3547. if ($nm !== '') {
  3548. $gymcMap[$gid] = $nm;
  3549. }
  3550. }
  3551. }
  3552. try {
  3553. $details = Db::table('purchase_order_detail')
  3554. ->where('scydgy_id', 'in', array_keys($sids))
  3555. ->order('company_name', 'asc')
  3556. ->order('id', 'asc')
  3557. ->select();
  3558. } catch (\Throwable $e) {
  3559. try {
  3560. $details = Db::table('purchase_order_detail')
  3561. ->where('scydgy_id', 'in', array_keys($sids))
  3562. ->order('company_name', 'asc')
  3563. ->order('ID', 'asc')
  3564. ->select();
  3565. } catch (\Throwable $e2) {
  3566. $details = [];
  3567. }
  3568. }
  3569. if (!is_array($details)) {
  3570. $details = [];
  3571. }
  3572. $byCompany = [];
  3573. foreach ($details as $d) {
  3574. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3575. continue;
  3576. }
  3577. $cn = trim((string)($d['company_name'] ?? ''));
  3578. if ($cn === '') {
  3579. continue;
  3580. }
  3581. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3582. $sid = (int)($d['scydgy_id'] ?? 0);
  3583. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3584. continue;
  3585. }
  3586. if (!isset($byCompany[$cn])) {
  3587. $ph = trim((string)($d['phone'] ?? ''));
  3588. $username = trim((string)($d['username'] ?? ''));
  3589. if ($username === '') {
  3590. $username = $this->resolveCustomerContactName($ph, $cn);
  3591. }
  3592. $byCompany[$cn] = [
  3593. 'name' => $cn,
  3594. 'email' => trim((string)($d['email'] ?? '')),
  3595. 'phone' => $ph,
  3596. 'username' => $username,
  3597. 'remark' => '',
  3598. 'pick_lines' => [],
  3599. 'detail_picks' => [],
  3600. ];
  3601. }
  3602. if ($byCompany[$cn]['remark'] === '') {
  3603. $rm = '';
  3604. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3605. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3606. $rm = trim((string)$d[$rk]);
  3607. break;
  3608. }
  3609. }
  3610. if ($rm !== '') {
  3611. $byCompany[$cn]['remark'] = $rm;
  3612. }
  3613. }
  3614. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3615. if ($gymc === '') {
  3616. $gymc = '工序';
  3617. }
  3618. $am = trim((string)($d['amount'] ?? ''));
  3619. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3620. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3621. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3622. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3623. $deliveryShow = $deliveryRaw;
  3624. }
  3625. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3626. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3627. $subtotal = null;
  3628. if ($amountNum !== null) {
  3629. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3630. }
  3631. $unitPriceText = $amountFilled
  3632. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3633. : '未填写';
  3634. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3635. $leadFilled = ($leadDays !== null);
  3636. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3637. $pickLine = [
  3638. 'cgymc' => $gymc,
  3639. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3640. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3641. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3642. 'amount_filled' => $amountFilled,
  3643. 'delivery_filled' => $deliveryFilled,
  3644. 'unit_price_text' => $unitPriceText,
  3645. 'lead_days' => $leadFilled ? $leadDays : '',
  3646. 'lead_days_filled'=> $leadFilled,
  3647. 'lead_days_show' => $leadText,
  3648. 'lead_days_text' => $leadText,
  3649. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3650. 'subtotal_num' => $subtotal,
  3651. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3652. 'is_quoted' => $amountFilled,
  3653. ];
  3654. if (!$quoteVisible) {
  3655. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3656. }
  3657. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3658. $byCompany[$cn]['detail_picks'][$sid] = [
  3659. 'scydgy_id' => $sid,
  3660. 'detail_id' => $detailId,
  3661. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3662. 'cgymc' => $gymc,
  3663. ];
  3664. }
  3665. $out = [];
  3666. foreach ($byCompany as $g) {
  3667. $pickLinesMap = $g['pick_lines'] ?? [];
  3668. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3669. continue;
  3670. }
  3671. $pickLines = [];
  3672. $usedLineSids = [];
  3673. foreach ($orderedSids as $sid) {
  3674. if (!isset($pickLinesMap[$sid])) {
  3675. continue;
  3676. }
  3677. $pickLines[] = $pickLinesMap[$sid];
  3678. $usedLineSids[$sid] = true;
  3679. }
  3680. foreach ($pickLinesMap as $sid => $ln) {
  3681. if (isset($usedLineSids[$sid])) {
  3682. continue;
  3683. }
  3684. $pickLines[] = $ln;
  3685. }
  3686. $groupTotal = 0.0;
  3687. $groupHasTotal = false;
  3688. if ($quoteVisible) {
  3689. foreach ($pickLines as $ln) {
  3690. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3691. $groupTotal += (float)$ln['subtotal_num'];
  3692. $groupHasTotal = true;
  3693. }
  3694. }
  3695. }
  3696. $lineCount = count($pickLines);
  3697. $g['pick_lines'] = $pickLines;
  3698. $g['line_count'] = $lineCount;
  3699. $g['has_total'] = $lineCount > 0;
  3700. $g['has_remark'] = $lineCount > 0;
  3701. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3702. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3703. // 工序行 + 备注行 + 总计行
  3704. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3705. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3706. $detailPicks = [];
  3707. $usedPickSids = [];
  3708. foreach ($orderedSids as $sid) {
  3709. if (!isset($detailPicksMap[$sid])) {
  3710. continue;
  3711. }
  3712. $detailPicks[] = $detailPicksMap[$sid];
  3713. $usedPickSids[$sid] = true;
  3714. }
  3715. foreach ($detailPicksMap as $sid => $dp) {
  3716. if (isset($usedPickSids[$sid])) {
  3717. continue;
  3718. }
  3719. $detailPicks[] = $dp;
  3720. }
  3721. $g['detail_picks'] = $detailPicks;
  3722. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3723. unset($g['detail_picks']);
  3724. $out[] = $g;
  3725. }
  3726. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3727. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3728. }
  3729. /**
  3730. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3731. * @return array<int, int[]> scydgy_id => detail_id[]
  3732. */
  3733. protected function mapDetailIdsByScydgyId(array $details): array
  3734. {
  3735. $out = [];
  3736. foreach ($details as $d) {
  3737. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3738. continue;
  3739. }
  3740. $sid = (int)($d['scydgy_id'] ?? 0);
  3741. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3742. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3743. continue;
  3744. }
  3745. if (!isset($out[$sid])) {
  3746. $out[$sid] = [];
  3747. }
  3748. $out[$sid][] = $pk;
  3749. }
  3750. foreach ($out as $sid => $ids) {
  3751. $out[$sid] = array_values(array_unique($ids));
  3752. }
  3753. return $out;
  3754. }
  3755. /**
  3756. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3757. *
  3758. * @param array<string, mixed> $dbRow
  3759. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3760. */
  3761. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3762. {
  3763. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3764. $r = [
  3765. 'ID' => $sid,
  3766. 'scydgy_id' => $sid,
  3767. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3768. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3769. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3770. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3771. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3772. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3773. 'CDW' => $dbRow['CDW'] ?? '',
  3774. 'czlyq' => $dbRow['czlyq'] ?? '',
  3775. 'NGZL' => $dbRow['NGZL'] ?? '',
  3776. 'CDF' => $dbRow['CDF'] ?? '',
  3777. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3778. 'MBZ' => $dbRow['MBZ'] ?? '',
  3779. 'bwjg' => $dbRow['bwjg'] ?? '',
  3780. 'iStatus' => $dbRow['iStatus'] ?? '',
  3781. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3782. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3783. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3784. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3785. 'dStamp' => $dbRow['dStamp'] ?? '',
  3786. 'pick_time' => $dbRow['pick_time'] ?? '',
  3787. ];
  3788. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3789. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3790. if ($sid > 0 && isset($dStampMap[$sid])) {
  3791. $t = trim((string)$dStampMap[$sid]);
  3792. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3793. $r['dStamp'] = $dStampMap[$sid];
  3794. }
  3795. }
  3796. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3797. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3798. $ct = $dbRow['createtime'];
  3799. if (is_numeric($ct) && (int)$ct > 946684800) {
  3800. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3801. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3802. $r['dStamp'] = trim($ct);
  3803. }
  3804. }
  3805. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3806. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3807. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3808. $fallback = trim((string)($r['dStamp'] ?? ''));
  3809. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3810. $r['dputrecord'] = $fallback;
  3811. }
  3812. }
  3813. if (array_key_exists('id', $dbRow)) {
  3814. $r['purchase_order_id'] = (int)$dbRow['id'];
  3815. }
  3816. if ($sid < 0) {
  3817. $r['_is_manual'] = 1;
  3818. }
  3819. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3820. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3821. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3822. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3823. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3824. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3825. $r['pick_time'] = $pickFallback;
  3826. break;
  3827. }
  3828. }
  3829. }
  3830. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3831. if ($pickNm !== '') {
  3832. $r['pick_company_name'] = $pickNm;
  3833. $r['picked_supplier_name'] = $pickNm;
  3834. }
  3835. return $r;
  3836. }
  3837. /**
  3838. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3839. *
  3840. * @return array<int, array<string, mixed>>
  3841. */
  3842. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3843. {
  3844. $pool = [];
  3845. if (!is_array($dbRows) || $dbRows === []) {
  3846. return $pool;
  3847. }
  3848. $dStampMap = [];
  3849. $sidList = [];
  3850. foreach ($dbRows as $tmpRow) {
  3851. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3852. $sid = (int)$tmpRow['scydgy_id'];
  3853. if ($sid > 0) {
  3854. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3855. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3856. $sidList[$sid] = true;
  3857. }
  3858. }
  3859. }
  3860. }
  3861. if ($sidList !== []) {
  3862. try {
  3863. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3864. } catch (\Throwable $e) {
  3865. $dStampMap = [];
  3866. }
  3867. }
  3868. foreach ($dbRows as $dbRow) {
  3869. if (!is_array($dbRow)) {
  3870. continue;
  3871. }
  3872. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3873. }
  3874. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3875. $needCcydh = [];
  3876. foreach ($pool as $row) {
  3877. if (!is_array($row)) {
  3878. continue;
  3879. }
  3880. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3881. continue;
  3882. }
  3883. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3884. if ($ccydh !== '') {
  3885. $needCcydh[$ccydh] = true;
  3886. }
  3887. }
  3888. if ($needCcydh !== []) {
  3889. $czMap = [];
  3890. try {
  3891. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3892. } catch (\Throwable $e) {
  3893. $czMap = [];
  3894. }
  3895. if (is_array($czMap) && $czMap !== []) {
  3896. foreach ($pool as &$row) {
  3897. if (!is_array($row)) {
  3898. continue;
  3899. }
  3900. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3901. continue;
  3902. }
  3903. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3904. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3905. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3906. }
  3907. }
  3908. unset($row);
  3909. }
  3910. }
  3911. return $pool;
  3912. }
  3913. /**
  3914. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3915. *
  3916. * @param int[] $scydgyIds
  3917. * @return array<int, array<string, mixed>>
  3918. */
  3919. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3920. {
  3921. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3922. if ($scydgyIds === []) {
  3923. return [];
  3924. }
  3925. try {
  3926. $list = Db::table('purchase_order_detail')
  3927. ->where('scydgy_id', 'in', $scydgyIds)
  3928. ->field('scydgy_id,company_name,amount,delivery')
  3929. ->select();
  3930. } catch (\Throwable $e) {
  3931. $list = [];
  3932. }
  3933. return is_array($list) ? $list : [];
  3934. }
  3935. /**
  3936. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3937. *
  3938. * @param int[] $scydgyIds
  3939. * @param array<int, array<string, mixed>> $allRows
  3940. * @return array{cnt:int, amt:int, deliv:int}
  3941. */
  3942. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3943. {
  3944. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3945. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3946. if ($scydgyIds === [] || $allRows === []) {
  3947. return $out;
  3948. }
  3949. $idSet = array_flip($scydgyIds);
  3950. $all = [];
  3951. $withAmt = [];
  3952. $withDeliv = [];
  3953. foreach ($allRows as $r) {
  3954. if (!is_array($r)) {
  3955. continue;
  3956. }
  3957. $sid = (int)($r['scydgy_id'] ?? 0);
  3958. if (!isset($idSet[$sid])) {
  3959. continue;
  3960. }
  3961. $cn = trim((string)($r['company_name'] ?? ''));
  3962. if ($cn === '') {
  3963. continue;
  3964. }
  3965. $all[$cn] = true;
  3966. $am = $r['amount'] ?? null;
  3967. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3968. $withAmt[$cn] = true;
  3969. }
  3970. $dv = $r['delivery'] ?? null;
  3971. if ($dv !== null && trim((string)$dv) !== '') {
  3972. $withDeliv[$cn] = true;
  3973. }
  3974. }
  3975. return [
  3976. 'cnt' => count($all),
  3977. 'amt' => count($withAmt),
  3978. 'deliv' => count($withDeliv),
  3979. ];
  3980. }
  3981. /**
  3982. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3983. *
  3984. * @param array<string, mixed> $row
  3985. */
  3986. protected function resolveProcuremenThisQuantity(array $row): string
  3987. {
  3988. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3989. if ($q !== '') {
  3990. return $q;
  3991. }
  3992. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3993. if (!is_scalar($ngzl)) {
  3994. return '';
  3995. }
  3996. $s = trim((string)$ngzl);
  3997. if ($s === '') {
  3998. return '';
  3999. }
  4000. if (is_numeric($s) && (float)$s === 0.0) {
  4001. return '';
  4002. }
  4003. return $s;
  4004. }
  4005. /**
  4006. * @param array<string, mixed> $row
  4007. */
  4008. protected function resolveProcuremenCeilingPrice(array $row): string
  4009. {
  4010. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4011. }
  4012. /**
  4013. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4014. *
  4015. * @param array<int, mixed> $parts
  4016. */
  4017. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4018. {
  4019. $out = [];
  4020. foreach ($parts as $p) {
  4021. $s = trim((string)$p);
  4022. if ($s !== '') {
  4023. $out[] = $s;
  4024. }
  4025. }
  4026. return $out === [] ? '' : implode($sep, $out);
  4027. }
  4028. /**
  4029. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4030. *
  4031. * @param array<int, array<string, mixed>> $rows
  4032. */
  4033. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4034. {
  4035. if ($rows === []) {
  4036. return;
  4037. }
  4038. $idList = [];
  4039. foreach ($rows as $rw) {
  4040. if (!is_array($rw)) {
  4041. continue;
  4042. }
  4043. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4044. foreach ($rw['_order_merge_rows'] as $mr) {
  4045. if (!is_array($mr)) {
  4046. continue;
  4047. }
  4048. $mid = (int)($mr['ID'] ?? 0);
  4049. if ($this->isValidScydgyRowId($mid)) {
  4050. $idList[$mid] = true;
  4051. }
  4052. }
  4053. }
  4054. $id = (int)($rw['ID'] ?? 0);
  4055. if ($this->isValidScydgyRowId($id)) {
  4056. $idList[$id] = true;
  4057. }
  4058. }
  4059. if ($idList === []) {
  4060. return;
  4061. }
  4062. try {
  4063. $list = Db::table('purchase_order')
  4064. ->where('scydgy_id', 'in', array_keys($idList))
  4065. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4066. ->select();
  4067. } catch (\Throwable $e) {
  4068. return;
  4069. }
  4070. if (!is_array($list)) {
  4071. return;
  4072. }
  4073. $byId = [];
  4074. foreach ($list as $dbRow) {
  4075. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4076. continue;
  4077. }
  4078. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4079. }
  4080. foreach ($rows as &$rw) {
  4081. if (!is_array($rw)) {
  4082. continue;
  4083. }
  4084. $mergeRows = [];
  4085. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4086. $mergeRows = $rw['_order_merge_rows'];
  4087. } else {
  4088. $mergeRows = [$rw];
  4089. }
  4090. $qtyList = [];
  4091. $priceList = [];
  4092. $picked = '';
  4093. foreach ($mergeRows as $mr) {
  4094. if (!is_array($mr)) {
  4095. continue;
  4096. }
  4097. $sid = (int)($mr['ID'] ?? 0);
  4098. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4099. $src = $mr;
  4100. if (is_array($db)) {
  4101. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4102. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4103. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4104. if ($qDb !== '') {
  4105. $src['This_quantity'] = $qDb;
  4106. }
  4107. if ($pDb !== '') {
  4108. $src['ceilingPrice'] = $pDb;
  4109. }
  4110. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4111. $src['NGZL'] = $ngzlDb;
  4112. }
  4113. if ($picked === '') {
  4114. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4115. }
  4116. }
  4117. if ($picked === '') {
  4118. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4119. }
  4120. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4121. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4122. }
  4123. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4124. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4125. if ($picked !== '') {
  4126. $rw['pick_company_name'] = $picked;
  4127. $rw['picked_supplier_name'] = $picked;
  4128. }
  4129. }
  4130. unset($rw);
  4131. }
  4132. /**
  4133. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4134. *
  4135. * @param int[] $scydgyIds
  4136. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4137. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4138. */
  4139. protected function OrderDetailSummary(array $scydgyIds)
  4140. {
  4141. $out = [];
  4142. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4143. if ($scydgyIds === []) {
  4144. return $out;
  4145. }
  4146. $list = [];
  4147. try {
  4148. $list = Db::table('purchase_order_detail')
  4149. ->where('scydgy_id', 'in', $scydgyIds)
  4150. ->field('id,scydgy_id,amount,delivery')
  4151. ->select();
  4152. } catch (\Throwable $e) {
  4153. $list = [];
  4154. }
  4155. if (!is_array($list)) {
  4156. return $out;
  4157. }
  4158. foreach ($list as $r) {
  4159. if (!is_array($r)) {
  4160. continue;
  4161. }
  4162. $ids = (int)($r['scydgy_id'] ?? 0);
  4163. if (!$this->isValidScydgyRowId($ids)) {
  4164. continue;
  4165. }
  4166. if (!isset($out[$ids])) {
  4167. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4168. }
  4169. $out[$ids]['cnt']++;
  4170. $am = $r['amount'] ?? null;
  4171. if ($am !== null && $am !== '') {
  4172. if (!(is_string($am) && trim($am) === '')) {
  4173. $out[$ids]['amt']++;
  4174. }
  4175. }
  4176. $dv = $r['delivery'] ?? null;
  4177. if ($dv !== null && trim((string)$dv) !== '') {
  4178. $out[$ids]['deliv']++;
  4179. }
  4180. }
  4181. return $out;
  4182. }
  4183. /**
  4184. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4185. *
  4186. * @return array
  4187. */
  4188. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4189. {
  4190. $strContains = function ($haystack, $needle) {
  4191. if ($needle === '') {
  4192. return false;
  4193. }
  4194. $haystack = (string)$haystack;
  4195. if (function_exists('mb_stripos')) {
  4196. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4197. }
  4198. return stripos($haystack, $needle) !== false;
  4199. };
  4200. $stripAlias = function ($f) {
  4201. return preg_replace('/^[ab]\./i', '', (string)$f);
  4202. };
  4203. $searchColNames = [];
  4204. foreach (explode(',', $this->searchFields) as $colRaw) {
  4205. $c = $stripAlias(trim($colRaw));
  4206. if ($c !== '') {
  4207. $searchColNames[] = $c;
  4208. }
  4209. }
  4210. // 等值条件先行(表头下拉),减少后续日期解析量
  4211. $eqFilters = [];
  4212. $otherFilters = [];
  4213. foreach ($filterArr as $fk => $fv) {
  4214. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4215. continue;
  4216. }
  4217. if (is_array($fv)) {
  4218. continue;
  4219. }
  4220. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4221. continue;
  4222. }
  4223. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4224. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4225. $field = $stripAlias($fk);
  4226. if ($sym === '=' || $sym === '') {
  4227. $eqFilters[$field] = trim((string)$fv);
  4228. } else {
  4229. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4230. }
  4231. }
  4232. $ymTarget = '';
  4233. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4234. $ymTarget = $ymM[1];
  4235. }
  4236. $filtered = [];
  4237. foreach ($pool as $r) {
  4238. if (!is_array($r)) {
  4239. continue;
  4240. }
  4241. foreach ($eqFilters as $field => $fv) {
  4242. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4243. continue 2;
  4244. }
  4245. }
  4246. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4247. // 初选池不应含手工单;若混入则直接剔除
  4248. if ($isManual) {
  4249. continue;
  4250. }
  4251. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4252. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4253. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4254. continue;
  4255. }
  4256. if ($applyMonthRange) {
  4257. $mo = (int)$m[2];
  4258. if ($mo < 1 || $mo > 12) {
  4259. continue;
  4260. }
  4261. if ($ymTarget !== '') {
  4262. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4263. if ($ymRow !== $ymTarget) {
  4264. continue;
  4265. }
  4266. } else {
  4267. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4268. $rowMonthStart = $ymRow . '-01 00:00:00';
  4269. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4270. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4271. continue;
  4272. }
  4273. }
  4274. }
  4275. if ($search !== '') {
  4276. $hitSearch = false;
  4277. foreach ($searchColNames as $c) {
  4278. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4279. if ($cell !== '' && $strContains($cell, $search)) {
  4280. $hitSearch = true;
  4281. break;
  4282. }
  4283. }
  4284. if (!$hitSearch) {
  4285. continue;
  4286. }
  4287. }
  4288. foreach ($otherFilters as $item) {
  4289. $fv = $item['fv'];
  4290. $sym = $item['sym'];
  4291. $field = $item['field'];
  4292. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4293. $cellStr = trim((string)$cell);
  4294. switch ($sym) {
  4295. case '<>':
  4296. if ((string)$cell === (string)$fv) {
  4297. continue 3;
  4298. }
  4299. break;
  4300. case 'LIKE':
  4301. case 'NOT LIKE':
  4302. $needle = trim((string)$fv);
  4303. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4304. if ($sym === 'LIKE' && !$hit) {
  4305. continue 3;
  4306. }
  4307. if ($sym === 'NOT LIKE' && $hit) {
  4308. continue 3;
  4309. }
  4310. break;
  4311. case 'BETWEEN':
  4312. case 'RANGE':
  4313. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4314. if (count($parts) < 2) {
  4315. $parts = is_string($fv) ? explode(',', $fv) : [];
  4316. }
  4317. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4318. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4319. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4320. continue 3;
  4321. }
  4322. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4323. continue 3;
  4324. }
  4325. break;
  4326. case '>':
  4327. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4328. continue 3;
  4329. }
  4330. break;
  4331. case '>=':
  4332. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4333. continue 3;
  4334. }
  4335. break;
  4336. case '<':
  4337. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4338. continue 3;
  4339. }
  4340. break;
  4341. case '<=':
  4342. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4343. continue 3;
  4344. }
  4345. break;
  4346. default:
  4347. if ((string)$cell !== (string)$fv) {
  4348. continue 3;
  4349. }
  4350. break;
  4351. }
  4352. }
  4353. $filtered[] = $r;
  4354. }
  4355. return $filtered;
  4356. }
  4357. /**
  4358. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4359. */
  4360. public function snapshotToProcure()
  4361. {
  4362. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4363. $this->error(__('Invalid parameters'));
  4364. }
  4365. $row = json_decode($this->request->post('row_json', ''), true);
  4366. if (!is_array($row)) {
  4367. $this->error(__('Invalid parameters'));
  4368. }
  4369. try {
  4370. $ids = $this->extractScydgyRowId($row);
  4371. if (!$this->isValidScydgyRowId($ids)) {
  4372. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4373. }
  4374. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4375. $data = [
  4376. 'scydgy_id' => $ids,
  4377. 'CCYDH' => $row['CCYDH'] ?? null,
  4378. 'CYJMC' => $row['CYJMC'] ?? null,
  4379. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4380. 'CDXMC' => $row['CDXMC'] ?? null,
  4381. 'CGYBH' => $row['CGYBH'] ?? null,
  4382. 'CGYMC' => $row['CGYMC'] ?? null,
  4383. 'CDW' => $row['CDW'] ?? null,
  4384. 'czlyq' => $row['czlyq'] ?? null,
  4385. 'NGZL' => $row['NGZL'] ?? null,
  4386. 'CDF' => $row['CDF'] ?? null,
  4387. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4388. 'MBZ' => $row['MBZ'] ?? null,
  4389. 'bwjg' => $row['bwjg'] ?? null,
  4390. 'iStatus' => $row['iStatus'] ?? null,
  4391. 'dStamp' => $row['dStamp'] ?? null,
  4392. 'dputrecord' => $row['dputrecord'] ?? null,
  4393. 'cywyxm' => $row['cywyxm'] ?? null,
  4394. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4395. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4396. ];
  4397. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4398. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4399. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4400. $this->success('操作成功');
  4401. return;
  4402. }
  4403. if ($exists) {
  4404. $upd = $data;
  4405. unset($upd['scydgy_id'], $upd['status']);
  4406. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4407. } else {
  4408. // 新增:不写 status(空/走库默认);仅写创建时间
  4409. $data['createtime'] = date('Y-m-d H:i:s');
  4410. Db::table('purchase_order')->insert($data);
  4411. }
  4412. } catch (\Throwable $e) {
  4413. $this->error($e->getMessage());
  4414. }
  4415. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4416. $this->success('操作成功');
  4417. }
  4418. /**
  4419. * 未发列表
  4420. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4421. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4422. */
  4423. public function completeDirectly()
  4424. {
  4425. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4426. $this->error(__('参数错误'));
  4427. }
  4428. if (!$this->procuremenCanComplete()) {
  4429. $this->error(__('You have no permission'));
  4430. }
  4431. $row = json_decode($this->request->post('row_json', ''), true);
  4432. if (!is_array($row)) {
  4433. $this->error(__('Invalid parameters'));
  4434. }
  4435. $finishRaw = $this->request->post('finish', '1');
  4436. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4437. $poIdLog = null;
  4438. try {
  4439. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4440. $ids = $this->extractScydgyRowId($row);
  4441. if (!$this->isValidScydgyRowId($ids)) {
  4442. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4443. }
  4444. if ($asComplete) {
  4445. $this->assertPickRowCanComplete($ids, $row);
  4446. }
  4447. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4448. $data = [
  4449. 'scydgy_id' => $ids,
  4450. 'CCYDH' => $row['CCYDH'] ?? null,
  4451. 'CYJMC' => $row['CYJMC'] ?? null,
  4452. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4453. 'CDXMC' => $row['CDXMC'] ?? null,
  4454. 'CGYBH' => $row['CGYBH'] ?? null,
  4455. 'CGYMC' => $row['CGYMC'] ?? null,
  4456. 'CDW' => $row['CDW'] ?? null,
  4457. 'czlyq' => $row['czlyq'] ?? null,
  4458. 'NGZL' => $row['NGZL'] ?? null,
  4459. 'CDF' => $row['CDF'] ?? null,
  4460. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4461. 'MBZ' => $row['MBZ'] ?? null,
  4462. 'bwjg' => $row['bwjg'] ?? null,
  4463. 'iStatus' => $row['iStatus'] ?? null,
  4464. 'dStamp' => $row['dStamp'] ?? null,
  4465. 'dputrecord' => $row['dputrecord'] ?? null,
  4466. 'cywyxm' => $row['cywyxm'] ?? null,
  4467. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4468. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4469. ];
  4470. if ($asComplete) {
  4471. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4472. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4473. }
  4474. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4475. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4476. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4477. $this->success('操作成功');
  4478. return;
  4479. }
  4480. if ($exists) {
  4481. $upd = $data;
  4482. unset($upd['scydgy_id']);
  4483. if (!$asComplete) {
  4484. unset($upd['status']);
  4485. }
  4486. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4487. } else {
  4488. // 新增:不写 status;完结时 $data 已含 status=1
  4489. $data['createtime'] = date('Y-m-d H:i:s');
  4490. Db::table('purchase_order')->insert($data);
  4491. }
  4492. } catch (\Throwable $e) {
  4493. $this->error($e->getMessage());
  4494. }
  4495. try {
  4496. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4497. if (is_array($rpo)) {
  4498. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4499. $poIdLog = $tid > 0 ? $tid : null;
  4500. }
  4501. } catch (\Throwable $e) {
  4502. $poIdLog = null;
  4503. }
  4504. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4505. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4506. if ($asComplete) {
  4507. $this->addOrderLog(
  4508. $ids,
  4509. 'mark_complete',
  4510. '点击「完结」,已标记为已完结',
  4511. $poIdLog
  4512. );
  4513. try {
  4514. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4515. if ($pdfPublicPath === '') {
  4516. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4517. }
  4518. } catch (\Throwable $e) {
  4519. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4520. }
  4521. } else {
  4522. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4523. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4524. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4525. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4526. $this->addOrderLog(
  4527. $ids,
  4528. 'save_qty_price',
  4529. '保存本次数量、最高限价:' . $detail,
  4530. $poIdLog
  4531. );
  4532. }
  4533. $this->pickHiddenScydgySetCache = null;
  4534. $this->success("操作成功");
  4535. }
  4536. /**
  4537. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4538. *
  4539. * @param array<int, array> $rows 引用传递当前页行
  4540. */
  4541. protected function mergePurchaseOrder(array &$rows)
  4542. {
  4543. if ($rows === []) {
  4544. return;
  4545. }
  4546. $ids = [];
  4547. foreach ($rows as $rw) {
  4548. if (!is_array($rw)) {
  4549. continue;
  4550. }
  4551. $id = (int)($rw['ID'] ?? 0);
  4552. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4553. if ($this->isValidScydgyRowId($id)) {
  4554. $ids[$id] = true;
  4555. }
  4556. }
  4557. $idList = array_keys($ids);
  4558. if ($idList === []) {
  4559. return;
  4560. }
  4561. try {
  4562. $list = Db::table('purchase_order')
  4563. ->where('scydgy_id', 'in', $idList)
  4564. ->field('scydgy_id,This_quantity,ceilingPrice')
  4565. ->select();
  4566. } catch (\Throwable $e) {
  4567. return;
  4568. }
  4569. if (!is_array($list)) {
  4570. return;
  4571. }
  4572. $byId = [];
  4573. foreach ($list as $dbRow) {
  4574. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4575. continue;
  4576. }
  4577. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4578. }
  4579. foreach ($rows as &$rw) {
  4580. if (!is_array($rw)) {
  4581. continue;
  4582. }
  4583. $sid = (int)($rw['ID'] ?? 0);
  4584. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4585. continue;
  4586. }
  4587. $db = $byId[$sid];
  4588. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4589. if (array_key_exists('This_quantity', $db)) {
  4590. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4591. }
  4592. if (array_key_exists('ceilingPrice', $db)) {
  4593. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4594. } elseif (array_key_exists('ceiling_price', $db)) {
  4595. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4596. }
  4597. }
  4598. unset($rw);
  4599. }
  4600. /**
  4601. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4602. */
  4603. public function purchaseConfirmPick()
  4604. {
  4605. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4606. $this->error(__('Invalid parameters'));
  4607. }
  4608. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4609. $this->error(__('You have no permission'));
  4610. }
  4611. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4612. if ($batchRaw !== '') {
  4613. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4614. return;
  4615. }
  4616. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4617. $sid = (int)$scydgyId;
  4618. if (!$this->isValidScydgyRowId($sid)) {
  4619. $this->error('参数无效');
  4620. }
  4621. $parseIdList = function ($raw) {
  4622. if (is_array($raw)) {
  4623. $arr = $raw;
  4624. } else {
  4625. $decoded = json_decode((string)$raw, true);
  4626. $arr = is_array($decoded) ? $decoded : [];
  4627. }
  4628. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4629. };
  4630. $selectedRaw = $this->request->post('selected_ids', null);
  4631. if ($selectedRaw === null || $selectedRaw === '') {
  4632. $legacy = (int)$this->request->post('selected_id', 0);
  4633. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4634. } else {
  4635. $selectedIds = $parseIdList($selectedRaw);
  4636. }
  4637. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4638. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4639. try {
  4640. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4641. } catch (\InvalidArgumentException $e) {
  4642. $this->error($e->getMessage());
  4643. } catch (\Throwable $e) {
  4644. $this->error($e->getMessage());
  4645. }
  4646. $this->pickHiddenScydgySetCache = null;
  4647. $this->success('操作成功', '', $result);
  4648. }
  4649. /**
  4650. * 整单采购确认(多道工序一次提交)
  4651. */
  4652. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4653. {
  4654. $decoded = json_decode($batchRaw, true);
  4655. if (!is_array($decoded) || $decoded === []) {
  4656. $this->error('提交数据无效');
  4657. }
  4658. $picks = [];
  4659. foreach ($decoded as $item) {
  4660. if (!is_array($item)) {
  4661. continue;
  4662. }
  4663. $sid = (int)($item['scydgy_id'] ?? 0);
  4664. if (!$this->isValidScydgyRowId($sid)) {
  4665. continue;
  4666. }
  4667. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4668. if (!is_array($sel)) {
  4669. $sel = [(int)$sel];
  4670. }
  4671. $unsel = $item['unselected_ids'] ?? [];
  4672. if (!is_array($unsel)) {
  4673. $unsel = json_decode((string)$unsel, true);
  4674. $unsel = is_array($unsel) ? $unsel : [];
  4675. }
  4676. $picks[] = [
  4677. 'scydgy_id' => $sid,
  4678. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4679. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4680. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4681. ];
  4682. }
  4683. if ($picks === []) {
  4684. $this->error('提交数据无效');
  4685. }
  4686. Db::startTrans();
  4687. $results = [];
  4688. try {
  4689. foreach ($picks as $pick) {
  4690. $results[] = $this->runPurchaseConfirmPick(
  4691. (int)$pick['scydgy_id'],
  4692. $pick['selected_ids'],
  4693. $pick['unselected_ids'],
  4694. (int)$pick['purchase_order_id'],
  4695. false,
  4696. false
  4697. );
  4698. }
  4699. Db::commit();
  4700. } catch (\Throwable $e) {
  4701. Db::rollback();
  4702. $msg = $e->getMessage();
  4703. $this->error($msg !== '' ? $msg : '提交失败');
  4704. }
  4705. try {
  4706. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4707. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4708. } catch (\Throwable $e) {
  4709. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4710. }
  4711. $this->pickHiddenScydgySetCache = null;
  4712. $this->success('操作成功', '', ['batch' => $results]);
  4713. }
  4714. /**
  4715. * @return array<string, mixed>
  4716. */
  4717. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4718. {
  4719. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4720. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4721. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4722. $scydgyId = (string)$sid;
  4723. if ($selectedIds === []) {
  4724. throw new \InvalidArgumentException('请至少勾选一条明细');
  4725. }
  4726. $inter = array_intersect($selectedIds, $unselectedIds);
  4727. if ($inter !== []) {
  4728. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4729. }
  4730. $allIds = $this->purchaseOrderDetail($sid);
  4731. if ($allIds === []) {
  4732. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4733. }
  4734. foreach ($selectedIds as $id) {
  4735. if (!in_array($id, $allIds, true)) {
  4736. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4737. }
  4738. }
  4739. foreach ($unselectedIds as $id) {
  4740. if (!in_array($id, $allIds, true)) {
  4741. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4742. }
  4743. }
  4744. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4745. sort($union, SORT_NUMERIC);
  4746. $expect = $allIds;
  4747. sort($expect, SORT_NUMERIC);
  4748. if ($union !== $expect) {
  4749. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4750. }
  4751. if ($manageTransaction) {
  4752. Db::startTrans();
  4753. }
  4754. try {
  4755. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4756. $aff = 0;
  4757. try {
  4758. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4759. } catch (\Throwable $e) {
  4760. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4761. }
  4762. if ($aff < 1) {
  4763. throw new \Exception('更新选中状态失败');
  4764. }
  4765. $poPayload = [
  4766. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4767. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4768. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4769. ];
  4770. if ($purchaseOrderId > 0) {
  4771. $poAff = (int)Db::table('purchase_order')
  4772. ->where('id', $purchaseOrderId)
  4773. ->where('scydgy_id', $sid)
  4774. ->update($poPayload);
  4775. if ($poAff < 1) {
  4776. throw new \Exception('主表订单不存在或与工序行不匹配');
  4777. }
  4778. } else {
  4779. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4780. if ($poAff < 1) {
  4781. throw new \Exception('未找到');
  4782. }
  4783. }
  4784. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4785. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4786. if ($manageTransaction) {
  4787. Db::commit();
  4788. }
  4789. } catch (\Throwable $e) {
  4790. if ($manageTransaction) {
  4791. Db::rollback();
  4792. }
  4793. throw $e;
  4794. }
  4795. $poIdFinal = $purchaseOrderId;
  4796. if ($poIdFinal <= 0) {
  4797. try {
  4798. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4799. if (is_array($rpo)) {
  4800. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4801. }
  4802. } catch (\Throwable $e) {
  4803. $poIdFinal = 0;
  4804. }
  4805. }
  4806. $pickNames = [];
  4807. foreach ($selectedIds as $pid) {
  4808. $dr = $this->purchaseOrderDetai($sid, $pid);
  4809. $nm = trim((string)($dr['company_name'] ?? ''));
  4810. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4811. }
  4812. $this->addOrderLog(
  4813. $sid,
  4814. 'purchase_confirm',
  4815. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4816. $poIdFinal > 0 ? $poIdFinal : null
  4817. );
  4818. if ($sendNotifications) {
  4819. try {
  4820. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4821. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4822. 'scydgy_id' => $sid,
  4823. 'selected_ids' => $selectedIds,
  4824. 'unselected_ids' => $unselectedIds,
  4825. 'purchase_order_id' => $purchaseOrderId,
  4826. ]]);
  4827. } catch (\Throwable $e) {
  4828. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4829. }
  4830. }
  4831. Log::write(sprintf(
  4832. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4833. $scydgyId,
  4834. $purchaseOrderId,
  4835. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4836. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4837. ), 'notice');
  4838. $pdfPublicPath = '';
  4839. try {
  4840. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4841. } catch (\Throwable $e) {
  4842. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4843. }
  4844. return [
  4845. 'scydgy_id' => $scydgyId,
  4846. 'purchase_order_id' => $purchaseOrderId,
  4847. 'selected_ids' => $selectedIds,
  4848. 'unselected_ids' => $unselectedIds,
  4849. 'purchase_confirm_pdf' => $pdfPublicPath,
  4850. ];
  4851. }
  4852. /**
  4853. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4854. *
  4855. * @param int[]|string[] $scydgyIds
  4856. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4857. */
  4858. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4859. {
  4860. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4861. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4862. if ($scydgyIds === []) {
  4863. return $empty;
  4864. }
  4865. $pos = [];
  4866. try {
  4867. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4868. } catch (\Throwable $e) {
  4869. $rows = [];
  4870. }
  4871. if (is_array($rows)) {
  4872. foreach ($rows as $po) {
  4873. if (is_array($po)) {
  4874. $pos[] = $po;
  4875. }
  4876. }
  4877. }
  4878. if ($pos === []) {
  4879. return $empty;
  4880. }
  4881. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4882. return [
  4883. 'ccydh' => $ccydh,
  4884. 'pos' => $pos,
  4885. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4886. ];
  4887. }
  4888. /**
  4889. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4890. *
  4891. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4892. * @param array<int, array<string, mixed>> $picks
  4893. */
  4894. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4895. {
  4896. if ($picks === []) {
  4897. return;
  4898. }
  4899. $this->ensureConfirmResultEmailTemplates();
  4900. $fallbackDetailId = 0;
  4901. $winners = [];
  4902. $losers = [];
  4903. foreach ($picks as $pick) {
  4904. if (!is_array($pick)) {
  4905. continue;
  4906. }
  4907. $sid = (int)($pick['scydgy_id'] ?? 0);
  4908. if (!$this->isValidScydgyRowId($sid)) {
  4909. continue;
  4910. }
  4911. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4912. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4913. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4914. $fallbackDetailId = (int)$selectedIds[0];
  4915. }
  4916. foreach ($selectedIds as $pid) {
  4917. $dr = $this->purchaseOrderDetai($sid, $pid);
  4918. if (!is_array($dr)) {
  4919. continue;
  4920. }
  4921. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4922. }
  4923. foreach ($unselectedIds as $pid) {
  4924. $dr = $this->purchaseOrderDetai($sid, $pid);
  4925. if (!is_array($dr)) {
  4926. continue;
  4927. }
  4928. $key = $this->notifySupplierDedupeKey($dr);
  4929. if (!isset($winners[$key])) {
  4930. $losers[$key] = $dr;
  4931. }
  4932. }
  4933. }
  4934. if ($winners === [] && $losers === []) {
  4935. return;
  4936. }
  4937. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4938. $poIdLog = 0;
  4939. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  4940. if (isset($pos[0]) && is_array($pos[0])) {
  4941. $poIdLog = (int)($pos[0]['id'] ?? 0);
  4942. }
  4943. $sendSmsSafe = function ($phone, $content) {
  4944. $phone = trim((string)$phone);
  4945. if ($phone === '') {
  4946. return;
  4947. }
  4948. try {
  4949. $this->smsbao($phone, $content);
  4950. } catch (\Throwable $e) {
  4951. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4952. }
  4953. };
  4954. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  4955. $cname = trim((string)($dr['company_name'] ?? ''));
  4956. $ph = trim((string)($dr['phone'] ?? ''));
  4957. $toEmail = trim((string)($dr['email'] ?? ''));
  4958. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4959. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  4960. return;
  4961. }
  4962. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4963. if ($detailId <= 0) {
  4964. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  4965. }
  4966. try {
  4967. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  4968. } catch (\Throwable $e) {
  4969. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  4970. $platformUrl = '';
  4971. }
  4972. $vars = array_merge($confirmNotifyVars, [
  4973. 'company_name' => $cname,
  4974. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4975. 'phone' => $ph,
  4976. 'email' => $toEmail,
  4977. 'platform_url' => $platformUrl,
  4978. ]);
  4979. unset($vars['_fallback_detail_id']);
  4980. try {
  4981. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  4982. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4983. $mailBody = $this->appendPlatformTapLinkToEmailHtml($mailBody, $platformUrl);
  4984. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  4985. $mailConfig = $this->loadMailerConfig();
  4986. $this->issueSendSupplierEmail([
  4987. 'company_name' => $cname,
  4988. 'email' => $toEmail,
  4989. 'mail_plain' => $mailPlain,
  4990. 'mail_body' => $mailBody,
  4991. 'notify_vars' => $vars,
  4992. 'sms_content' => '',
  4993. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  4994. 'email_log_scene' => 'confirm_result',
  4995. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  4996. 'email_log_purchase_order_id' => $poIdLog,
  4997. ], $mailConfig, $mailSubject);
  4998. } catch (\Throwable $e) {
  4999. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5000. }
  5001. };
  5002. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5003. foreach ($winners as $dr) {
  5004. $cname = trim((string)($dr['company_name'] ?? ''));
  5005. $ph = trim((string)($dr['phone'] ?? ''));
  5006. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5007. 'company_name' => $cname,
  5008. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5009. 'phone' => $ph,
  5010. ]));
  5011. $sendSmsSafe($ph, $sms);
  5012. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5013. }
  5014. foreach ($losers as $dr) {
  5015. $cname = trim((string)($dr['company_name'] ?? ''));
  5016. $ph = trim((string)($dr['phone'] ?? ''));
  5017. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5018. 'company_name' => $cname,
  5019. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5020. 'phone' => $ph,
  5021. ]));
  5022. $sendSmsSafe($ph, $sms);
  5023. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5024. }
  5025. }
  5026. /**
  5027. * 短信去重键:优先手机号,否则公司名
  5028. */
  5029. protected function notifySupplierDedupeKey(array $detailRow): string
  5030. {
  5031. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5032. if ($ph !== '') {
  5033. return 'p:' . $ph;
  5034. }
  5035. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5036. return 'c:' . $cn;
  5037. }
  5038. /**
  5039. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5040. *
  5041. * @param int[] $detailIds
  5042. */
  5043. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5044. {
  5045. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5046. if ($detailIds === []) {
  5047. return;
  5048. }
  5049. $payload = ['status_name' => $statusName];
  5050. try {
  5051. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5052. } catch (\Throwable $e) {
  5053. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5054. }
  5055. }
  5056. /**
  5057. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5058. */
  5059. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5060. {
  5061. try {
  5062. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5063. } catch (\Throwable $e) {
  5064. return;
  5065. }
  5066. if (!is_array($rows)) {
  5067. return;
  5068. }
  5069. foreach ($rows as $dr) {
  5070. if (!is_array($dr)) {
  5071. continue;
  5072. }
  5073. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5074. if ($id <= 0) {
  5075. continue;
  5076. }
  5077. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5078. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5079. try {
  5080. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5081. } catch (\Throwable $e) {
  5082. }
  5083. }
  5084. }
  5085. /**
  5086. * @param array<string, mixed> $detailRow
  5087. */
  5088. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5089. {
  5090. $am = $detailRow['amount'] ?? null;
  5091. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5092. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5093. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5094. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5095. }
  5096. /**
  5097. * @return int[]
  5098. */
  5099. protected function purchaseOrderDetail(int $scydgyId): array
  5100. {
  5101. if (!$this->isValidScydgyRowId($scydgyId)) {
  5102. return [];
  5103. }
  5104. try {
  5105. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5106. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5107. $list = $listQuery->select();
  5108. } catch (\Throwable $e) {
  5109. return [];
  5110. }
  5111. if (!is_array($list)) {
  5112. return [];
  5113. }
  5114. $ids = [];
  5115. foreach ($list as $r) {
  5116. if (!is_array($r)) {
  5117. continue;
  5118. }
  5119. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5120. if ($pk > 0) {
  5121. $ids[] = $pk;
  5122. }
  5123. }
  5124. return array_values(array_unique($ids));
  5125. }
  5126. /**
  5127. * 获取当前登录用户信息 [id, 展示名]
  5128. */
  5129. protected function GetUseName(): array
  5130. {
  5131. $id = 0;
  5132. $name = '';
  5133. try {
  5134. if ($this->auth && $this->auth->isLogin()) {
  5135. $u = $this->auth->getUserInfo();
  5136. if (is_array($u)) {
  5137. $id = (int)($u['id'] ?? 0);
  5138. $name = trim((string)($u['nickname'] ?? ''));
  5139. if ($name === '') {
  5140. $name = trim((string)($u['username'] ?? ''));
  5141. }
  5142. }
  5143. }
  5144. } catch (\Throwable $e) {
  5145. }
  5146. if ($name === '') {
  5147. $name = '未知用户';
  5148. }
  5149. return [$id, $name];
  5150. }
  5151. /**
  5152. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5153. */
  5154. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5155. {
  5156. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5157. }
  5158. /**
  5159. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5160. *
  5161. * @param array<int, array<string, mixed>> $rows
  5162. */
  5163. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5164. {
  5165. $sidList = [];
  5166. foreach ($rows as $rw) {
  5167. if (!is_array($rw)) {
  5168. continue;
  5169. }
  5170. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5171. foreach ($rw['_order_merge_rows'] as $mr) {
  5172. $mid = (int)($mr['ID'] ?? 0);
  5173. if ($this->isValidScydgyRowId($mid)) {
  5174. $sidList[$mid] = true;
  5175. }
  5176. }
  5177. }
  5178. $id = (int)($rw['ID'] ?? 0);
  5179. if ($this->isValidScydgyRowId($id)) {
  5180. $sidList[$id] = true;
  5181. }
  5182. }
  5183. $sids = array_keys($sidList);
  5184. $issueBySid = [];
  5185. $confirmBySid = [];
  5186. $approveBySid = [];
  5187. if ($sids !== []) {
  5188. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5189. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5190. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5191. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5192. try {
  5193. $logs = Db::table('purchase_order_oper_log')
  5194. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5195. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5196. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5197. ->order('id', 'asc')
  5198. ->select();
  5199. } catch (\Throwable $e) {
  5200. $logs = [];
  5201. }
  5202. if (is_array($logs)) {
  5203. $issueSet = array_fill_keys($issueActs, true);
  5204. $confirmSet = array_fill_keys($confirmActs, true);
  5205. $approveSet = array_fill_keys($approveActs, true);
  5206. foreach ($logs as $lg) {
  5207. if (!is_array($lg)) {
  5208. continue;
  5209. }
  5210. $lg = ProcuremenOperLog::normalizeRow($lg);
  5211. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5212. if ($sid === 0) {
  5213. continue;
  5214. }
  5215. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5216. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5217. if ($t === '') {
  5218. continue;
  5219. }
  5220. if (isset($issueSet[$action])) {
  5221. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5222. $issueBySid[$sid] = $t;
  5223. }
  5224. }
  5225. if (isset($confirmSet[$action])) {
  5226. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5227. $confirmBySid[$sid] = $t;
  5228. }
  5229. }
  5230. if (isset($approveSet[$action])) {
  5231. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5232. $approveBySid[$sid] = $t;
  5233. }
  5234. }
  5235. }
  5236. }
  5237. }
  5238. foreach ($rows as &$rw) {
  5239. if (!is_array($rw)) {
  5240. continue;
  5241. }
  5242. $mergeSids = [];
  5243. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5244. foreach ($rw['_order_merge_rows'] as $mr) {
  5245. $mid = (int)($mr['ID'] ?? 0);
  5246. if ($this->isValidScydgyRowId($mid)) {
  5247. $mergeSids[] = $mid;
  5248. }
  5249. }
  5250. }
  5251. $rid = (int)($rw['ID'] ?? 0);
  5252. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5253. $mergeSids[] = $rid;
  5254. }
  5255. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5256. $issue = $pick;
  5257. $confirm = '';
  5258. $approve = '';
  5259. foreach ($mergeSids as $sid) {
  5260. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5261. $issue = $issueBySid[$sid];
  5262. }
  5263. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5264. $confirm = $confirmBySid[$sid];
  5265. }
  5266. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5267. $approve = $approveBySid[$sid];
  5268. }
  5269. }
  5270. if ($issue === '' && $pick !== '') {
  5271. $issue = $pick;
  5272. }
  5273. $rw['issue_time'] = $issue;
  5274. $rw['confirm_time'] = $confirm;
  5275. $rw['approve_time'] = $approve;
  5276. }
  5277. unset($rw);
  5278. }
  5279. /**
  5280. * 按主键取一条
  5281. */
  5282. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5283. {
  5284. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5285. return [];
  5286. }
  5287. try {
  5288. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5289. if (is_array($one)) {
  5290. return $one;
  5291. }
  5292. } catch (\Throwable $e) {
  5293. }
  5294. try {
  5295. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5296. if (is_array($one)) {
  5297. return $one;
  5298. }
  5299. } catch (\Throwable $e) {
  5300. }
  5301. return [];
  5302. }
  5303. /**
  5304. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5305. */
  5306. protected function formatProcuremenDetailTime($v): string
  5307. {
  5308. if ($v === null || $v === '') {
  5309. return '';
  5310. }
  5311. if (is_numeric($v) && (int)$v > 946684800) {
  5312. return date('Y-m-d H:i:s', (int)$v);
  5313. }
  5314. return ProcuremenTime::formatDisplayDateTime($v);
  5315. }
  5316. /**
  5317. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5318. */
  5319. protected function formatDeliveryYmd($v): string
  5320. {
  5321. if ($v === null || $v === '') {
  5322. return '';
  5323. }
  5324. $s = trim((string)$v);
  5325. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5326. return '';
  5327. }
  5328. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5329. return $m[1];
  5330. }
  5331. $ts = strtotime($s);
  5332. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5333. }
  5334. /**
  5335. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5336. */
  5337. protected function detailRowSupplierOperated(array $r): bool
  5338. {
  5339. $am = $r['amount'] ?? null;
  5340. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5341. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5342. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5343. return $okAmt || $okDel;
  5344. }
  5345. /**
  5346. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5347. */
  5348. protected function resolveDetailSupplierOperTime(array $r): string
  5349. {
  5350. if (!$this->detailRowSupplierOperated($r)) {
  5351. return '';
  5352. }
  5353. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5354. if ($t !== '') {
  5355. return $t;
  5356. }
  5357. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5358. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5359. continue;
  5360. }
  5361. $t = $this->formatProcuremenDetailTime($r[$col]);
  5362. if ($t !== '') {
  5363. return $t;
  5364. }
  5365. }
  5366. return '';
  5367. }
  5368. /**
  5369. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5370. */
  5371. protected function detailRowSupplierAccepted(array $r): bool
  5372. {
  5373. $am = $r['amount'] ?? null;
  5374. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5375. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5376. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5377. return $okAmt && $okDel;
  5378. }
  5379. /**
  5380. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5381. */
  5382. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5383. {
  5384. if ($detailCount > 0) {
  5385. return true;
  5386. }
  5387. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5388. return true;
  5389. }
  5390. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5391. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5392. return true;
  5393. }
  5394. return false;
  5395. }
  5396. /**
  5397. * 下发时间:优先 pick_time,其次首条下发明细时间
  5398. */
  5399. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5400. {
  5401. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5402. if ($issueTime !== '') {
  5403. return $issueTime;
  5404. }
  5405. foreach ($details as $dr) {
  5406. if (!is_array($dr)) {
  5407. continue;
  5408. }
  5409. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5410. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5411. $issueTime = $t;
  5412. }
  5413. }
  5414. if ($issueTime !== '') {
  5415. return $issueTime;
  5416. }
  5417. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5418. }
  5419. /**
  5420. * 直接点「完结」时间:优先操作记录 mark_complete
  5421. */
  5422. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5423. {
  5424. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5425. }
  5426. /**
  5427. * 操作记录时间(取指定 action 最近一条)
  5428. *
  5429. * @param string|array<int, string> $actions
  5430. */
  5431. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5432. {
  5433. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5434. }
  5435. /**
  5436. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5437. *
  5438. * @param array $main purchase_order 一行
  5439. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5440. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5441. */
  5442. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5443. {
  5444. $issueCnt = count($details);
  5445. $acceptCnt = 0;
  5446. $pickedName = '';
  5447. $pickedTime = '';
  5448. foreach ($details as $dr) {
  5449. if (!is_array($dr)) {
  5450. continue;
  5451. }
  5452. if ($this->detailRowSupplierAccepted($dr)) {
  5453. $acceptCnt++;
  5454. }
  5455. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5456. if ($pickedName === '') {
  5457. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5458. }
  5459. if ($pickedTime === '') {
  5460. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5461. if ($pickedTime === '') {
  5462. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5463. }
  5464. }
  5465. }
  5466. }
  5467. $hasMain = $main !== [];
  5468. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5469. if ($poTime === '') {
  5470. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5471. }
  5472. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5473. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5474. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5475. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5476. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5477. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5478. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5479. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5480. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5481. $inboundResult = '';
  5482. if ($scydgyId > 0) {
  5483. try {
  5484. $inRow = Db::table('purchase_order_inbound_score')
  5485. ->where('scydgy_id', $scydgyId)
  5486. ->field('result,updatetime,createtime')
  5487. ->find();
  5488. } catch (\Throwable $e) {
  5489. $inRow = null;
  5490. }
  5491. if (is_array($inRow) && $inRow !== []) {
  5492. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5493. if ($inboundScoreTime === '') {
  5494. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5495. }
  5496. }
  5497. }
  5498. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5499. $supplierTime = '';
  5500. if ($acceptCnt > 0) {
  5501. foreach ($details as $dr) {
  5502. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5503. continue;
  5504. }
  5505. $t = $this->resolveDetailSupplierOperTime($dr);
  5506. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5507. $supplierTime = $t;
  5508. }
  5509. }
  5510. }
  5511. $directComplete = ($mainCompleted && !$issued);
  5512. $doneTime = '';
  5513. if ($mainCompleted) {
  5514. if ($directComplete) {
  5515. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5516. }
  5517. if ($doneTime === '' && $inboundScoreTime !== '') {
  5518. $doneTime = $inboundScoreTime;
  5519. }
  5520. if ($doneTime === '') {
  5521. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5522. }
  5523. if ($doneTime === '') {
  5524. foreach ($details as $dr) {
  5525. if (!is_array($dr)) {
  5526. continue;
  5527. }
  5528. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5529. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5530. $doneTime = $t;
  5531. }
  5532. }
  5533. }
  5534. if ($doneTime === '') {
  5535. $doneTime = $poTime;
  5536. }
  5537. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5538. if ($doneTime === '' && $confirmApproveTime !== '') {
  5539. $doneTime = $confirmApproveTime;
  5540. }
  5541. }
  5542. if ($directComplete) {
  5543. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5544. $step1Done = $hasMain;
  5545. $step2Done = false;
  5546. $step3Done = false;
  5547. $step4Done = false;
  5548. $step5Done = false;
  5549. $stepInboundDone = $inboundScored;
  5550. $step6Done = $mainCompleted && $inboundScored;
  5551. } else {
  5552. $step1Done = $issued;
  5553. $step2Done = $issued;
  5554. $step3Done = $acceptCnt > 0;
  5555. $step4Done = $wflowPendingApproval;
  5556. if (!$step4Done) {
  5557. foreach ($details as $dr) {
  5558. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5559. $step4Done = true;
  5560. break;
  5561. }
  5562. }
  5563. }
  5564. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5565. $stepInboundDone = $inboundScored;
  5566. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5567. $step6Done = $mainCompleted && $inboundScored;
  5568. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5569. if ($mainCompleted && $issued) {
  5570. $step3Done = true;
  5571. $step4Done = true;
  5572. $step5Done = true;
  5573. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5574. if ($supplierTime === '') {
  5575. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5576. if ($fillT !== '') {
  5577. $supplierTime = $fillT;
  5578. }
  5579. }
  5580. if ($pickedTime === '') {
  5581. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5582. if ($fillT !== '') {
  5583. $pickedTime = $fillT;
  5584. }
  5585. }
  5586. if ($auditSelectTime === '') {
  5587. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5588. if ($fillT !== '') {
  5589. $auditSelectTime = $fillT;
  5590. }
  5591. }
  5592. if ($confirmApproveTime === '') {
  5593. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5594. if ($fillT !== '') {
  5595. $confirmApproveTime = $fillT;
  5596. }
  5597. }
  5598. }
  5599. }
  5600. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5601. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5602. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5603. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5604. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5605. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5606. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5607. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5608. $deadlineLines = [];
  5609. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5610. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5611. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5612. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5613. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5614. }
  5615. }
  5616. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5617. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5618. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5619. if ($deliveryDisp === '') {
  5620. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5621. }
  5622. if ($deliveryDisp !== '') {
  5623. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5624. }
  5625. }
  5626. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5627. $deadlineText = implode("\n", $deadlineLines);
  5628. $prefixOperTime = static function (string $t): string {
  5629. $t = trim($t);
  5630. if ($t === '' || $t === '—') {
  5631. return $t;
  5632. }
  5633. if (strpos($t, '操作时间') === 0) {
  5634. return $t;
  5635. }
  5636. return '操作时间:' . $t;
  5637. };
  5638. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5639. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5640. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5641. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5642. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5643. $steps = [
  5644. [
  5645. 'title' => '未发',
  5646. 'subtitle' => '',
  5647. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5648. 'done' => $step1Done,
  5649. ],
  5650. [
  5651. 'title' => '下发',
  5652. 'subtitle' => $deadlineText,
  5653. 'time' => $prefixOperTime($step2Time),
  5654. 'done' => $step2Done,
  5655. ],
  5656. [
  5657. 'title' => '供应商接单',
  5658. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5659. 'time' => '',
  5660. 'done' => $step3Done,
  5661. ],
  5662. [
  5663. 'title' => '待确认',
  5664. 'subtitle' => $step4Done
  5665. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5666. : ($issued ? '待选供应商' : ''),
  5667. 'time' => $prefixOperTime($step4Time),
  5668. 'done' => $step4Done,
  5669. ],
  5670. [
  5671. 'title' => '待审批',
  5672. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5673. 'time' => $prefixOperTime($step5Time),
  5674. 'done' => $step5Done,
  5675. ],
  5676. [
  5677. 'title' => '是否合格',
  5678. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5679. 'time' => $prefixOperTime($stepInboundTime),
  5680. 'done' => $stepInboundDone,
  5681. ],
  5682. [
  5683. 'title' => '已完结',
  5684. 'subtitle' => '',
  5685. 'time' => $prefixOperTime($step6Time),
  5686. 'done' => $step6Done,
  5687. ],
  5688. ];
  5689. $currentIdx = count($steps) - 1;
  5690. if ($directComplete) {
  5691. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5692. if (!$step6Done) {
  5693. foreach ($steps as $i => $s) {
  5694. if (($s['title'] ?? '') === '是否合格') {
  5695. $currentIdx = $i;
  5696. break;
  5697. }
  5698. }
  5699. }
  5700. } else {
  5701. foreach ($steps as $i => $s) {
  5702. if (!$s['done']) {
  5703. $currentIdx = $i;
  5704. break;
  5705. }
  5706. }
  5707. }
  5708. $nSteps = count($steps);
  5709. foreach ($steps as $idx => &$s) {
  5710. $s['current'] = ($idx === $currentIdx);
  5711. if ($idx === 0) {
  5712. $s['pdf_left_bg'] = '';
  5713. } else {
  5714. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5715. }
  5716. if ($idx >= $nSteps - 1) {
  5717. $s['pdf_right_bg'] = '';
  5718. } else {
  5719. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5720. }
  5721. }
  5722. unset($s);
  5723. $labelMap = [
  5724. 'CCYDH' => '订单号',
  5725. 'CYJMC' => '印件名称',
  5726. 'CCLBMMC' => '承揽部门',
  5727. 'CGYMC' => '工序名称',
  5728. 'CDW' => '单位',
  5729. 'czlyq' => '类型',
  5730. 'NGZL' => '工作量',
  5731. 'CDF' => '单价',
  5732. 'cGzzxMc' => '工作中心',
  5733. 'MBZ' => '备注',
  5734. 'This_quantity' => '本次数量',
  5735. 'ceilingPrice' => '最高限价',
  5736. ];
  5737. $orderSummary = [];
  5738. foreach ($labelMap as $key => $lab) {
  5739. if (!array_key_exists($key, $main)) {
  5740. continue;
  5741. }
  5742. $val = $main[$key];
  5743. if ($val === null) {
  5744. $val = '';
  5745. } elseif (!is_scalar($val)) {
  5746. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5747. } else {
  5748. $val = (string)$val;
  5749. }
  5750. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5751. }
  5752. $orderSummary[] = [
  5753. 'label' => '是否合格',
  5754. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5755. ];
  5756. $orderSummaryGrid = [];
  5757. $n = count($orderSummary);
  5758. for ($i = 0; $i < $n; $i += 2) {
  5759. $left = $orderSummary[$i];
  5760. $hasRight = ($i + 1) < $n;
  5761. $orderSummaryGrid[] = [
  5762. 'l1' => $left['label'],
  5763. 'v1' => $left['value'],
  5764. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5765. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5766. ];
  5767. }
  5768. return [
  5769. 'steps' => $steps,
  5770. 'orderSummary' => $orderSummary,
  5771. 'orderSummaryGrid' => $orderSummaryGrid,
  5772. 'inbound_result' => $inboundResult,
  5773. 'inbound_score_time'=> $inboundScoreTime,
  5774. 'detailRows' => $details,
  5775. ];
  5776. }
  5777. /**
  5778. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5779. *
  5780. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5781. */
  5782. protected function prepareProcuremenDetailsView(string $ids): array
  5783. {
  5784. $main = [];
  5785. try {
  5786. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5787. $main = is_array($one) ? $one : [];
  5788. } catch (\Throwable $e) {
  5789. $main = [];
  5790. }
  5791. $details = [];
  5792. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5793. if ($mergeRows === []) {
  5794. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5795. if ($mergeRows === [] && $main !== []) {
  5796. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5797. }
  5798. }
  5799. $detailSidList = [];
  5800. $anchorSid = (int)$ids;
  5801. if ($anchorSid !== 0) {
  5802. $detailSidList[$anchorSid] = true;
  5803. }
  5804. foreach ($mergeRows as $mr) {
  5805. if (!is_array($mr)) {
  5806. continue;
  5807. }
  5808. $sid = $this->extractScydgyRowId($mr);
  5809. if ($sid !== 0) {
  5810. $detailSidList[$sid] = true;
  5811. }
  5812. }
  5813. try {
  5814. if ($detailSidList !== []) {
  5815. $details = Db::table('purchase_order_detail')
  5816. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5817. ->order('id', 'asc')
  5818. ->select();
  5819. }
  5820. } catch (\Throwable $e) {
  5821. $details = [];
  5822. }
  5823. if (!is_array($details)) {
  5824. $details = [];
  5825. }
  5826. foreach ($details as &$r) {
  5827. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5828. $r['id'] = $r['ID'];
  5829. }
  5830. if (isset($r['createtime'])) {
  5831. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5832. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5833. } else {
  5834. $r['createtime_text'] = (string)$r['createtime'];
  5835. }
  5836. } else {
  5837. $r['createtime_text'] = '';
  5838. }
  5839. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5840. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5841. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5842. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5843. if (is_array($r)) {
  5844. $r = $this->maskSupplierContactFields($r);
  5845. }
  5846. }
  5847. unset($r);
  5848. $activeDetails = [];
  5849. foreach ($details as $r) {
  5850. if (is_array($r) && empty($r['is_void'])) {
  5851. $activeDetails[] = $r;
  5852. }
  5853. }
  5854. $operLogs = [];
  5855. try {
  5856. $operSidList = array_keys($detailSidList);
  5857. if ($operSidList === [] && (int)$ids !== 0) {
  5858. $operSidList = [(int)$ids];
  5859. }
  5860. if ($operSidList !== []) {
  5861. $operLogs = Db::table('purchase_order_oper_log')
  5862. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5863. ->order('id', 'asc')
  5864. ->select();
  5865. }
  5866. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5867. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5868. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5869. if ($poId > 0) {
  5870. $operLogs = Db::table('purchase_order_oper_log')
  5871. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5872. ->order('id', 'asc')
  5873. ->select();
  5874. }
  5875. }
  5876. } catch (\Throwable $e) {
  5877. $operLogs = [];
  5878. }
  5879. if (!is_array($operLogs)) {
  5880. $operLogs = [];
  5881. }
  5882. $operLogsRaw = $operLogs;
  5883. $processNameBySid = [];
  5884. foreach ($mergeRows as $mr) {
  5885. if (!is_array($mr)) {
  5886. continue;
  5887. }
  5888. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5889. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5890. if ($psid !== 0 && $gymc !== '') {
  5891. $processNameBySid[$psid] = $gymc;
  5892. }
  5893. }
  5894. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5895. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5896. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5897. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5898. if ($ccydh === '') {
  5899. foreach ($details as $r) {
  5900. if (!is_array($r)) {
  5901. continue;
  5902. }
  5903. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5904. if ($ccydh !== '') {
  5905. break;
  5906. }
  5907. }
  5908. }
  5909. $this->view->assign('ccydh', $ccydh);
  5910. $this->view->assign('steps', $bundle['steps']);
  5911. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5912. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5913. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5914. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5915. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5916. $this->view->assign('processCount', count($mergeRows));
  5917. $this->view->assign('detailRows', $details);
  5918. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5919. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5920. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5921. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5922. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5923. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5924. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5925. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5926. $this->view->assign('operLogs', $operLogs);
  5927. $sg = $quoteView['supplier_groups'] ?? [];
  5928. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5929. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5930. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5931. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5932. return [
  5933. 'ok' => $main !== [] || $details !== [],
  5934. 'ccydh' => $ccydh,
  5935. ];
  5936. }
  5937. /**
  5938. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5939. */
  5940. public function details()
  5941. {
  5942. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5943. if (is_array($ids)) {
  5944. $ids = isset($ids[0]) ? $ids[0] : '';
  5945. }
  5946. $ids = trim((string)$ids);
  5947. if ($ids === '') {
  5948. $this->error(__('Invalid parameters'));
  5949. }
  5950. $this->assertManualOrderDetailsViewable((int)$ids);
  5951. $this->prepareProcuremenDetailsView($ids);
  5952. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5953. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5954. $this->view->engine->layout(false);
  5955. try {
  5956. return $this->view->fetch('procuremen/details_dialog_shell');
  5957. } finally {
  5958. if ($restoreLayout) {
  5959. $this->view->engine->layout($restoreLayout);
  5960. }
  5961. }
  5962. }
  5963. /**
  5964. * 解析合并审核工序行(订单号须一致,且均未协助)
  5965. *
  5966. * @return array<int, array<string, mixed>>
  5967. */
  5968. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5969. {
  5970. $primary = json_decode($rowJson, true);
  5971. if (!is_array($primary)) {
  5972. $this->error(__('Invalid parameters'));
  5973. }
  5974. $merge = json_decode($mergeRowsJson, true);
  5975. if (!is_array($merge) || $merge === []) {
  5976. $merge = [$primary];
  5977. }
  5978. $seen = [];
  5979. $out = [];
  5980. foreach ($merge as $r) {
  5981. if (!is_array($r)) {
  5982. continue;
  5983. }
  5984. $id = $this->extractScydgyRowId($r);
  5985. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5986. continue;
  5987. }
  5988. $seen[$id] = true;
  5989. $out[] = $r;
  5990. }
  5991. if ($out === []) {
  5992. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5993. }
  5994. $ccydh = null;
  5995. foreach ($out as $r) {
  5996. $dh = trim((string)($r['CCYDH'] ?? ''));
  5997. if ($ccydh === null) {
  5998. $ccydh = $dh;
  5999. } elseif ($dh !== $ccydh) {
  6000. $this->error('合并审核要求所选行的订单号一致');
  6001. }
  6002. }
  6003. $ids = [];
  6004. foreach ($out as $r) {
  6005. $id = $this->extractScydgyRowId($r);
  6006. if ($this->isValidScydgyRowId($id)) {
  6007. $ids[$id] = true;
  6008. }
  6009. }
  6010. $poBySid = [];
  6011. $detCntBySid = [];
  6012. if ($ids !== []) {
  6013. $idList = array_keys($ids);
  6014. try {
  6015. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6016. if (is_array($poList)) {
  6017. foreach ($poList as $po) {
  6018. if (!is_array($po)) {
  6019. continue;
  6020. }
  6021. $sid = (int)($po['scydgy_id'] ?? 0);
  6022. if ($this->isValidScydgyRowId($sid)) {
  6023. $poBySid[$sid] = $po;
  6024. }
  6025. }
  6026. }
  6027. } catch (\Throwable $e) {
  6028. }
  6029. try {
  6030. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6031. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6032. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6033. if (is_array($detRows)) {
  6034. foreach ($detRows as $dr) {
  6035. if (!is_array($dr)) {
  6036. continue;
  6037. }
  6038. $sid = (int)($dr['scydgy_id'] ?? 0);
  6039. if ($this->isValidScydgyRowId($sid)) {
  6040. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6041. }
  6042. }
  6043. }
  6044. } catch (\Throwable $e) {
  6045. }
  6046. }
  6047. foreach ($out as $r) {
  6048. $id = $this->extractScydgyRowId($r);
  6049. if (!$this->isValidScydgyRowId($id)) {
  6050. continue;
  6051. }
  6052. $po = $poBySid[$id] ?? null;
  6053. if (!is_array($po)) {
  6054. continue;
  6055. }
  6056. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6057. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6058. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6059. }
  6060. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6061. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6062. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6063. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6064. }
  6065. }
  6066. return $out;
  6067. }
  6068. /**
  6069. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6070. */
  6071. protected function maskSupplierContactFields(array $item): array
  6072. {
  6073. if (array_key_exists('email', $item)) {
  6074. $item['email'] = mask_email((string)$item['email']);
  6075. }
  6076. if (array_key_exists('phone', $item)) {
  6077. $item['phone'] = mask_phone((string)$item['phone']);
  6078. }
  6079. return $item;
  6080. }
  6081. /**
  6082. * @param array<int, array<string, mixed>> $list
  6083. * @return array<int, array<string, mixed>>
  6084. */
  6085. protected function maskSupplierContactList(array $list): array
  6086. {
  6087. $out = [];
  6088. foreach ($list as $item) {
  6089. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6090. }
  6091. return $out;
  6092. }
  6093. /**
  6094. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6095. *
  6096. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6097. * @return array<string, string>|null
  6098. */
  6099. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6100. {
  6101. if (!is_array($row)) {
  6102. return null;
  6103. }
  6104. $norm = [];
  6105. foreach ($row as $k => $v) {
  6106. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6107. }
  6108. $row = $norm;
  6109. $st = $row['status'] ?? '';
  6110. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6111. return null;
  6112. }
  6113. $companyName = '';
  6114. foreach (['company_name', 'name'] as $nk) {
  6115. if (!empty($row[$nk])) {
  6116. $companyName = trim((string)$row[$nk]);
  6117. break;
  6118. }
  6119. }
  6120. if ($companyName === '') {
  6121. return null;
  6122. }
  6123. $username = '';
  6124. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6125. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6126. $username = trim((string)$row[$uk]);
  6127. break;
  6128. }
  6129. }
  6130. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6131. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6132. if ($phone === '' && isset($row['account'])) {
  6133. $phone = trim((string)$row['account']);
  6134. }
  6135. if ($phone === '' && isset($row['mobile'])) {
  6136. $phone = trim((string)$row['mobile']);
  6137. }
  6138. if ($requireContactChannels && $email === '' && $phone === '') {
  6139. return null;
  6140. }
  6141. $category = '';
  6142. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6143. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6144. $category = trim((string)$row[$ck]);
  6145. break;
  6146. }
  6147. }
  6148. return [
  6149. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6150. 'name' => $companyName,
  6151. 'company_name' => $companyName,
  6152. 'username' => $username,
  6153. 'email' => $email,
  6154. 'phone' => $phone,
  6155. 'category' => $category,
  6156. 'company_type' => $category,
  6157. ];
  6158. }
  6159. /**
  6160. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6161. */
  6162. protected function resolveCustomerContactById(string $id): ?array
  6163. {
  6164. $id = trim($id);
  6165. if ($id === '' || !ctype_digit($id)) {
  6166. return null;
  6167. }
  6168. try {
  6169. $row = Db::table('customer')->where('id', (int)$id)->find();
  6170. } catch (\Throwable $e) {
  6171. return null;
  6172. }
  6173. return $this->buildCustomerContactPayloadFromRow($row);
  6174. }
  6175. /**
  6176. * 按供应商名称解析联系信息(兼容旧提交数据)
  6177. *
  6178. * @param bool $requireContactChannels true 时须有邮箱或手机
  6179. */
  6180. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6181. {
  6182. $name = trim($name);
  6183. if ($name === '') {
  6184. return null;
  6185. }
  6186. try {
  6187. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6188. $row = Db::table('customer')
  6189. ->where('company_name', $name)
  6190. ->order('id', 'desc')
  6191. ->find();
  6192. } catch (\Throwable $e) {
  6193. return null;
  6194. }
  6195. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6196. }
  6197. /**
  6198. * 规范化下发/确认时勾选的供应商
  6199. *
  6200. * @param array<int, mixed> $companies
  6201. * @return array<int, array<string, string>>
  6202. */
  6203. protected function normalizePickCompanies(array $companies): array
  6204. {
  6205. $out = [];
  6206. foreach ($companies as $c) {
  6207. if (!is_array($c)) {
  6208. continue;
  6209. }
  6210. $resolved = null;
  6211. $cid = trim((string)($c['id'] ?? ''));
  6212. if ($cid !== '') {
  6213. $resolved = $this->resolveCustomerContactById($cid);
  6214. }
  6215. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6216. if ($resolved === null && $name !== '') {
  6217. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6218. }
  6219. if ($resolved === null) {
  6220. continue;
  6221. }
  6222. $out[] = $resolved;
  6223. }
  6224. return $out;
  6225. }
  6226. /**
  6227. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6228. *
  6229. * @param array<int, array<string, mixed>> $pool
  6230. * @return array<int, array<string, mixed>>
  6231. */
  6232. protected function collapseProcuremenPoolByOrder(array $pool): array
  6233. {
  6234. if ($pool === []) {
  6235. return [];
  6236. }
  6237. $groups = [];
  6238. foreach ($pool as $row) {
  6239. if (!is_array($row)) {
  6240. continue;
  6241. }
  6242. $dh = trim((string)($row['CCYDH'] ?? ''));
  6243. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6244. if (!isset($groups[$key])) {
  6245. $groups[$key] = [];
  6246. }
  6247. $groups[$key][] = $row;
  6248. }
  6249. $out = [];
  6250. foreach ($groups as $ccydh => $rows) {
  6251. if ($rows === []) {
  6252. continue;
  6253. }
  6254. usort($rows, function ($a, $b) {
  6255. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6256. });
  6257. $head = $rows[0];
  6258. $gymcList = [];
  6259. foreach ($rows as $r) {
  6260. $g = trim((string)($r['CGYMC'] ?? ''));
  6261. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6262. $gymcList[] = $g;
  6263. }
  6264. }
  6265. $merged = $head;
  6266. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6267. $merged['process_count'] = count($rows);
  6268. $merged['_order_merge_rows'] = $rows;
  6269. $qtyList = [];
  6270. $priceList = [];
  6271. foreach ($rows as $r) {
  6272. if (!is_array($r)) {
  6273. continue;
  6274. }
  6275. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6276. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6277. }
  6278. if (count($rows) > 1) {
  6279. $merged['CGYMC'] = implode('、', $gymcList);
  6280. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6281. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6282. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6283. } else {
  6284. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6285. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6286. }
  6287. // 已选供应商:取合并行中首个非空 pick_company_name
  6288. $pickedName = '';
  6289. foreach ($rows as $r) {
  6290. if (!is_array($r)) {
  6291. continue;
  6292. }
  6293. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6294. if ($pn !== '') {
  6295. $pickedName = $pn;
  6296. break;
  6297. }
  6298. }
  6299. if ($pickedName !== '') {
  6300. $merged['pick_company_name'] = $pickedName;
  6301. $merged['picked_supplier_name'] = $pickedName;
  6302. }
  6303. $mergedPickTime = '';
  6304. foreach ($rows as $r) {
  6305. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6306. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6307. $mergedPickTime = $t;
  6308. }
  6309. }
  6310. if ($mergedPickTime !== '') {
  6311. $merged['pick_time'] = $mergedPickTime;
  6312. }
  6313. $out[] = $merged;
  6314. }
  6315. usort($out, function ($a, $b) {
  6316. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6317. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6318. if ($ta === $tb) {
  6319. $ida = (int)($a['purchase_order_id'] ?? 0);
  6320. $idb = (int)($b['purchase_order_id'] ?? 0);
  6321. if ($ida !== $idb) {
  6322. return $idb <=> $ida;
  6323. }
  6324. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6325. }
  6326. if ($ta === '') {
  6327. return 1;
  6328. }
  6329. if ($tb === '') {
  6330. return -1;
  6331. }
  6332. return strcmp($tb, $ta);
  6333. });
  6334. return $out;
  6335. }
  6336. /**
  6337. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6338. *
  6339. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6340. */
  6341. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6342. {
  6343. $scydgyId = trim($scydgyId);
  6344. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6345. if ($scydgyId === '') {
  6346. return $empty;
  6347. }
  6348. try {
  6349. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6350. } catch (\Throwable $e) {
  6351. $anchor = null;
  6352. }
  6353. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6354. return $empty;
  6355. }
  6356. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6357. if ($ccydh === '') {
  6358. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6359. }
  6360. try {
  6361. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6362. } catch (\Throwable $e) {
  6363. $pos = [$anchor];
  6364. }
  6365. if (!is_array($pos) || $pos === []) {
  6366. $pos = [$anchor];
  6367. }
  6368. return [
  6369. 'ccydh' => $ccydh,
  6370. 'pos' => $pos,
  6371. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6372. ];
  6373. }
  6374. /**
  6375. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6376. */
  6377. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6378. {
  6379. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6380. return false;
  6381. }
  6382. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6383. return false;
  6384. }
  6385. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6386. return true;
  6387. }
  6388. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6389. $sid = (int)($po['scydgy_id'] ?? 0);
  6390. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6391. }
  6392. return false;
  6393. }
  6394. /**
  6395. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6396. *
  6397. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6398. */
  6399. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6400. {
  6401. $scydgyId = trim($scydgyId);
  6402. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6403. if ($scydgyId === '') {
  6404. return $empty;
  6405. }
  6406. try {
  6407. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6408. } catch (\Throwable $e) {
  6409. $anchor = null;
  6410. }
  6411. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6412. return $empty;
  6413. }
  6414. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6415. if ($ccydh === '') {
  6416. return [
  6417. 'ccydh' => '',
  6418. 'pos' => [$anchor],
  6419. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6420. ];
  6421. }
  6422. try {
  6423. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6424. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6425. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6426. } catch (\Throwable $e) {
  6427. $pos = [$anchor];
  6428. }
  6429. if (!is_array($pos) || $pos === []) {
  6430. $pos = [$anchor];
  6431. }
  6432. $pos = array_values(array_filter($pos, function ($po) {
  6433. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6434. }));
  6435. if ($pos === []) {
  6436. $pos = [$anchor];
  6437. }
  6438. return [
  6439. 'ccydh' => $ccydh,
  6440. 'pos' => $pos,
  6441. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6442. ];
  6443. }
  6444. /**
  6445. * @param array<int, array<string, mixed>> $purchaseOrders
  6446. * @return array<int, array<string, mixed>>
  6447. */
  6448. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6449. {
  6450. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6451. $byId = [];
  6452. foreach ($pool as $r) {
  6453. if (!is_array($r)) {
  6454. continue;
  6455. }
  6456. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6457. if ($this->isValidScydgyRowId($sid)) {
  6458. $byId[$sid] = $r;
  6459. }
  6460. }
  6461. $out = [];
  6462. foreach ($purchaseOrders as $po) {
  6463. if (!is_array($po)) {
  6464. continue;
  6465. }
  6466. $sid = (int)($po['scydgy_id'] ?? 0);
  6467. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6468. $out[] = $byId[$sid];
  6469. }
  6470. }
  6471. return $out;
  6472. }
  6473. /**
  6474. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6475. *
  6476. * @return array<int, array<string, mixed>>
  6477. */
  6478. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6479. {
  6480. $scydgyId = trim($scydgyId);
  6481. if ($scydgyId === '') {
  6482. return [];
  6483. }
  6484. try {
  6485. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6486. } catch (\Throwable $e) {
  6487. $anchor = null;
  6488. }
  6489. if (!is_array($anchor)) {
  6490. return [];
  6491. }
  6492. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6493. return [];
  6494. }
  6495. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6496. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6497. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6498. try {
  6499. $q = Db::table('purchase_order');
  6500. if ($ccydh !== '') {
  6501. $q->where('CCYDH', $ccydh);
  6502. } else {
  6503. $q->where('scydgy_id', $scydgyId);
  6504. }
  6505. if ($isValidPick) {
  6506. $q->where('pick_time', $pickTime);
  6507. }
  6508. $pos = $q->order('scydgy_id', 'asc')->select();
  6509. } catch (\Throwable $e) {
  6510. $pos = [$anchor];
  6511. }
  6512. if (!is_array($pos) || $pos === []) {
  6513. $pos = [$anchor];
  6514. }
  6515. $pos = array_values(array_filter($pos, function ($po) {
  6516. if (!is_array($po)) {
  6517. return false;
  6518. }
  6519. $mr = $po['mod_rq'] ?? null;
  6520. if ($mr === null || $mr === '') {
  6521. return true;
  6522. }
  6523. $mrs = trim((string)$mr);
  6524. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6525. }));
  6526. if ($pos === []) {
  6527. $pos = [$anchor];
  6528. }
  6529. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6530. if ($rows === []) {
  6531. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6532. }
  6533. return $rows;
  6534. }
  6535. /**
  6536. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6537. *
  6538. * @param array<int, array<string, mixed>> $mergeRows
  6539. * @return array<int, array<string, mixed>>
  6540. */
  6541. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6542. {
  6543. $list = array_values($mergeRows);
  6544. $n = count($list);
  6545. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6546. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6547. $mergeSame = $n > 1 && $orderKey0 !== '';
  6548. if ($mergeSame) {
  6549. foreach ($list as $rr) {
  6550. if (!is_array($rr)) {
  6551. $mergeSame = false;
  6552. break;
  6553. }
  6554. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6555. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6556. $mergeSame = false;
  6557. break;
  6558. }
  6559. }
  6560. }
  6561. $out = [];
  6562. foreach ($list as $idx => $r) {
  6563. if (!is_array($r)) {
  6564. continue;
  6565. }
  6566. $qty = $this->resolveProcuremenThisQuantity($r);
  6567. $price = $this->resolveProcuremenCeilingPrice($r);
  6568. $sid = $this->extractScydgyRowId($r);
  6569. $out[] = [
  6570. 'seq' => $idx + 1,
  6571. 'scydgy_id' => $sid,
  6572. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6573. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6574. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6575. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6576. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6577. 'NGZL' => $r['NGZL'] ?? '',
  6578. 'This_quantity' => $qty,
  6579. 'ceilingPrice' => $price,
  6580. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6581. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6582. 'show_order_cells' => !$mergeSame || $idx === 0,
  6583. 'order_rowspan' => $mergeSame ? $n : 1,
  6584. ];
  6585. }
  6586. return $out;
  6587. }
  6588. /**
  6589. * 解析金额/数量(去千分位等非数字字符)
  6590. */
  6591. protected function parseProcuremenMoneyNumber($value): ?float
  6592. {
  6593. if ($value === null || $value === '') {
  6594. return null;
  6595. }
  6596. if (is_numeric($value)) {
  6597. return (float)$value;
  6598. }
  6599. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6600. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6601. }
  6602. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6603. {
  6604. if ($amount === null) {
  6605. return '';
  6606. }
  6607. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6608. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6609. return $s === '' ? '0' : $s;
  6610. }
  6611. /**
  6612. * 列表/详情展示:工作量为 0 时显示空
  6613. */
  6614. protected function formatProcuremenWorkloadDisplay($value): string
  6615. {
  6616. if ($value === null || $value === '') {
  6617. return '';
  6618. }
  6619. $s = trim((string)$value);
  6620. if ($s === '') {
  6621. return '';
  6622. }
  6623. if (is_numeric($s) && (float)$s == 0) {
  6624. return '';
  6625. }
  6626. return $s;
  6627. }
  6628. /**
  6629. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6630. */
  6631. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6632. {
  6633. foreach ($details as $d) {
  6634. if (!is_array($d)) {
  6635. continue;
  6636. }
  6637. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6638. $cn = trim((string)($d['company_name'] ?? ''));
  6639. if ($cn !== '') {
  6640. return $cn;
  6641. }
  6642. }
  6643. }
  6644. return trim((string)($main['pick_company_name'] ?? ''));
  6645. }
  6646. /**
  6647. * 详情报价小计:单价 × 本工序本次数量
  6648. */
  6649. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6650. {
  6651. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6652. if ($unit === null) {
  6653. return null;
  6654. }
  6655. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6656. if ($qty === null || $qty <= 0) {
  6657. return null;
  6658. }
  6659. return $unit * $qty;
  6660. }
  6661. /**
  6662. * 详情页:工序小计 + 供应商分组报价与总计
  6663. *
  6664. * @param array<int, array<string, mixed>> $mergeRows
  6665. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6666. * @return array{
  6667. * process_rows: array,
  6668. * supplier_groups: array,
  6669. * order_total_text: string,
  6670. * order_total_has: bool,
  6671. * selected_company: string
  6672. * }
  6673. */
  6674. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6675. {
  6676. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6677. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6678. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6679. || ((int)($main['manual_pick'] ?? 0) === 1);
  6680. $qtyBySid = [];
  6681. $gymcBySid = [];
  6682. $orderedSids = [];
  6683. foreach ($mergeRows as $mr) {
  6684. if (!is_array($mr)) {
  6685. continue;
  6686. }
  6687. $sid = $this->extractScydgyRowId($mr);
  6688. if ($this->isValidScydgyRowId($sid)) {
  6689. $orderedSids[] = $sid;
  6690. }
  6691. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6692. if ($qty === '') {
  6693. $qty = trim((string)($mr['NGZL'] ?? ''));
  6694. }
  6695. $qtyBySid[$sid] = $qty;
  6696. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6697. }
  6698. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6699. $detailByCompanySid = [];
  6700. foreach ($details as $d) {
  6701. if (!is_array($d)) {
  6702. continue;
  6703. }
  6704. $cn = trim((string)($d['company_name'] ?? ''));
  6705. $sid = (int)($d['scydgy_id'] ?? 0);
  6706. if ($cn === '' || $sid === 0) {
  6707. continue;
  6708. }
  6709. if (!isset($detailByCompanySid[$cn])) {
  6710. $detailByCompanySid[$cn] = [];
  6711. }
  6712. $detailByCompanySid[$cn][$sid] = $d;
  6713. }
  6714. $supplierGroups = [];
  6715. foreach ($detailByCompanySid as $cn => $bySid) {
  6716. $lines = [];
  6717. $groupTotal = 0.0;
  6718. $groupHas = false;
  6719. $groupVoid = true;
  6720. $usedSids = [];
  6721. $appendLine = function (int $sid, array $d) use (
  6722. &$lines,
  6723. &$groupTotal,
  6724. &$groupHas,
  6725. &$groupVoid,
  6726. $qtyBySid,
  6727. $gymcBySid,
  6728. $quoteVisible
  6729. ) {
  6730. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6731. if (!$isVoid) {
  6732. $groupVoid = false;
  6733. }
  6734. $qtyStr = $qtyBySid[$sid] ?? '';
  6735. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6736. $am = trim((string)($d['amount'] ?? ''));
  6737. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6738. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6739. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6740. $sub = null;
  6741. if (!$isVoid && $amountNum !== null) {
  6742. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6743. }
  6744. $ct = $this->resolveDetailSupplierOperTime($d);
  6745. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6746. $leadFilled = ($leadDays !== null);
  6747. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6748. $line = [
  6749. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6750. 'amount' => $am,
  6751. 'unit_price_text' => $amountFilled
  6752. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6753. : '未填写',
  6754. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6755. 'delivery_ymd' => $deliveryYmd,
  6756. 'amount_filled' => $amountFilled,
  6757. 'delivery_filled' => $deliveryFilled,
  6758. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6759. 'lead_days' => $leadFilled ? $leadDays : '',
  6760. 'lead_days_filled'=> $leadFilled,
  6761. 'lead_days_show' => $leadText,
  6762. 'lead_days_text' => $leadText,
  6763. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6764. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6765. 'is_void' => $isVoid,
  6766. 'oper_time_text' => $ct,
  6767. ];
  6768. if (!$quoteVisible && !$isVoid) {
  6769. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6770. } elseif ($sub !== null) {
  6771. $groupTotal += $sub;
  6772. $groupHas = true;
  6773. }
  6774. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6775. };
  6776. foreach ($orderedSids as $sid) {
  6777. if (!isset($bySid[$sid])) {
  6778. continue;
  6779. }
  6780. $usedSids[$sid] = true;
  6781. $appendLine($sid, $bySid[$sid]);
  6782. }
  6783. foreach ($bySid as $sid => $d) {
  6784. if (isset($usedSids[$sid])) {
  6785. continue;
  6786. }
  6787. $appendLine((int)$sid, $d);
  6788. }
  6789. $firstDetail = null;
  6790. foreach ($bySid as $d) {
  6791. if (is_array($d)) {
  6792. $firstDetail = $d;
  6793. break;
  6794. }
  6795. }
  6796. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6797. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6798. if ($username === '' && $ph !== '') {
  6799. $username = $this->resolveCustomerContactName($ph, $cn);
  6800. }
  6801. $remark = '';
  6802. foreach ($bySid as $d) {
  6803. if (!is_array($d)) {
  6804. continue;
  6805. }
  6806. $rm = '';
  6807. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6808. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6809. $rm = trim((string)$d[$rk]);
  6810. break;
  6811. }
  6812. }
  6813. if ($rm !== '') {
  6814. $remark = $rm;
  6815. break;
  6816. }
  6817. }
  6818. $lineCount = count($lines);
  6819. $hasRemark = $lineCount > 0;
  6820. $supplierGroup = [
  6821. 'company_name' => $cn,
  6822. 'username' => $username,
  6823. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6824. 'phone' => $ph,
  6825. 'remark' => $remark,
  6826. 'has_remark' => $hasRemark,
  6827. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6828. 'is_void' => $groupVoid,
  6829. 'lines' => $lines,
  6830. 'line_count' => $lineCount,
  6831. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6832. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6833. 'has_total' => $lineCount > 0,
  6834. ];
  6835. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6836. $supplierGroups[] = $supplierGroup;
  6837. }
  6838. usort($supplierGroups, function ($a, $b) {
  6839. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6840. return ($a['is_void'] ?? false) ? 1 : -1;
  6841. }
  6842. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6843. return ($a['is_selected'] ?? false) ? -1 : 1;
  6844. }
  6845. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6846. });
  6847. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6848. return [
  6849. 'process_rows' => $processRows,
  6850. 'supplier_groups' => $supplierGroups,
  6851. 'order_total_text' => '',
  6852. 'order_total_has' => false,
  6853. 'selected_company' => $selectedCompany,
  6854. ];
  6855. }
  6856. /**
  6857. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6858. */
  6859. protected function buildProcessLinesPlain(array $mergeRows): string
  6860. {
  6861. $lines = [];
  6862. $i = 1;
  6863. foreach ($mergeRows as $r) {
  6864. if (!is_array($r)) {
  6865. continue;
  6866. }
  6867. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6868. $dw = trim((string)($r['CDW'] ?? ''));
  6869. $gzl = trim((string)($r['NGZL'] ?? ''));
  6870. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6871. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6872. if ($dw !== '') {
  6873. $parts[] = '单位:' . $dw;
  6874. }
  6875. if ($gzl !== '') {
  6876. $parts[] = '工作量:' . $gzl;
  6877. }
  6878. if ($qty !== '') {
  6879. $parts[] = '本次数量:' . $qty;
  6880. }
  6881. $lines[] = implode(' ', $parts);
  6882. $i++;
  6883. }
  6884. return implode("\n", $lines);
  6885. }
  6886. /**
  6887. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6888. *
  6889. * @return array<string, string>
  6890. */
  6891. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6892. {
  6893. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6894. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6895. }
  6896. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6897. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6898. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6899. $cyjmc = '';
  6900. foreach ($mergeRows as $mr) {
  6901. if (!is_array($mr)) {
  6902. continue;
  6903. }
  6904. if ($ccydh === '') {
  6905. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6906. }
  6907. if ($cyjmc === '') {
  6908. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6909. }
  6910. }
  6911. if ($pos !== []) {
  6912. $firstPo = $pos[0];
  6913. if (is_array($firstPo)) {
  6914. if ($ccydh === '') {
  6915. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6916. }
  6917. if ($cyjmc === '') {
  6918. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6919. }
  6920. }
  6921. }
  6922. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6923. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6924. if (is_array($any)) {
  6925. if ($ccydh === '') {
  6926. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6927. }
  6928. if ($cyjmc === '') {
  6929. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6930. }
  6931. }
  6932. }
  6933. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6934. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6935. $cgymc = '';
  6936. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6937. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6938. }
  6939. return [
  6940. 'ccydh' => $ccydh,
  6941. 'cyjmc' => $cyjmc,
  6942. 'cgymc' => $cgymc,
  6943. 'process_lines' => $processLines,
  6944. 'process_lines_html' => '',
  6945. ];
  6946. }
  6947. /**
  6948. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6949. */
  6950. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6951. {
  6952. $lines = [];
  6953. if ($ccydh !== '') {
  6954. $lines[] = '订单号:' . $ccydh;
  6955. }
  6956. if ($cyjmc !== '') {
  6957. $lines[] = '印件名称:' . $cyjmc;
  6958. }
  6959. if ($processPlain !== '') {
  6960. $lines[] = $processPlain;
  6961. }
  6962. return implode("\n", $lines);
  6963. }
  6964. /**
  6965. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6966. *
  6967. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6968. */
  6969. protected function buildPlatformLinksPlain(array $detailLinks): string
  6970. {
  6971. $lines = [];
  6972. $i = 1;
  6973. foreach ($detailLinks as $lk) {
  6974. if (!is_array($lk)) {
  6975. continue;
  6976. }
  6977. $url = trim((string)($lk['url'] ?? ''));
  6978. if ($url === '') {
  6979. continue;
  6980. }
  6981. $label = trim((string)($lk['cgymc'] ?? ''));
  6982. if ($label === '') {
  6983. $label = '工序' . $i;
  6984. }
  6985. $lines[] = $label . ':' . $url;
  6986. $i++;
  6987. }
  6988. return implode("\n", $lines);
  6989. }
  6990. /**
  6991. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6992. *
  6993. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6994. */
  6995. protected function buildPlatformLinksHtml(array $detailLinks): string
  6996. {
  6997. $parts = [];
  6998. $i = 1;
  6999. foreach ($detailLinks as $lk) {
  7000. if (!is_array($lk)) {
  7001. continue;
  7002. }
  7003. $url = trim((string)($lk['url'] ?? ''));
  7004. if ($url === '') {
  7005. continue;
  7006. }
  7007. $label = trim((string)($lk['cgymc'] ?? ''));
  7008. if ($label === '') {
  7009. $label = '工序' . $i;
  7010. }
  7011. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7012. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7013. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7014. $i++;
  7015. }
  7016. return implode("<br>\n", $parts);
  7017. }
  7018. /**
  7019. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7020. *
  7021. * @return array<string, mixed>
  7022. */
  7023. protected function loadMailerConfig(): array
  7024. {
  7025. try {
  7026. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7027. } catch (\Throwable $e) {
  7028. $cfg = [];
  7029. }
  7030. return is_array($cfg) ? $cfg : [];
  7031. }
  7032. protected function loadNotifyTemplateRow(string $scene): ?array
  7033. {
  7034. try {
  7035. $row = Db::table('purchase_sms_template')
  7036. ->where('scene', $scene)
  7037. ->where(function ($q) {
  7038. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7039. })
  7040. ->order('id', 'asc')
  7041. ->find();
  7042. } catch (\Throwable $e) {
  7043. return null;
  7044. }
  7045. if (!is_array($row) || $row === []) {
  7046. return null;
  7047. }
  7048. return [
  7049. 'title' => trim((string)($row['title'] ?? '')),
  7050. 'content' => trim((string)($row['content'] ?? '')),
  7051. ];
  7052. }
  7053. /**
  7054. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7055. */
  7056. protected function buildProcessLinesHtml(array $mergeRows): string
  7057. {
  7058. if (count($mergeRows) <= 1) {
  7059. $r = $mergeRows[0] ?? [];
  7060. if (!is_array($r)) {
  7061. return '';
  7062. }
  7063. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7064. $dw = trim((string)($r['CDW'] ?? ''));
  7065. $gzl = trim((string)($r['NGZL'] ?? ''));
  7066. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7067. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7068. if ($dw !== '') {
  7069. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7070. }
  7071. if ($gzl !== '') {
  7072. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7073. }
  7074. if ($qty !== '') {
  7075. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7076. }
  7077. return $html;
  7078. }
  7079. $rows = '';
  7080. $i = 1;
  7081. foreach ($mergeRows as $r) {
  7082. if (!is_array($r)) {
  7083. continue;
  7084. }
  7085. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7086. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7087. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7088. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7089. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7090. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7091. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7092. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7093. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7094. $i++;
  7095. }
  7096. if ($rows === '') {
  7097. return '';
  7098. }
  7099. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7100. . '<thead><tr style="background:#f5f5f5;">'
  7101. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7102. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7103. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7104. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7105. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7106. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7107. }
  7108. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7109. {
  7110. $sysRq = trim($sysRq);
  7111. if ($sysRq === '') {
  7112. if ($required) {
  7113. $this->error('请选择招标截止日期');
  7114. }
  7115. return '';
  7116. }
  7117. $ts = strtotime($sysRq);
  7118. if ($ts === false || $ts <= 0) {
  7119. $this->error('招标截止日期格式无效');
  7120. }
  7121. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7122. if (!$allowPast) {
  7123. $ymd = date('Y-m-d', $ts);
  7124. if ($ymd < date('Y-m-d')) {
  7125. $this->error('招标截止日期不能早于今天');
  7126. }
  7127. if ($ts <= time()) {
  7128. $this->error('招标截止时间不能早于当前时间');
  7129. }
  7130. }
  7131. return date('Y-m-d H:i:s', $ts);
  7132. }
  7133. /**
  7134. * 确保 purchase_order.czlyq(类型)存在
  7135. */
  7136. protected function ensurePurchaseOrderCzlyqColumn(): void
  7137. {
  7138. static $done = false;
  7139. if ($done) {
  7140. return;
  7141. }
  7142. $done = true;
  7143. try {
  7144. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7145. if (empty($cols)) {
  7146. Db::execute(
  7147. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7148. );
  7149. }
  7150. } catch (\Throwable $e) {
  7151. // ignore
  7152. }
  7153. }
  7154. /**
  7155. * 确保 purchase_order.delivery_deadline 存在
  7156. */
  7157. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7158. {
  7159. static $done = false;
  7160. if ($done) {
  7161. return;
  7162. }
  7163. $done = true;
  7164. try {
  7165. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7166. if (empty($cols)) {
  7167. Db::execute(
  7168. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7169. );
  7170. }
  7171. } catch (\Throwable $e) {
  7172. // ignore
  7173. }
  7174. }
  7175. /**
  7176. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7177. */
  7178. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7179. {
  7180. static $done = false;
  7181. if ($done) {
  7182. return;
  7183. }
  7184. $done = true;
  7185. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7186. $adds = [
  7187. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7188. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7189. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7190. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7191. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7192. ];
  7193. $changed = false;
  7194. foreach ($adds as $col => $ddl) {
  7195. try {
  7196. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7197. if (!is_array($cols) || $cols === []) {
  7198. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7199. $changed = true;
  7200. }
  7201. } catch (\Throwable $e) {
  7202. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7203. }
  7204. }
  7205. if ($changed) {
  7206. $this->clearPurchaseOrderTableFieldsCache();
  7207. }
  7208. }
  7209. /**
  7210. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7211. */
  7212. protected function clearPurchaseOrderTableFieldsCache(): void
  7213. {
  7214. try {
  7215. $db = (string)Config::get('database.database');
  7216. $key = $db . '.purchase_order';
  7217. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7218. $ref->setAccessible(true);
  7219. $info = $ref->getValue();
  7220. if (is_array($info) && isset($info[$key])) {
  7221. unset($info[$key]);
  7222. $ref->setValue(null, $info);
  7223. }
  7224. } catch (\Throwable $e) {
  7225. }
  7226. try {
  7227. $db = (string)Config::get('database.database');
  7228. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7229. if (is_file($schemaFile)) {
  7230. @unlink($schemaFile);
  7231. }
  7232. } catch (\Throwable $e) {
  7233. }
  7234. }
  7235. /**
  7236. * @return array<string, bool>
  7237. */
  7238. protected function loadPurchaseOrderColumnSet(): array
  7239. {
  7240. static $set = null;
  7241. if (is_array($set)) {
  7242. return $set;
  7243. }
  7244. $set = [];
  7245. try {
  7246. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7247. } catch (\Throwable $e) {
  7248. return $set;
  7249. }
  7250. if (!is_array($cols)) {
  7251. return $set;
  7252. }
  7253. foreach ($cols as $c) {
  7254. if (!is_array($c)) {
  7255. continue;
  7256. }
  7257. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7258. if ($f !== '') {
  7259. $set[$f] = true;
  7260. }
  7261. }
  7262. return $set;
  7263. }
  7264. /**
  7265. * 解析交货截止日期(仅年月日)
  7266. */
  7267. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7268. {
  7269. $raw = trim($raw);
  7270. if ($raw === '') {
  7271. if ($required) {
  7272. $this->error('请选择交货截止日期');
  7273. }
  7274. return '';
  7275. }
  7276. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7277. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7278. } else {
  7279. $ts = strtotime(str_replace('/', '-', $raw));
  7280. if ($ts === false || $ts <= 0) {
  7281. $this->error('交货截止日期格式无效');
  7282. }
  7283. $ymd = date('Y-m-d', $ts);
  7284. }
  7285. if ($ymd < date('Y-m-d')) {
  7286. $this->error('交货截止日期不能早于今天');
  7287. }
  7288. return $ymd;
  7289. }
  7290. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7291. {
  7292. $s = trim((string)$value);
  7293. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7294. return '';
  7295. }
  7296. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7297. return $m[1];
  7298. }
  7299. $ts = strtotime(str_replace('/', '-', $s));
  7300. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7301. }
  7302. /**
  7303. * @param array{pos?:array} $bundle
  7304. */
  7305. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7306. {
  7307. foreach ($bundle['pos'] ?? [] as $po) {
  7308. if (!is_array($po)) {
  7309. continue;
  7310. }
  7311. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7312. if ($d !== '') {
  7313. return $d;
  7314. }
  7315. }
  7316. return '';
  7317. }
  7318. protected function formatProcuremenSysRqForInput($sysRq): string
  7319. {
  7320. $sr = trim((string)$sysRq);
  7321. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7322. return '';
  7323. }
  7324. $ts = strtotime($sr);
  7325. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7326. }
  7327. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7328. {
  7329. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7330. if ($sr === '') {
  7331. return '—';
  7332. }
  7333. $ts = strtotime($sr);
  7334. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7335. }
  7336. /**
  7337. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7338. *
  7339. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7340. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7341. */
  7342. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7343. {
  7344. return $bundle;
  7345. }
  7346. /**
  7347. * 写入/更新 purchase_order(单道工序行)
  7348. *
  7349. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7350. */
  7351. protected function upsertPurchaseOrderFromRow(
  7352. array $row,
  7353. string $sysRqDb,
  7354. $wflowStatus = null,
  7355. ?string $pickTime = null,
  7356. ?array $exists = null,
  7357. ?string $deliveryDeadline = null,
  7358. $scoreRuleId = null
  7359. ): void {
  7360. $ids = $this->extractScydgyRowId($row);
  7361. if (!$this->isValidScydgyRowId($ids)) {
  7362. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7363. }
  7364. if ($exists === null) {
  7365. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7366. }
  7367. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7368. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7369. $this->ensurePurchaseOrderCzlyqColumn();
  7370. $data = [
  7371. 'scydgy_id' => $ids,
  7372. 'CCYDH' => $row['CCYDH'] ?? null,
  7373. 'CYJMC' => $row['CYJMC'] ?? null,
  7374. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7375. 'CDXMC' => $row['CDXMC'] ?? null,
  7376. 'CGYBH' => $row['CGYBH'] ?? null,
  7377. 'CGYMC' => $row['CGYMC'] ?? null,
  7378. 'CDW' => $row['CDW'] ?? null,
  7379. 'czlyq' => $row['czlyq'] ?? null,
  7380. 'NGZL' => $row['NGZL'] ?? null,
  7381. 'CDF' => $row['CDF'] ?? null,
  7382. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7383. 'MBZ' => $row['MBZ'] ?? null,
  7384. 'bwjg' => $row['bwjg'] ?? null,
  7385. 'iStatus' => $row['iStatus'] ?? null,
  7386. 'dStamp' => $row['dStamp'] ?? null,
  7387. 'dputrecord' => $row['dputrecord'] ?? null,
  7388. 'cywyxm' => $row['cywyxm'] ?? null,
  7389. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7390. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7391. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7392. 'sys_rq' => $sysRqDb,
  7393. ];
  7394. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7395. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7396. if ($qtyUp === '') {
  7397. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7398. 'This_quantity' => '',
  7399. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7400. ]);
  7401. if ($qtyFallback !== '') {
  7402. $data['This_quantity'] = $qtyFallback;
  7403. }
  7404. }
  7405. if ($deliveryDeadline !== null) {
  7406. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7407. }
  7408. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7409. $scoreRule = null;
  7410. if (is_array($scoreRuleId)) {
  7411. $scoreRule = $scoreRuleId;
  7412. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7413. } else {
  7414. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7415. }
  7416. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7417. $poCols = $this->loadPurchaseOrderColumnSet();
  7418. if (!empty($poCols['score_rule_id'])) {
  7419. $data['score_rule_id'] = $scoreRuleId;
  7420. if (is_array($scoreRule)) {
  7421. if (!empty($poCols['score_rule_name'])) {
  7422. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7423. }
  7424. if (!empty($poCols['score_quality_weight'])) {
  7425. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7426. }
  7427. if (!empty($poCols['score_price_weight'])) {
  7428. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7429. }
  7430. if (!empty($poCols['score_lead_weight'])) {
  7431. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7432. }
  7433. }
  7434. }
  7435. }
  7436. if ($wflowStatus !== null && $wflowStatus !== '') {
  7437. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7438. }
  7439. if ($pickTime !== null && $pickTime !== '') {
  7440. $data['pick_time'] = $pickTime;
  7441. $data['pick_company_name'] = '';
  7442. }
  7443. if ($exists) {
  7444. $upd = $data;
  7445. unset($upd['scydgy_id']);
  7446. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7447. } else {
  7448. $data['createtime'] = date('Y-m-d H:i:s');
  7449. Db::table('purchase_order')->insert($data);
  7450. }
  7451. }
  7452. /**
  7453. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7454. *
  7455. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7456. */
  7457. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7458. {
  7459. $toDb = function ($value) {
  7460. if ($value === null) {
  7461. return null;
  7462. }
  7463. if (is_scalar($value)) {
  7464. return $value;
  7465. }
  7466. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7467. };
  7468. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7469. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7470. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7471. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7472. if ($username === '') {
  7473. $username = $this->resolveCustomerContactName($phone, $companyName);
  7474. }
  7475. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7476. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7477. }
  7478. if ($requirePhone && $phone === '') {
  7479. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7480. }
  7481. $detailLinks = [];
  7482. foreach ($mergeRows as $row) {
  7483. if (!is_array($row)) {
  7484. continue;
  7485. }
  7486. $sid = $this->extractScydgyRowId($row);
  7487. $detailId = 0;
  7488. if ($skipExisting) {
  7489. try {
  7490. $existsQuery = Db::table('purchase_order_detail')
  7491. ->where('scydgy_id', $sid)
  7492. ->where('company_name', $companyName);
  7493. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7494. $exists = $existsQuery->find();
  7495. } catch (\Throwable $e) {
  7496. $exists = null;
  7497. }
  7498. if (is_array($exists)) {
  7499. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7500. }
  7501. }
  7502. if ($detailId <= 0) {
  7503. $one = [
  7504. 'scydgy_id' => $toDb($sid),
  7505. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7506. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7507. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7508. 'username' => $username !== '' ? $username : null,
  7509. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7510. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7511. 'createtime' => date('Y-m-d H:i:s'),
  7512. 'status' => ProcuremenStatus::POD_UNPICKED,
  7513. 'status_name' => '未提交',
  7514. ];
  7515. Db::table('purchase_order_detail')->insert($one);
  7516. $detailId = (int)Db::getLastInsID();
  7517. }
  7518. $mprocUrl = '';
  7519. if ($buildMobileLinks && $detailId > 0) {
  7520. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7521. }
  7522. $detailLinks[] = [
  7523. 'detail_id' => $detailId,
  7524. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7525. 'url' => $mprocUrl,
  7526. ];
  7527. }
  7528. $this->invalidatePickHiddenScydgyCache();
  7529. return $detailLinks;
  7530. }
  7531. /**
  7532. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7533. * @return array<string, mixed>
  7534. */
  7535. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7536. {
  7537. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7538. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7539. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7540. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7541. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7542. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7543. $isMerge = !empty($ctx['is_merge']);
  7544. $contactName = trim((string)($c['username'] ?? ''));
  7545. if ($contactName === '') {
  7546. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7547. }
  7548. $notifyVars = [
  7549. 'company_name' => $companyName,
  7550. 'contact_name' => $contactName,
  7551. 'phone' => $phone,
  7552. 'email' => $toEmail,
  7553. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7554. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7555. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7556. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7557. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7558. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7559. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7560. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7561. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7562. 'platform_url' => $platformUrl,
  7563. 'platform_links' => $platformLinksPlain,
  7564. 'platform_links_html' => $platformLinksHtml,
  7565. ];
  7566. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7567. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7568. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7569. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7570. $mailBody = $this->appendPlatformTapLinkToEmailHtml($mailBody, $platformUrl);
  7571. return [
  7572. 'company_name' => $companyName,
  7573. 'phone' => $phone,
  7574. 'email' => $toEmail,
  7575. 'sms_content' => $smsContent,
  7576. 'mail_plain' => $mailPlain,
  7577. 'mail_body' => $mailBody,
  7578. 'notify_vars' => $notifyVars,
  7579. 'detail_links' => $detailLinks,
  7580. ];
  7581. }
  7582. /**
  7583. * @param array<string, mixed> $chosen
  7584. * @param array<int, array<string, mixed>> $mergeRows
  7585. * @param array{ccydh:string, pos:array} $bundle
  7586. */
  7587. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7588. {
  7589. if (!$sendSms && !$sendEmail) {
  7590. return;
  7591. }
  7592. $companyName = trim((string)($chosen['name'] ?? ''));
  7593. $phone = trim((string)($chosen['phone'] ?? ''));
  7594. $toEmail = trim((string)($chosen['email'] ?? ''));
  7595. if ($companyName === '') {
  7596. throw new \Exception('供应商名称无效');
  7597. }
  7598. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7599. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7600. }
  7601. if ($sendSms && $phone === '') {
  7602. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7603. }
  7604. $sids = [];
  7605. foreach ($mergeRows as $mr) {
  7606. if (!is_array($mr)) {
  7607. continue;
  7608. }
  7609. $sid = $this->extractScydgyRowId($mr);
  7610. if ($this->isValidScydgyRowId($sid)) {
  7611. $sids[$sid] = true;
  7612. }
  7613. }
  7614. if ($sids === []) {
  7615. throw new \Exception('未找到工序行,无法发送通知');
  7616. }
  7617. $sysRqNotify = '';
  7618. $pos = $bundle['pos'] ?? [];
  7619. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7620. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7621. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7622. $ts = strtotime($sr);
  7623. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7624. }
  7625. }
  7626. try {
  7627. $detailsQuery = Db::table('purchase_order_detail')
  7628. ->where('scydgy_id', 'in', array_keys($sids))
  7629. ->where('company_name', $companyName);
  7630. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7631. $details = $detailsQuery->order('id', 'asc')->select();
  7632. } catch (\Throwable $e) {
  7633. $details = [];
  7634. }
  7635. if (!is_array($details) || $details === []) {
  7636. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7637. try {
  7638. $detailsQuery = Db::table('purchase_order_detail')
  7639. ->where('scydgy_id', 'in', array_keys($sids))
  7640. ->where('company_name', $companyName);
  7641. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7642. $details = $detailsQuery->order('id', 'asc')->select();
  7643. } catch (\Throwable $e) {
  7644. $details = [];
  7645. }
  7646. }
  7647. if (!is_array($details) || $details === []) {
  7648. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7649. }
  7650. $detailLinks = [];
  7651. foreach ($details as $d) {
  7652. if (!is_array($d)) {
  7653. continue;
  7654. }
  7655. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7656. if ($detailId <= 0) {
  7657. continue;
  7658. }
  7659. $sid = (int)($d['scydgy_id'] ?? 0);
  7660. $gymc = '';
  7661. foreach ($mergeRows as $mr) {
  7662. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7663. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7664. break;
  7665. }
  7666. }
  7667. $detailLinks[] = [
  7668. 'detail_id' => $detailId,
  7669. 'cgymc' => $gymc,
  7670. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7671. ];
  7672. }
  7673. if ($detailLinks === []) {
  7674. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7675. }
  7676. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7677. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7678. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7679. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7680. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7681. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7682. $notifyBundle['email_log_scene'] = $emailLogScene;
  7683. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7684. $poIdLog = 0;
  7685. $pos = $bundle['pos'] ?? [];
  7686. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7687. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7688. }
  7689. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7690. if ($sendEmail) {
  7691. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7692. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7693. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7694. }
  7695. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7696. $mailConfig = $this->loadMailerConfig();
  7697. if (!$this->isProcuremenNotifyDryRun()) {
  7698. if (empty($mailConfig['host'])) {
  7699. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7700. }
  7701. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7702. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7703. }
  7704. }
  7705. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7706. }
  7707. if ($sendSms) {
  7708. $this->issueSendSupplierSms($notifyBundle);
  7709. }
  7710. }
  7711. /**
  7712. * @param array<int, array<string, mixed>> $quoteGroups
  7713. * @return array<int, array<string, mixed>>
  7714. */
  7715. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7716. {
  7717. $names = [];
  7718. if (is_string($companiesJson) && $companiesJson !== '') {
  7719. $decoded = json_decode($companiesJson, true);
  7720. if (is_array($decoded)) {
  7721. foreach ($decoded as $nm) {
  7722. $nm = trim((string)$nm);
  7723. if ($nm !== '') {
  7724. $names[] = $nm;
  7725. }
  7726. }
  7727. }
  7728. }
  7729. $names = array_values(array_unique($names));
  7730. if ($names === [] && $selectedCompany !== '') {
  7731. $names = [$selectedCompany];
  7732. }
  7733. if ($names === []) {
  7734. return $quoteGroups;
  7735. }
  7736. $targets = [];
  7737. foreach ($quoteGroups as $g) {
  7738. if (!is_array($g)) {
  7739. continue;
  7740. }
  7741. $cn = trim((string)($g['name'] ?? ''));
  7742. if ($cn !== '' && in_array($cn, $names, true)) {
  7743. $targets[] = $g;
  7744. }
  7745. }
  7746. return $targets;
  7747. }
  7748. /**
  7749. * @return array{pos:array, merge_rows:array, bundle:array}
  7750. */
  7751. protected function loadAuditResendBundle(string $scydgyId): array
  7752. {
  7753. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7754. $pos = $bundle['pos'];
  7755. $mergeRows = $bundle['merge_rows'];
  7756. if ($pos === [] || $mergeRows === []) {
  7757. $this->error('该订单不在待确认供应商状态');
  7758. }
  7759. $sysRqDb = '';
  7760. if (isset($pos[0]) && is_array($pos[0])) {
  7761. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7762. }
  7763. foreach ($pos as $i => $poRow) {
  7764. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7765. $pos[$i]['sys_rq'] = $sysRqDb;
  7766. }
  7767. }
  7768. $bundle['pos'] = $pos;
  7769. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7770. }
  7771. /**
  7772. * @param array<int, array<string, mixed>> $targets
  7773. */
  7774. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7775. {
  7776. if ($targets === []) {
  7777. $this->error('未找到可通知的供应商');
  7778. }
  7779. $notifyErrors = [];
  7780. try {
  7781. $this->notifyDryRunPreview = [];
  7782. foreach ($targets as $g) {
  7783. if (!is_array($g)) {
  7784. continue;
  7785. }
  7786. $cname = trim((string)($g['name'] ?? ''));
  7787. if ($cname === '') {
  7788. continue;
  7789. }
  7790. $chosen = [
  7791. 'name' => $cname,
  7792. 'company_name' => $cname,
  7793. 'email' => trim((string)($g['email'] ?? '')),
  7794. 'phone' => trim((string)($g['phone'] ?? '')),
  7795. 'username' => trim((string)($g['username'] ?? '')),
  7796. ];
  7797. try {
  7798. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7799. } catch (\Throwable $e) {
  7800. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7801. }
  7802. }
  7803. } catch (\Throwable $e) {
  7804. $this->error('通知发送失败:' . $e->getMessage());
  7805. }
  7806. if ($notifyErrors !== []) {
  7807. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7808. }
  7809. if ($this->isProcuremenNotifyDryRun()) {
  7810. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7811. 'notify_dry_run' => true,
  7812. 'notify_preview' => $this->notifyDryRunPreview,
  7813. ]);
  7814. }
  7815. $nameLabels = [];
  7816. foreach ($targets as $g) {
  7817. if (!is_array($g)) {
  7818. continue;
  7819. }
  7820. $n = trim((string)($g['name'] ?? ''));
  7821. if ($n !== '') {
  7822. $nameLabels[] = $n;
  7823. }
  7824. }
  7825. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7826. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7827. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7828. $seenLogSid = [];
  7829. foreach ($bundle['pos'] ?? [] as $poRow) {
  7830. if (!is_array($poRow)) {
  7831. continue;
  7832. }
  7833. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7834. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7835. continue;
  7836. }
  7837. $seenLogSid[$sid] = true;
  7838. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7839. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7840. }
  7841. if ($seenLogSid === []) {
  7842. foreach ($mergeRows as $mr) {
  7843. if (!is_array($mr)) {
  7844. continue;
  7845. }
  7846. $sid = $this->extractScydgyRowId($mr);
  7847. if ($this->isValidScydgyRowId($sid)) {
  7848. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7849. break;
  7850. }
  7851. }
  7852. }
  7853. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7854. }
  7855. /**
  7856. * 协助下发 — 发送短信(一家供应商)
  7857. *
  7858. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7859. */
  7860. protected function issueSendSupplierSms(array $bundle): void
  7861. {
  7862. $companyName = (string)($bundle['company_name'] ?? '');
  7863. $phone = (string)($bundle['phone'] ?? '');
  7864. $smsContent = (string)($bundle['sms_content'] ?? '');
  7865. $this->logIssueNotifyDebug('短信', [
  7866. 'company' => $companyName,
  7867. 'phone' => $phone,
  7868. 'sms_content' => $smsContent,
  7869. ]);
  7870. if ($this->isProcuremenNotifyDryRun()) {
  7871. $this->recordNotifyDryRunPreview([
  7872. 'scene' => 'issue_sms',
  7873. 'company_name' => $companyName,
  7874. 'phone' => $phone,
  7875. 'sms_content' => $smsContent,
  7876. ]);
  7877. return;
  7878. }
  7879. $this->smsbao($phone, $smsContent);
  7880. }
  7881. /**
  7882. * 协助下发 — 发送邮件(一家供应商)
  7883. *
  7884. * @param array<string, mixed> $bundle
  7885. * @param array<string, mixed> $mailConfig
  7886. */
  7887. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7888. {
  7889. $companyName = (string)($bundle['company_name'] ?? '');
  7890. $toEmail = (string)($bundle['email'] ?? '');
  7891. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7892. $mailBody = (string)($bundle['mail_body'] ?? '');
  7893. $this->logIssueNotifyDebug('邮件', [
  7894. 'company' => $companyName,
  7895. 'email' => $toEmail,
  7896. 'mail_subject' => $mailSubject,
  7897. 'mail_body' => $mailPlain,
  7898. ]);
  7899. if ($this->isProcuremenNotifyDryRun()) {
  7900. $this->recordNotifyDryRunPreview([
  7901. 'scene' => 'issue_email',
  7902. 'company_name' => $companyName,
  7903. 'email' => $toEmail,
  7904. 'mail_subject' => $mailSubject,
  7905. 'mail_body' => $mailPlain,
  7906. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7907. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7908. 'detail_links' => $bundle['detail_links'] ?? [],
  7909. ]);
  7910. return;
  7911. }
  7912. $mail = new PHPMailer(true);
  7913. $mail->isSMTP();
  7914. $mail->Host = $mailConfig['host'];
  7915. $mail->SMTPAuth = true;
  7916. $mail->Username = $mailConfig['addr'];
  7917. $mail->Password = $mailConfig['pass'];
  7918. $mail->SMTPSecure = $mailConfig['security'];
  7919. $mail->Port = $mailConfig['port'];
  7920. $mail->CharSet = $mailConfig['charset'];
  7921. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7922. $mail->addAddress($toEmail, $companyName);
  7923. $mail->isHTML(true);
  7924. $mail->Subject = $mailSubject;
  7925. $mail->Body = $mailBody;
  7926. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7927. $sendOk = true;
  7928. $failReason = '';
  7929. try {
  7930. $mail->send();
  7931. } catch (\Throwable $e) {
  7932. $sendOk = false;
  7933. $failReason = $e->getMessage();
  7934. $this->persistEmailSendLog([
  7935. 'from_email' => $fromEmail,
  7936. 'to_email' => $toEmail,
  7937. 'send_time' => date('Y-m-d H:i:s'),
  7938. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7939. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7940. 'company_name' => $companyName,
  7941. 'mail_subject' => $mailSubject,
  7942. 'status' => 0,
  7943. 'fail_reason' => $failReason,
  7944. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7945. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7946. ]);
  7947. throw $e;
  7948. }
  7949. $this->persistEmailSendLog([
  7950. 'from_email' => $fromEmail,
  7951. 'to_email' => $toEmail,
  7952. 'send_time' => date('Y-m-d H:i:s'),
  7953. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7954. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7955. 'company_name' => $companyName,
  7956. 'mail_subject' => $mailSubject,
  7957. 'status' => 1,
  7958. 'fail_reason' => '',
  7959. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7960. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7961. ]);
  7962. }
  7963. /**
  7964. * 下发通知:解析订单类型名称与评分比例文案
  7965. *
  7966. * @param array<string, mixed> $bundle
  7967. * @return array{order_type:string,score_weights:string}
  7968. */
  7969. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  7970. {
  7971. $orderType = '';
  7972. $scoreWeights = '';
  7973. $rule = null;
  7974. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  7975. $rule = $bundle['score_rule'];
  7976. }
  7977. $pos = $bundle['pos'] ?? [];
  7978. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  7979. if ($rule === null && is_array($po0)) {
  7980. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  7981. if ($ruleId > 0) {
  7982. try {
  7983. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  7984. } catch (\Throwable $e) {
  7985. $rule = null;
  7986. }
  7987. }
  7988. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  7989. $qw = (int)($po0['score_quality_weight'] ?? 0);
  7990. $pw = (int)($po0['score_price_weight'] ?? 0);
  7991. $lw = (int)($po0['score_lead_weight'] ?? 0);
  7992. if ($qw > 0 || $pw > 0 || $lw > 0) {
  7993. $rule = [
  7994. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  7995. 'quality_weight' => $qw,
  7996. 'price_weight' => $pw,
  7997. 'lead_weight' => $lw,
  7998. ];
  7999. }
  8000. }
  8001. }
  8002. if (is_array($rule)) {
  8003. $orderType = trim((string)($rule['name'] ?? ''));
  8004. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8005. }
  8006. if ($orderType === '' && is_array($po0)) {
  8007. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8008. }
  8009. return [
  8010. 'order_type' => $orderType,
  8011. 'score_weights' => $scoreWeights,
  8012. ];
  8013. }
  8014. /**
  8015. * 评分比例文案:质量30%、价格50%、交货20%
  8016. *
  8017. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8018. */
  8019. protected function formatScoreRuleWeightsText(array $rule): string
  8020. {
  8021. $parts = [];
  8022. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8023. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8024. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8025. $fmt = static function ($n) {
  8026. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8027. return $s === '' ? '0' : $s;
  8028. };
  8029. if ($qw > 0) {
  8030. $parts[] = '质量' . $fmt($qw) . '%';
  8031. }
  8032. if ($pw > 0) {
  8033. $parts[] = '价格' . $fmt($pw) . '%';
  8034. }
  8035. if ($lw > 0) {
  8036. $parts[] = '交货' . $fmt($lw) . '%';
  8037. }
  8038. return implode('、', $parts);
  8039. }
  8040. /**
  8041. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8042. *
  8043. * @param array<int, array<string, mixed>> $mergeRows
  8044. * @return array<string, mixed>
  8045. */
  8046. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8047. {
  8048. $head = $mergeRows[0] ?? [];
  8049. $isMerge = count($mergeRows) > 1;
  8050. return [
  8051. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8052. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8053. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8054. 'is_merge' => $isMerge,
  8055. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8056. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8057. 'deadline' => $sysRqNotify,
  8058. 'order_type' => '',
  8059. 'score_weights' => '',
  8060. ];
  8061. }
  8062. /**
  8063. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8064. *
  8065. * @param array<string, mixed> $data
  8066. */
  8067. protected function logIssueNotifyDebug(string $type, array $data): void
  8068. {
  8069. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8070. return;
  8071. }
  8072. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8073. }
  8074. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8075. {
  8076. try {
  8077. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8078. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8079. return;
  8080. } catch (\Throwable $e) {
  8081. }
  8082. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8083. if (is_file($sqlFile)) {
  8084. $sql = file_get_contents($sqlFile);
  8085. if (is_string($sql) && $sql !== '') {
  8086. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8087. $stmt = trim($stmt);
  8088. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8089. continue;
  8090. }
  8091. try {
  8092. Db::execute($stmt);
  8093. } catch (\Throwable $ignore) {
  8094. }
  8095. }
  8096. }
  8097. }
  8098. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8099. }
  8100. /**
  8101. * @param array<string, mixed> $row
  8102. */
  8103. protected function persistEmailSendLog(array $row): void
  8104. {
  8105. try {
  8106. $this->ensurePurchaseEmailSendLogTableOnce();
  8107. } catch (\Throwable $e) {
  8108. return;
  8109. }
  8110. list($adminId, $adminName) = $this->GetUseName();
  8111. $cut = function ($s, $max) {
  8112. $s = (string)$s;
  8113. if (function_exists('mb_substr')) {
  8114. return mb_substr($s, 0, $max, 'UTF-8');
  8115. }
  8116. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8117. };
  8118. $data = [
  8119. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8120. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8121. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8122. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8123. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8124. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8125. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8126. 'status' => !empty($row['status']) ? 1 : 0,
  8127. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8128. 'admin_id' => (int)$adminId,
  8129. 'admin_name' => $cut($adminName, 64),
  8130. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8131. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8132. 'createtime' => date('Y-m-d H:i:s'),
  8133. ];
  8134. try {
  8135. Db::table('purchase_email_send_log')->insert($data);
  8136. } catch (\Throwable $e) {
  8137. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8138. }
  8139. }
  8140. protected function formatEmailLogSceneText(string $scene): string
  8141. {
  8142. $map = [
  8143. 'pick_issue' => '初选下发',
  8144. 'audit_resend' => '确认页重发',
  8145. 'rfq_salesman' => '询价通知业务员',
  8146. 'rfq_supplier' => '供应商询价通知',
  8147. ];
  8148. return $map[$scene] ?? $scene;
  8149. }
  8150. /**
  8151. * 邮件发送日志列表
  8152. */
  8153. public function emailLog()
  8154. {
  8155. $this->relationSearch = false;
  8156. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8157. $this->request->filter(['strip_tags', 'trim']);
  8158. $bakModel = $this->model;
  8159. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8160. if ($this->request->isAjax()) {
  8161. $this->ensurePurchaseEmailSendLogTableOnce();
  8162. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8163. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8164. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8165. $list = $this->model
  8166. ->where($where)
  8167. ->order($sortField, $orderDir)
  8168. ->paginate($limit);
  8169. $rows = [];
  8170. foreach ($list->items() as $item) {
  8171. $row = is_array($item) ? $item : $item->toArray();
  8172. $scene = trim((string)($row['scene'] ?? ''));
  8173. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8174. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8175. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8176. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8177. $rows[] = $row;
  8178. }
  8179. $this->model = $bakModel;
  8180. return json(['total' => $list->total(), 'rows' => $rows]);
  8181. }
  8182. $this->model = $bakModel;
  8183. return $this->view->fetch('procuremen/emaillog');
  8184. }
  8185. /**
  8186. * 协助下发弹窗(选多家供应商并通知)
  8187. */
  8188. public function pickReview()
  8189. {
  8190. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8191. $this->error(__('You have no permission'));
  8192. }
  8193. if ($this->request->isPost()) {
  8194. $this->error('请使用弹窗内「确认下发」提交');
  8195. }
  8196. $this->view->assign('pickMode', 1);
  8197. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8198. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8199. }
  8200. /**
  8201. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8202. */
  8203. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8204. {
  8205. static $done = false;
  8206. if ($done) {
  8207. return;
  8208. }
  8209. $done = true;
  8210. try {
  8211. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8212. if (empty($cols)) {
  8213. Db::execute(
  8214. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8215. );
  8216. } else {
  8217. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8218. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8219. Db::execute(
  8220. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8221. );
  8222. }
  8223. }
  8224. } catch (\Throwable $e) {
  8225. // ignore
  8226. }
  8227. }
  8228. /**
  8229. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8230. */
  8231. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8232. {
  8233. static $done = false;
  8234. if ($done) {
  8235. return;
  8236. }
  8237. $done = true;
  8238. try {
  8239. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8240. if (empty($cols)) {
  8241. Db::execute(
  8242. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8243. );
  8244. }
  8245. } catch (\Throwable $e) {
  8246. // ignore
  8247. }
  8248. try {
  8249. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8250. if (empty($cols2)) {
  8251. Db::execute(
  8252. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8253. );
  8254. }
  8255. } catch (\Throwable $e) {
  8256. // ignore
  8257. }
  8258. }
  8259. /**
  8260. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8261. */
  8262. protected function ensureConfirmResultEmailTemplates(): void
  8263. {
  8264. static $done = false;
  8265. if ($done) {
  8266. return;
  8267. }
  8268. $done = true;
  8269. $now = date('Y-m-d H:i:s');
  8270. $seeds = [
  8271. 'confirm_ok_email' => [
  8272. 'title' => '采购确认结果:已通过',
  8273. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8274. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8275. ],
  8276. 'confirm_fail_email' => [
  8277. 'title' => '采购确认结果:未通过',
  8278. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8279. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8280. ],
  8281. ];
  8282. try {
  8283. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8284. } catch (\Throwable $e) {
  8285. return;
  8286. }
  8287. $colNames = [];
  8288. foreach ($cols as $c) {
  8289. if (!is_array($c)) {
  8290. continue;
  8291. }
  8292. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8293. if ($n !== '') {
  8294. $colNames[$n] = true;
  8295. }
  8296. }
  8297. foreach ($seeds as $scene => $seed) {
  8298. try {
  8299. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8300. } catch (\Throwable $e) {
  8301. continue;
  8302. }
  8303. if (is_array($row) && $row !== []) {
  8304. continue;
  8305. }
  8306. $data = [
  8307. 'scene' => $scene,
  8308. 'title' => $seed['title'],
  8309. 'content' => $seed['content'],
  8310. 'remark' => $seed['remark'],
  8311. 'status' => 1,
  8312. ];
  8313. if (isset($colNames['updatetime'])) {
  8314. $data['updatetime'] = $now;
  8315. }
  8316. if (isset($colNames['createtime'])) {
  8317. $data['createtime'] = $now;
  8318. }
  8319. try {
  8320. Db::table('purchase_sms_template')->insert($data);
  8321. } catch (\Throwable $e) {
  8322. // ignore
  8323. }
  8324. }
  8325. }
  8326. /**
  8327. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8328. */
  8329. protected function ensureRfqSupplierEmailTemplate(): void
  8330. {
  8331. static $done = false;
  8332. if ($done) {
  8333. return;
  8334. }
  8335. $done = true;
  8336. $content = "您好,{company_name}:\n\n"
  8337. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8338. . "需求编号:{ccydh}\n"
  8339. . "印件名称:{cyjmc}\n"
  8340. . "{process_lines}\n\n"
  8341. . "请在 {deadline} 前完成回复。\n\n"
  8342. . "平台链接:{platform_url}\n";
  8343. try {
  8344. $row = Db::table('purchase_sms_template')
  8345. ->where('scene', 'rfq_supplier_email')
  8346. ->find();
  8347. } catch (\Throwable $e) {
  8348. return;
  8349. }
  8350. $now = date('Y-m-d H:i:s');
  8351. if (is_array($row) && $row !== []) {
  8352. return;
  8353. }
  8354. try {
  8355. $data = [
  8356. 'scene' => 'rfq_supplier_email',
  8357. 'title' => '供应商询价通知',
  8358. 'content' => $content,
  8359. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8360. 'status' => 1,
  8361. ];
  8362. try {
  8363. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8364. } catch (\Throwable $e) {
  8365. $cols = [];
  8366. }
  8367. $colNames = [];
  8368. foreach ($cols as $c) {
  8369. if (!is_array($c)) {
  8370. continue;
  8371. }
  8372. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8373. if ($n !== '') {
  8374. $colNames[$n] = true;
  8375. }
  8376. }
  8377. if (isset($colNames['updatetime'])) {
  8378. $data['updatetime'] = $now;
  8379. }
  8380. if (isset($colNames['createtime'])) {
  8381. $data['createtime'] = $now;
  8382. }
  8383. Db::table('purchase_sms_template')->insert($data);
  8384. } catch (\Throwable $e) {
  8385. // ignore
  8386. }
  8387. }
  8388. /**
  8389. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8390. */
  8391. protected function ensureRfqSalesmanEmailTemplate(): void
  8392. {
  8393. static $done = false;
  8394. if ($done) {
  8395. return;
  8396. }
  8397. $done = true;
  8398. $content = "您好,{contact_name}:\n\n"
  8399. . "有新的协助采购询价需求,请知悉。\n"
  8400. . "印件名称:{cyjmc}\n"
  8401. . "工序名称:{cgymc}\n"
  8402. . "本次数量:{this_quantity}\n"
  8403. . "供应商报价:\n{supplier_quotes}\n"
  8404. . "需求发起人:{cywyxm}\n";
  8405. try {
  8406. $row = Db::table('purchase_sms_template')
  8407. ->where('scene', 'rfq_salesman_email')
  8408. ->find();
  8409. } catch (\Throwable $e) {
  8410. return;
  8411. }
  8412. $now = date('Y-m-d H:i:s');
  8413. if (is_array($row) && $row !== []) {
  8414. $old = (string)($row['content'] ?? '');
  8415. // 仍用旧的「供应商:{supplier_name}」或没有报价占位符时,补上单价表格
  8416. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8417. || (strpos($old, '供应商:{supplier_name}') !== false);
  8418. if ($needMigrate) {
  8419. $data = ['content' => $content];
  8420. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8421. $data['title'] = '业务员询价通知';
  8422. }
  8423. try {
  8424. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8425. if (!empty($cols)) {
  8426. $data['updatetime'] = $now;
  8427. }
  8428. } catch (\Throwable $e) {
  8429. }
  8430. try {
  8431. Db::table('purchase_sms_template')
  8432. ->where('id', (int)($row['id'] ?? 0))
  8433. ->update($data);
  8434. } catch (\Throwable $e) {
  8435. }
  8436. }
  8437. return;
  8438. }
  8439. try {
  8440. $data = [
  8441. 'scene' => 'rfq_salesman_email',
  8442. 'title' => '业务员询价通知',
  8443. 'content' => $content,
  8444. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8445. 'status' => 1,
  8446. ];
  8447. try {
  8448. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8449. } catch (\Throwable $e) {
  8450. $cols = [];
  8451. }
  8452. $colNames = [];
  8453. foreach ($cols as $c) {
  8454. if (!is_array($c)) {
  8455. continue;
  8456. }
  8457. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8458. if ($n !== '') {
  8459. $colNames[$n] = true;
  8460. }
  8461. }
  8462. if (isset($colNames['updatetime'])) {
  8463. $data['updatetime'] = $now;
  8464. }
  8465. if (isset($colNames['createtime'])) {
  8466. $data['createtime'] = $now;
  8467. }
  8468. Db::table('purchase_sms_template')->insert($data);
  8469. } catch (\Throwable $e) {
  8470. // ignore
  8471. }
  8472. }
  8473. /**
  8474. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8475. *
  8476. * @return array<int, array{name:string,amount:string}>
  8477. */
  8478. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8479. {
  8480. $list = [];
  8481. $seen = [];
  8482. try {
  8483. $rows = Db::table('purchase_order_detail')
  8484. ->where('scydgy_id', $sid)
  8485. ->field('company_name,amount')
  8486. ->order('id', 'asc')
  8487. ->select();
  8488. if (is_array($rows)) {
  8489. foreach ($rows as $r) {
  8490. if (!is_array($r)) {
  8491. continue;
  8492. }
  8493. $cn = trim((string)($r['company_name'] ?? ''));
  8494. if ($cn === '' || isset($seen[$cn])) {
  8495. continue;
  8496. }
  8497. $seen[$cn] = true;
  8498. $amount = trim((string)($r['amount'] ?? ''));
  8499. $list[] = [
  8500. 'name' => $cn,
  8501. 'amount' => $amount !== '' ? $amount : '未报价',
  8502. ];
  8503. }
  8504. }
  8505. } catch (\Throwable $e) {
  8506. }
  8507. if ($list === [] && $supplierRaw !== '') {
  8508. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8509. if ($cn === '' || isset($seen[$cn])) {
  8510. continue;
  8511. }
  8512. $seen[$cn] = true;
  8513. $list[] = [
  8514. 'name' => $cn,
  8515. 'amount' => '未报价',
  8516. ];
  8517. }
  8518. }
  8519. return $list;
  8520. }
  8521. /**
  8522. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8523. */
  8524. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8525. {
  8526. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8527. if ($rows === []) {
  8528. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8529. }
  8530. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8531. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8532. . '<thead><tr style="background:#f5f5f5;">'
  8533. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8534. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8535. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8536. . '</tr></thead><tbody>';
  8537. foreach ($rows as $i => $row) {
  8538. $html .= '<tr>'
  8539. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8540. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8541. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8542. . '</tr>';
  8543. }
  8544. $html .= '</tbody></table>';
  8545. return $html;
  8546. }
  8547. /**
  8548. * 询价多选字段:数组或字符串统一为顿号拼接
  8549. *
  8550. * @param mixed $raw
  8551. */
  8552. protected function joinRfqMultiSelectValues($raw): string
  8553. {
  8554. $parts = [];
  8555. if (is_array($raw)) {
  8556. foreach ($raw as $item) {
  8557. if (is_array($item)) {
  8558. continue;
  8559. }
  8560. $v = trim((string)$item);
  8561. if ($v !== '') {
  8562. $parts[] = $v;
  8563. }
  8564. }
  8565. } else {
  8566. $s = trim((string)$raw);
  8567. if ($s !== '') {
  8568. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8569. $v = trim((string)$piece);
  8570. if ($v !== '') {
  8571. $parts[] = $v;
  8572. }
  8573. }
  8574. }
  8575. }
  8576. $parts = array_values(array_unique($parts));
  8577. return implode('、', $parts);
  8578. }
  8579. /**
  8580. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8581. *
  8582. * @return string[]
  8583. */
  8584. protected function loadRfqSupplierNameOptions(): array
  8585. {
  8586. $out = [];
  8587. try {
  8588. $rows = Db::table('customer')
  8589. ->where(function ($q) {
  8590. $q->where('status', 1)
  8591. ->whereOr('status', '1')
  8592. ->whereOr('status', '')
  8593. ->whereNull('status');
  8594. })
  8595. ->order('id', 'desc')
  8596. ->column('company_name');
  8597. } catch (\Throwable $e) {
  8598. return [];
  8599. }
  8600. if (!is_array($rows)) {
  8601. return [];
  8602. }
  8603. foreach ($rows as $name) {
  8604. $name = trim((string)$name);
  8605. if ($name === '' || isset($out[$name])) {
  8606. continue;
  8607. }
  8608. $out[$name] = $name;
  8609. }
  8610. return array_values($out);
  8611. }
  8612. /**
  8613. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8614. */
  8615. protected function rfqNotifySalesmanAuthGroupId(): int
  8616. {
  8617. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8618. if ($id > 0) {
  8619. return $id;
  8620. }
  8621. try {
  8622. $found = Db::name('auth_group')
  8623. ->where('name', '业务员')
  8624. ->where('status', 'normal')
  8625. ->order('id', 'asc')
  8626. ->value('id');
  8627. $id = (int)$found;
  8628. } catch (\Throwable $e) {
  8629. $id = 0;
  8630. }
  8631. return $id > 0 ? $id : 12;
  8632. }
  8633. /**
  8634. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8635. *
  8636. * @return string[]
  8637. */
  8638. protected function loadRfqSalesmanNameOptions(): array
  8639. {
  8640. $out = [];
  8641. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8642. $name = trim((string)($row['name'] ?? ''));
  8643. if ($name !== '') {
  8644. $out[] = $name;
  8645. }
  8646. }
  8647. return $out;
  8648. }
  8649. /**
  8650. * 业务员角色组下管理员:姓名、邮箱、手机
  8651. *
  8652. * @return array<int, array{name:string,email:string,mobile:string}>
  8653. */
  8654. protected function loadRfqSalesmanContactOptions(): array
  8655. {
  8656. $out = [];
  8657. $seen = [];
  8658. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8659. if ($groupId <= 0) {
  8660. return [];
  8661. }
  8662. try {
  8663. $adminIds = Db::name('auth_group_access')
  8664. ->where('group_id', $groupId)
  8665. ->column('uid');
  8666. } catch (\Throwable $e) {
  8667. return [];
  8668. }
  8669. $adminIds = is_array($adminIds)
  8670. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8671. : [];
  8672. if ($adminIds === []) {
  8673. return [];
  8674. }
  8675. try {
  8676. $rows = Db::name('admin')
  8677. ->where('status', 'normal')
  8678. ->where('id', 'in', $adminIds)
  8679. ->order('id', 'asc')
  8680. ->field('id,nickname,username,email,mobile')
  8681. ->select();
  8682. } catch (\Throwable $e) {
  8683. return [];
  8684. }
  8685. if (!is_array($rows)) {
  8686. return [];
  8687. }
  8688. foreach ($rows as $row) {
  8689. if (!is_array($row)) {
  8690. continue;
  8691. }
  8692. $name = trim((string)($row['nickname'] ?? ''));
  8693. if ($name === '') {
  8694. $name = trim((string)($row['username'] ?? ''));
  8695. }
  8696. if ($name === '' || isset($seen[$name])) {
  8697. continue;
  8698. }
  8699. $seen[$name] = true;
  8700. $out[] = [
  8701. 'name' => $name,
  8702. 'email' => trim((string)($row['email'] ?? '')),
  8703. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8704. ];
  8705. }
  8706. return $out;
  8707. }
  8708. /**
  8709. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8710. *
  8711. * @return string[]
  8712. */
  8713. protected function loadRfqDeptNameOptions(): array
  8714. {
  8715. $out = [];
  8716. // ERP 承揽部门(主来源)
  8717. try {
  8718. $vals = Db::table('mcyd')
  8719. ->where('CCLBMMC', '<>', '')
  8720. ->whereNotNull('CCLBMMC')
  8721. ->distinct(true)
  8722. ->limit(300)
  8723. ->column('CCLBMMC');
  8724. } catch (\Throwable $e) {
  8725. $vals = [];
  8726. }
  8727. if (is_array($vals)) {
  8728. foreach ($vals as $v) {
  8729. $v = trim((string)$v);
  8730. if ($v === '' || isset($out[$v])) {
  8731. continue;
  8732. }
  8733. $out[$v] = $v;
  8734. }
  8735. }
  8736. // 手工询价历史部门补全
  8737. try {
  8738. $poVals = Db::table('purchase_order')
  8739. ->where('CCLBMMC', '<>', '')
  8740. ->whereNotNull('CCLBMMC')
  8741. ->distinct(true)
  8742. ->limit(200)
  8743. ->column('CCLBMMC');
  8744. } catch (\Throwable $e) {
  8745. $poVals = [];
  8746. }
  8747. if (is_array($poVals)) {
  8748. foreach ($poVals as $v) {
  8749. $v = trim((string)$v);
  8750. if ($v === '' || isset($out[$v])) {
  8751. continue;
  8752. }
  8753. $out[$v] = $v;
  8754. }
  8755. }
  8756. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8757. if (!isset($out[$preset])) {
  8758. $out[$preset] = $preset;
  8759. }
  8760. }
  8761. $list = array_values($out);
  8762. // 常用部门靠前
  8763. usort($list, static function ($a, $b) {
  8764. $weight = [
  8765. '营销中心' => 1,
  8766. '业务部' => 2,
  8767. '市场部' => 3,
  8768. '外贸部' => 4,
  8769. '新华技术业务部' => 5,
  8770. ];
  8771. $wa = $weight[$a] ?? 100;
  8772. $wb = $weight[$b] ?? 100;
  8773. if ($wa !== $wb) {
  8774. return $wa <=> $wb;
  8775. }
  8776. return strcmp((string)$a, (string)$b);
  8777. });
  8778. return $list;
  8779. }
  8780. /**
  8781. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8782. */
  8783. public function add()
  8784. {
  8785. if ($this->request->isPost()) {
  8786. $params = $this->request->post('row/a');
  8787. if (!is_array($params)) {
  8788. $this->error(__('Parameter %s can not be empty', ''));
  8789. }
  8790. [, $adminName] = $this->GetUseName();
  8791. $params['cywyxm'] = $adminName;
  8792. try {
  8793. $sid = $this->saveManualPickOrder($params);
  8794. } catch (\InvalidArgumentException $e) {
  8795. $this->error($e->getMessage());
  8796. } catch (\Throwable $e) {
  8797. $this->error($e->getMessage());
  8798. }
  8799. $this->success('新增成功', '', [
  8800. 'scydgy_id' => $sid,
  8801. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8802. ]);
  8803. }
  8804. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8805. [, $adminName] = $this->GetUseName();
  8806. $this->view->assign('adminNickname', $adminName);
  8807. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8808. $this->view->assign('defaultCclbmmc', '营销中心');
  8809. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8810. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8811. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8812. return $this->view->fetch();
  8813. }
  8814. /**
  8815. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8816. */
  8817. public function rfqlist()
  8818. {
  8819. $this->relationSearch = false;
  8820. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8821. $this->request->filter(['strip_tags', 'trim']);
  8822. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8823. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8824. $this->ensureRfqSalesmanEmailTemplate();
  8825. $this->ensureRfqSupplierEmailTemplate();
  8826. if ($this->request->isAjax()) {
  8827. try {
  8828. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8829. $limit = max(10, min(500, (int)$limit));
  8830. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8831. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8832. $filterYm = date('Y-m');
  8833. }
  8834. $applyFilters = function ($query) use ($where, $filterYm) {
  8835. $query->where('scydgy_id', '<', 0);
  8836. $this->applyPurchaseOrderNotDeletedWhere($query);
  8837. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8838. $this->applyRfqListMonthFilter($query, $filterYm);
  8839. if (!empty($where)) {
  8840. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8841. $safeWhere = [];
  8842. $skipFields = [
  8843. 'supplier_name' => true,
  8844. 'progress_text' => true,
  8845. 'createtime_text' => true,
  8846. 'notify_time_text' => true,
  8847. 'can_notify_salesman' => true,
  8848. 'has_issued' => true,
  8849. 'has_quoted' => true,
  8850. ];
  8851. foreach ((array)$where as $cond) {
  8852. if (!is_array($cond) || !isset($cond[0])) {
  8853. continue;
  8854. }
  8855. $field = (string)$cond[0];
  8856. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8857. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8858. if (isset($skipFields[$fieldBase])) {
  8859. continue;
  8860. }
  8861. if ($fieldBase === 'supplier_name') {
  8862. continue;
  8863. }
  8864. $safeWhere[] = $cond;
  8865. }
  8866. if ($safeWhere !== []) {
  8867. $query->where($safeWhere);
  8868. }
  8869. }
  8870. };
  8871. $countQuery = Db::table('purchase_order');
  8872. $applyFilters($countQuery);
  8873. $total = (int)$countQuery->count();
  8874. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8875. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8876. $listQuery = Db::table('purchase_order');
  8877. $applyFilters($listQuery);
  8878. $rows = $listQuery
  8879. ->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')
  8880. ->order($sortField, $orderDir)
  8881. ->limit($offset, $limit)
  8882. ->select();
  8883. if (!is_array($rows)) {
  8884. $rows = [];
  8885. }
  8886. $sidList = [];
  8887. foreach ($rows as $r) {
  8888. if (!is_array($r)) {
  8889. continue;
  8890. }
  8891. $sid = (int)($r['scydgy_id'] ?? 0);
  8892. if ($sid < 0) {
  8893. $sidList[$sid] = true;
  8894. }
  8895. }
  8896. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8897. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8898. $out = [];
  8899. foreach ($rows as $r) {
  8900. if (!is_array($r)) {
  8901. continue;
  8902. }
  8903. $sid = (int)($r['scydgy_id'] ?? 0);
  8904. if ($sid >= 0) {
  8905. continue;
  8906. }
  8907. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8908. if ($createdText === '') {
  8909. $createdText = trim((string)($r['dStamp'] ?? ''));
  8910. }
  8911. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8912. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8913. if ($supplier === '') {
  8914. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8915. }
  8916. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8917. || isset($issuedSidSet[$sid]);
  8918. $hasQuoted = isset($quotedSidSet[$sid]);
  8919. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8920. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8921. $out[] = [
  8922. 'id' => (int)($r['id'] ?? 0),
  8923. 'scydgy_id' => $sid,
  8924. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8925. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8926. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8927. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8928. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8929. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8930. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8931. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8932. 'supplier_name' => $supplier,
  8933. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8934. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8935. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8936. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8937. 'notify_time_text' => $notifyTimeText,
  8938. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8939. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8940. 'has_issued' => $hasIssued ? 1 : 0,
  8941. 'has_quoted' => $hasQuoted ? 1 : 0,
  8942. 'can_notify_salesman' => $canNotifySalesman,
  8943. 'createtime' => $r['createtime'] ?? null,
  8944. 'createtime_text' => $createdText,
  8945. ];
  8946. }
  8947. return json(['total' => $total, 'rows' => $out]);
  8948. } catch (\Throwable $e) {
  8949. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8950. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8951. }
  8952. }
  8953. $sidebar = $this->loadRfqSidebarYearMonths();
  8954. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8955. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8956. [, $adminName] = $this->GetUseName();
  8957. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8958. $this->view->assign('adminNickname', $adminName);
  8959. $this->view->assign('defaultYm', $defaultYm);
  8960. $this->view->assign('sidebarYearMonths', $sidebar);
  8961. return $this->view->fetch('procuremen/rfqlist');
  8962. }
  8963. /**
  8964. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8965. *
  8966. * @param array<int, array{year:string, months:array}> $sidebar
  8967. */
  8968. protected function resolveRfqListDefaultYm(array $sidebar): string
  8969. {
  8970. $current = date('Y-m');
  8971. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8972. if (in_array($current, $yms, true)) {
  8973. return $current;
  8974. }
  8975. if ($yms !== []) {
  8976. rsort($yms, SORT_STRING);
  8977. return (string)$yms[0];
  8978. }
  8979. return $current;
  8980. }
  8981. /**
  8982. * 手工询价列表左侧月份(按 createtime / dStamp)
  8983. *
  8984. * @return array<int, array{year:string, months:array}>
  8985. */
  8986. protected function loadRfqSidebarYearMonths(): array
  8987. {
  8988. $ymSet = [];
  8989. try {
  8990. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8991. $this->applyPurchaseOrderNotDeletedWhere($q);
  8992. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8993. } catch (\Throwable $e) {
  8994. $rows = [];
  8995. }
  8996. if (!is_array($rows)) {
  8997. $rows = [];
  8998. }
  8999. foreach ($rows as $r) {
  9000. if (!is_array($r)) {
  9001. continue;
  9002. }
  9003. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9004. if ($t === '') {
  9005. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9006. }
  9007. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9008. $ymSet[$m[1] . '-' . $m[2]] = true;
  9009. }
  9010. }
  9011. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9012. }
  9013. /**
  9014. * 手工询价可见范围(用于详情/操作校验):
  9015. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9016. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9017. */
  9018. protected function applyManualRfqViewerWhere($query): void
  9019. {
  9020. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9021. return;
  9022. }
  9023. [, $adminName] = $this->GetUseName();
  9024. $adminName = trim((string)$adminName);
  9025. if ($adminName === '') {
  9026. $query->whereRaw('1 = 0');
  9027. return;
  9028. }
  9029. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9030. $query->where(function ($q) use ($adminName) {
  9031. $q->where('cywyxm', $adminName)
  9032. ->whereOr('notify_salesman', $adminName)
  9033. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9034. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9035. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9036. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9037. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9038. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9039. });
  9040. }
  9041. /**
  9042. * 当前用户是否可查看/操作该手工询价单
  9043. */
  9044. protected function canViewManualRfqOrder(array $po): bool
  9045. {
  9046. if ($this->auth->isSuperAdmin()) {
  9047. return true;
  9048. }
  9049. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9050. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9051. return true;
  9052. }
  9053. [, $adminName] = $this->GetUseName();
  9054. $adminName = trim((string)$adminName);
  9055. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9056. return true;
  9057. }
  9058. if ($adminName !== '') {
  9059. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9060. if ($n === $adminName) {
  9061. return true;
  9062. }
  9063. }
  9064. }
  9065. return false;
  9066. }
  9067. /**
  9068. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9069. */
  9070. protected function applyRfqListMonthFilter($query, string $ym): void
  9071. {
  9072. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9073. $ym = date('Y-m');
  9074. }
  9075. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9076. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9077. $query->whereRaw(
  9078. "("
  9079. . "CASE "
  9080. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9081. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9082. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9083. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9084. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9085. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9086. . "END"
  9087. . ") LIKE '{$ymEsc}-%'"
  9088. );
  9089. }
  9090. /**
  9091. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9092. */
  9093. public function rfqlistDetails()
  9094. {
  9095. return $this->details();
  9096. }
  9097. /**
  9098. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9099. */
  9100. public function rfqnotifysalesmen()
  9101. {
  9102. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9103. $this->error(__('You have no permission'));
  9104. }
  9105. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9106. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9107. $sid = (int)$this->request->param('scydgy_id', 0);
  9108. if ($sid >= 0) {
  9109. $this->error('仅支持手工新增询价单');
  9110. }
  9111. $po = $this->loadManualRfqOrderForNotify($sid);
  9112. $selectedMap = [];
  9113. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9114. $selectedMap[$n] = true;
  9115. }
  9116. $list = [];
  9117. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9118. $name = trim((string)($row['name'] ?? ''));
  9119. if ($name === '') {
  9120. continue;
  9121. }
  9122. $email = trim((string)($row['email'] ?? ''));
  9123. $mobile = trim((string)($row['mobile'] ?? ''));
  9124. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9125. $list[] = [
  9126. 'name' => $name,
  9127. 'email' => $email,
  9128. 'mobile' => $mobile,
  9129. 'can_select' => $hasEmail ? 1 : 0,
  9130. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9131. ];
  9132. }
  9133. $canNotify = $this->canRfqNotifySalesman($po);
  9134. $this->success('', null, [
  9135. 'scydgy_id' => $sid,
  9136. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9137. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9138. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9139. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9140. 'list' => $list,
  9141. ]);
  9142. }
  9143. /**
  9144. * 查询询价 — 补加通知业务员可选名单
  9145. */
  9146. public function rfqsalesmanoptions()
  9147. {
  9148. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9149. $this->error(__('You have no permission'));
  9150. }
  9151. $out = [];
  9152. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9153. $email = trim((string)($row['email'] ?? ''));
  9154. $mobile = trim((string)($row['mobile'] ?? ''));
  9155. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9156. $out[] = [
  9157. 'name' => (string)($row['name'] ?? ''),
  9158. 'email' => $email,
  9159. 'mobile' => $mobile,
  9160. 'can_select' => $hasEmail ? 1 : 0,
  9161. ];
  9162. }
  9163. $this->success('', null, ['list' => $out]);
  9164. }
  9165. /**
  9166. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9167. */
  9168. public function rfqappendsalesmen()
  9169. {
  9170. if (!$this->request->isPost()) {
  9171. $this->error(__('Invalid parameters'));
  9172. }
  9173. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9174. $this->error(__('You have no permission'));
  9175. }
  9176. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9177. $sid = (int)$this->request->post('scydgy_id', 0);
  9178. if ($sid >= 0) {
  9179. $this->error('仅支持手工新增询价单');
  9180. }
  9181. $po = $this->loadManualRfqOrderForNotify($sid);
  9182. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9183. $this->error('订单已完结,无法添加业务员');
  9184. }
  9185. $raw = $this->request->post('salesmen/a', []);
  9186. if (!is_array($raw) || $raw === []) {
  9187. $salesmenJson = $this->request->post('salesmen_json', '');
  9188. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9189. $decoded = json_decode($salesmenJson, true);
  9190. $raw = is_array($decoded) ? $decoded : [];
  9191. }
  9192. }
  9193. $addNames = [];
  9194. foreach ((array)$raw as $item) {
  9195. if (is_array($item)) {
  9196. $n = trim((string)($item['name'] ?? ''));
  9197. } else {
  9198. $n = trim((string)$item);
  9199. }
  9200. if ($n !== '') {
  9201. $addNames[] = $n;
  9202. }
  9203. }
  9204. $addNames = array_values(array_unique($addNames));
  9205. if ($addNames === []) {
  9206. $this->error('请选择要添加的业务员');
  9207. }
  9208. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9209. $allowedMap = [];
  9210. foreach ($allowedOptions as $opt) {
  9211. $n = trim((string)($opt['name'] ?? ''));
  9212. if ($n === '') {
  9213. continue;
  9214. }
  9215. $email = trim((string)($opt['email'] ?? ''));
  9216. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9217. }
  9218. foreach ($addNames as $n) {
  9219. if (!array_key_exists($n, $allowedMap)) {
  9220. $this->error('业务员不在可选名单中:' . $n);
  9221. }
  9222. if (!$allowedMap[$n]) {
  9223. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9224. }
  9225. }
  9226. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9227. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9228. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9229. try {
  9230. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9231. } catch (\Throwable $e) {
  9232. $this->error('保存失败:' . $e->getMessage());
  9233. }
  9234. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9235. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9236. $this->success('已添加业务员', null, [
  9237. 'scydgy_id' => $sid,
  9238. 'notify_salesman' => $mergedStr,
  9239. 'added_count' => count($addNames),
  9240. ]);
  9241. }
  9242. /**
  9243. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9244. */
  9245. public function rfqnotifysalesman()
  9246. {
  9247. if (!$this->request->isPost()) {
  9248. $this->error(__('Invalid parameters'));
  9249. }
  9250. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9251. $this->error(__('You have no permission'));
  9252. }
  9253. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9254. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9255. $sid = (int)$this->request->post('scydgy_id', 0);
  9256. if ($sid >= 0) {
  9257. $this->error('仅支持手工新增询价单');
  9258. }
  9259. $po = $this->loadManualRfqOrderForNotify($sid);
  9260. $this->assertRfqCanNotifySalesman($po);
  9261. $raw = $this->request->post('salesmen/a', []);
  9262. if (!is_array($raw) || $raw === []) {
  9263. $salesmenJson = $this->request->post('salesmen_json', '');
  9264. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9265. $decoded = json_decode($salesmenJson, true);
  9266. $raw = is_array($decoded) ? $decoded : [];
  9267. }
  9268. }
  9269. // 兼容旧参数:notify_all / 单人 name
  9270. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9271. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9272. }
  9273. if ((!is_array($raw) || $raw === [])) {
  9274. $oneName = trim((string)$this->request->post('name', ''));
  9275. if ($oneName !== '') {
  9276. $raw = [$oneName];
  9277. }
  9278. }
  9279. $selectedNames = [];
  9280. foreach ((array)$raw as $item) {
  9281. if (is_array($item)) {
  9282. $n = trim((string)($item['name'] ?? ''));
  9283. } else {
  9284. $n = trim((string)$item);
  9285. }
  9286. if ($n !== '') {
  9287. $selectedNames[] = $n;
  9288. }
  9289. }
  9290. $selectedNames = array_values(array_unique($selectedNames));
  9291. if ($selectedNames === []) {
  9292. $this->error('请选择要通知的业务员');
  9293. }
  9294. $optionMap = [];
  9295. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9296. $n = trim((string)($opt['name'] ?? ''));
  9297. if ($n === '') {
  9298. continue;
  9299. }
  9300. $optionMap[$n] = $opt;
  9301. }
  9302. $targets = [];
  9303. foreach ($selectedNames as $n) {
  9304. if (!isset($optionMap[$n])) {
  9305. $this->error('业务员不在可选名单中:' . $n);
  9306. }
  9307. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9308. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9309. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9310. }
  9311. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9312. $targets[] = $resolved[0] ?? [
  9313. 'admin_id' => 0,
  9314. 'name' => $n,
  9315. 'email' => $email,
  9316. ];
  9317. }
  9318. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9319. try {
  9320. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9321. 'notify_salesman' => $mergedStr,
  9322. ]);
  9323. } catch (\Throwable $e) {
  9324. $this->error('保存通知业务员失败:' . $e->getMessage());
  9325. }
  9326. $po['notify_salesman'] = $mergedStr;
  9327. $mailConfig = $this->loadMailerConfig();
  9328. if (empty($mailConfig['host'])) {
  9329. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9330. }
  9331. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9332. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9333. }
  9334. $this->ensureRfqSalesmanEmailTemplate();
  9335. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9336. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9337. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9338. $cdw = trim((string)($po['CDW'] ?? ''));
  9339. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9340. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9341. $mbz = trim((string)($po['MBZ'] ?? ''));
  9342. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9343. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9344. if ($supplier === '') {
  9345. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9346. }
  9347. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9348. try {
  9349. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9350. } catch (\Throwable $e) {
  9351. $this->error($e->getMessage());
  9352. }
  9353. $okNames = [];
  9354. $failMsgs = [];
  9355. foreach ($targets as $contact) {
  9356. $toEmail = trim((string)($contact['email'] ?? ''));
  9357. $toName = trim((string)($contact['name'] ?? ''));
  9358. $notifyVars = [
  9359. 'contact_name' => $toName,
  9360. 'salesman_name' => $toName,
  9361. 'company_name' => $toName,
  9362. 'email' => $toEmail,
  9363. 'ccydh' => $ccydh,
  9364. 'cyjmc' => $cyjmc,
  9365. 'cgymc' => $cgymc,
  9366. 'cdw' => $cdw,
  9367. 'this_quantity' => $qty,
  9368. 'ceilingPrice' => $ceiling,
  9369. 'MBZ' => $mbz,
  9370. 'supplier_name' => $supplier,
  9371. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9372. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9373. 'cywyxm' => $cywyxm,
  9374. ];
  9375. try {
  9376. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9377. $mailSubject = $mailSubjectTpl;
  9378. foreach ($notifyVars as $k => $v) {
  9379. if ($k === 'supplier_quotes') {
  9380. continue;
  9381. }
  9382. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9383. }
  9384. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9385. $mailSubject = trim((string)$mailSubject);
  9386. if ($mailSubject === '') {
  9387. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9388. }
  9389. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9390. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9391. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9392. $bundle = [
  9393. 'company_name' => $toName,
  9394. 'email' => $toEmail,
  9395. 'mail_plain' => $mailPlainForLog,
  9396. 'mail_body' => $mailBody,
  9397. 'ccydh' => $ccydh,
  9398. 'email_log_scene' => 'rfq_salesman',
  9399. 'email_log_scydgy_id' => $sid,
  9400. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9401. 'notify_vars' => $notifyVars,
  9402. ];
  9403. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9404. $okNames[] = $toName . '(' . $toEmail . ')';
  9405. } catch (\Throwable $e) {
  9406. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9407. }
  9408. }
  9409. if ($okNames === []) {
  9410. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9411. }
  9412. $now = date('Y-m-d H:i:s');
  9413. try {
  9414. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9415. 'rfq_salesman_notified' => 1,
  9416. 'rfq_salesman_notify_time' => $now,
  9417. ]);
  9418. } catch (\Throwable $e) {
  9419. // ignore
  9420. }
  9421. $this->addOrderLog(
  9422. $sid,
  9423. 'rfq_notify_salesman',
  9424. '邮箱通知业务员:' . implode('、', $okNames),
  9425. (int)($po['id'] ?? 0)
  9426. );
  9427. $msg = '已通知 ' . count($okNames) . ' 人';
  9428. if ($failMsgs !== []) {
  9429. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9430. }
  9431. $this->success($msg, null, [
  9432. 'scydgy_id' => $sid,
  9433. 'notify_salesman' => $mergedStr,
  9434. 'rfq_salesman_notified' => 1,
  9435. 'rfq_salesman_notify_time' => $now,
  9436. 'notify_time_text' => $now,
  9437. 'ok_count' => count($okNames),
  9438. 'fail_count' => count($failMsgs),
  9439. ]);
  9440. }
  9441. /**
  9442. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9443. */
  9444. public function rfqissuesuppliers()
  9445. {
  9446. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9447. $this->error(__('You have no permission'));
  9448. }
  9449. $sid = (int)$this->request->param('scydgy_id', 0);
  9450. if ($sid >= 0) {
  9451. $this->error('仅支持手工新增询价单');
  9452. }
  9453. $po = $this->loadManualRfqOrderForNotify($sid);
  9454. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9455. if ($supplierRaw === '') {
  9456. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9457. }
  9458. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9459. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9460. $notifiedMap = [];
  9461. try {
  9462. $this->ensurePurchaseEmailSendLogTableOnce();
  9463. $logRows = Db::table('purchase_email_send_log')
  9464. ->where('scydgy_id', $sid)
  9465. ->where('status', 1)
  9466. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9467. ->field('company_name')
  9468. ->select();
  9469. if (is_array($logRows)) {
  9470. foreach ($logRows as $lr) {
  9471. if (!is_array($lr)) {
  9472. continue;
  9473. }
  9474. $cn = trim((string)($lr['company_name'] ?? ''));
  9475. if ($cn !== '') {
  9476. $notifiedMap[$cn] = true;
  9477. }
  9478. }
  9479. }
  9480. } catch (\Throwable $e) {
  9481. }
  9482. // 兼容:明细已生成(曾下发)也视为已通知
  9483. try {
  9484. $detRows = Db::table('purchase_order_detail')
  9485. ->where('scydgy_id', $sid)
  9486. ->field('company_name')
  9487. ->select();
  9488. if (is_array($detRows)) {
  9489. foreach ($detRows as $dr) {
  9490. if (!is_array($dr)) {
  9491. continue;
  9492. }
  9493. $cn = trim((string)($dr['company_name'] ?? ''));
  9494. if ($cn !== '') {
  9495. $notifiedMap[$cn] = true;
  9496. }
  9497. }
  9498. }
  9499. } catch (\Throwable $e) {
  9500. }
  9501. $list = [];
  9502. foreach ($names as $name) {
  9503. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9504. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9505. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9506. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9507. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9508. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9509. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9510. $list[] = [
  9511. 'name' => $name,
  9512. 'username' => $username,
  9513. 'email' => $email,
  9514. 'phone' => $phone,
  9515. 'can_notify' => $okEmail ? 1 : 0,
  9516. 'found' => is_array($contact) ? 1 : 0,
  9517. 'notified' => $notified,
  9518. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9519. ];
  9520. }
  9521. $this->success('', null, [
  9522. 'scydgy_id' => $sid,
  9523. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9524. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9525. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9526. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9527. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9528. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9529. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9530. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9531. 'list' => $list,
  9532. ]);
  9533. }
  9534. /**
  9535. * 查询询价 — 补加供应商可选名单
  9536. */
  9537. public function rfqsupplieroptions()
  9538. {
  9539. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9540. $this->error(__('You have no permission'));
  9541. }
  9542. $names = array_values($this->loadRfqSupplierNameOptions());
  9543. $out = [];
  9544. foreach ($names as $name) {
  9545. $out[] = ['name' => $name];
  9546. }
  9547. $this->success('', null, ['list' => $out]);
  9548. }
  9549. /**
  9550. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9551. */
  9552. public function rfqappendsuppliers()
  9553. {
  9554. if (!$this->request->isPost()) {
  9555. $this->error(__('Invalid parameters'));
  9556. }
  9557. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9558. $this->error(__('You have no permission'));
  9559. }
  9560. $sid = (int)$this->request->post('scydgy_id', 0);
  9561. if ($sid >= 0) {
  9562. $this->error('仅支持手工新增询价单');
  9563. }
  9564. $po = $this->loadManualRfqOrderForNotify($sid);
  9565. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9566. $this->error('订单已完结,无法补加供应商');
  9567. }
  9568. $raw = $this->request->post('suppliers/a', []);
  9569. if (!is_array($raw) || $raw === []) {
  9570. $suppliersJson = $this->request->post('suppliers_json', '');
  9571. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9572. $decoded = json_decode($suppliersJson, true);
  9573. $raw = is_array($decoded) ? $decoded : [];
  9574. }
  9575. }
  9576. $addNames = [];
  9577. foreach ((array)$raw as $item) {
  9578. if (is_array($item)) {
  9579. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9580. } else {
  9581. $n = trim((string)$item);
  9582. }
  9583. if ($n !== '') {
  9584. $addNames[] = $n;
  9585. }
  9586. }
  9587. $addNames = array_values(array_unique($addNames));
  9588. if ($addNames === []) {
  9589. $this->error('请选择要补加的供应商');
  9590. }
  9591. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9592. if ($existingRaw === '') {
  9593. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9594. }
  9595. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9596. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9597. try {
  9598. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9599. } catch (\Throwable $e) {
  9600. $this->error('保存失败:' . $e->getMessage());
  9601. }
  9602. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9603. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9604. $this->success('已补加供应商', null, [
  9605. 'scydgy_id' => $sid,
  9606. 'cGzzxMc' => $mergedStr,
  9607. 'added_count' => count($addNames),
  9608. ]);
  9609. }
  9610. /**
  9611. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9612. */
  9613. public function rfqissue()
  9614. {
  9615. if (!$this->request->isPost()) {
  9616. $this->error(__('Invalid parameters'));
  9617. }
  9618. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9619. $this->error(__('You have no permission'));
  9620. }
  9621. $this->ensureRfqSupplierEmailTemplate();
  9622. $sid = (int)$this->request->post('scydgy_id', 0);
  9623. if ($sid >= 0) {
  9624. $this->error('仅支持手工新增询价单');
  9625. }
  9626. $po = $this->loadManualRfqOrderForNotify($sid);
  9627. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9628. $this->error('订单已完结,无法下发');
  9629. }
  9630. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9631. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9632. $this->error('订单已进入后续流程,无法再下发');
  9633. }
  9634. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9635. if ($supplierRaw === '') {
  9636. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9637. }
  9638. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9639. if ($supplierNames === []) {
  9640. $this->error('请先在新增询价时选择供应商');
  9641. }
  9642. $companies = [];
  9643. $missing = [];
  9644. $noEmail = [];
  9645. foreach ($supplierNames as $name) {
  9646. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9647. if ($contact === null) {
  9648. $missing[] = $name;
  9649. continue;
  9650. }
  9651. $em = trim((string)($contact['email'] ?? ''));
  9652. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9653. $noEmail[] = $name;
  9654. continue;
  9655. }
  9656. $companies[] = $contact;
  9657. }
  9658. if ($missing !== []) {
  9659. $this->error('未找到供应商档案:' . implode('、', $missing));
  9660. }
  9661. if ($noEmail !== []) {
  9662. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9663. }
  9664. if ($companies === []) {
  9665. $this->error('没有可通知的供应商');
  9666. }
  9667. $mailConfig = $this->loadMailerConfig();
  9668. if (empty($mailConfig['host'])) {
  9669. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9670. }
  9671. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9672. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9673. }
  9674. $mergeRow = $po;
  9675. $mergeRow['ID'] = $sid;
  9676. $mergeRow['id'] = $sid;
  9677. $mergeRows = [$mergeRow];
  9678. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9679. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9680. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9681. }
  9682. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9683. $issueTime = date('Y-m-d H:i:s');
  9684. $nameLabels = [];
  9685. foreach ($companies as $c) {
  9686. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9687. }
  9688. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9689. Db::startTrans();
  9690. try {
  9691. $this->upsertPurchaseOrderFromRow(
  9692. $mergeRow,
  9693. $sysRqDb,
  9694. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9695. $issueTime,
  9696. $po,
  9697. null,
  9698. $scoreRule
  9699. );
  9700. foreach ($companies as $c) {
  9701. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9702. }
  9703. Db::commit();
  9704. } catch (\Throwable $e) {
  9705. Db::rollback();
  9706. $this->error($e->getMessage());
  9707. }
  9708. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9709. if ($poId <= 0) {
  9710. try {
  9711. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9712. } catch (\Throwable $e) {
  9713. $poId = 0;
  9714. }
  9715. }
  9716. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9717. $posNotify = [];
  9718. try {
  9719. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9720. if (is_array($fresh)) {
  9721. $fresh['sys_rq'] = $sysRqDb;
  9722. $posNotify = [$fresh];
  9723. }
  9724. } catch (\Throwable $e) {
  9725. $posNotify = [$po];
  9726. $posNotify[0]['sys_rq'] = $sysRqDb;
  9727. }
  9728. $notifyBundle = [
  9729. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9730. 'pos' => $posNotify,
  9731. 'merge_rows' => $mergeRows,
  9732. ];
  9733. $notifyErrors = [];
  9734. foreach ($companies as $c) {
  9735. $cname = trim((string)($c['name'] ?? ''));
  9736. try {
  9737. // 询价下发:仅邮箱通知供应商
  9738. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9739. } catch (\Throwable $e) {
  9740. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9741. }
  9742. }
  9743. if ($notifyErrors !== []) {
  9744. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9745. }
  9746. $this->success('已询价并邮件通知供应商', null, [
  9747. 'scydgy_id' => $sid,
  9748. 'progress_text' => '待报价',
  9749. 'supplier_count' => count($companies),
  9750. ]);
  9751. }
  9752. /**
  9753. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9754. */
  9755. public function rfqissuesendmail()
  9756. {
  9757. if (!$this->request->isPost()) {
  9758. $this->error(__('Invalid parameters'));
  9759. }
  9760. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9761. $this->error(__('You have no permission'));
  9762. }
  9763. $this->ensureRfqSupplierEmailTemplate();
  9764. $sid = (int)$this->request->post('scydgy_id', 0);
  9765. $companyName = trim((string)$this->request->post('company_name', ''));
  9766. if ($sid >= 0) {
  9767. $this->error('仅支持手工新增询价单');
  9768. }
  9769. if ($companyName === '') {
  9770. $this->error('请选择供应商');
  9771. }
  9772. $po = $this->loadManualRfqOrderForNotify($sid);
  9773. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9774. $this->error('订单已完结,无法发送');
  9775. }
  9776. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9777. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9778. $this->error('订单已进入后续流程,无法再发送');
  9779. }
  9780. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9781. if ($contact === null) {
  9782. $this->error('未找到供应商档案:' . $companyName);
  9783. }
  9784. $email = trim((string)($contact['email'] ?? ''));
  9785. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9786. $this->error('该供应商未填写有效邮箱');
  9787. }
  9788. $mailConfig = $this->loadMailerConfig();
  9789. if (empty($mailConfig['host'])) {
  9790. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9791. }
  9792. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9793. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9794. }
  9795. $mergeRow = $po;
  9796. $mergeRow['ID'] = $sid;
  9797. $mergeRow['id'] = $sid;
  9798. $mergeRows = [$mergeRow];
  9799. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9800. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9801. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9802. }
  9803. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9804. $issueTime = date('Y-m-d H:i:s');
  9805. Db::startTrans();
  9806. try {
  9807. $this->upsertPurchaseOrderFromRow(
  9808. $mergeRow,
  9809. $sysRqDb,
  9810. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9811. $issueTime,
  9812. $po,
  9813. null,
  9814. $scoreRule
  9815. );
  9816. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9817. Db::commit();
  9818. } catch (\Throwable $e) {
  9819. Db::rollback();
  9820. $this->error($e->getMessage());
  9821. }
  9822. $posNotify = [];
  9823. try {
  9824. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9825. if (is_array($fresh)) {
  9826. $fresh['sys_rq'] = $sysRqDb;
  9827. $posNotify = [$fresh];
  9828. }
  9829. } catch (\Throwable $e) {
  9830. $posNotify = [$po];
  9831. $posNotify[0]['sys_rq'] = $sysRqDb;
  9832. }
  9833. $notifyBundle = [
  9834. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9835. 'pos' => $posNotify,
  9836. 'merge_rows' => $mergeRows,
  9837. ];
  9838. try {
  9839. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9840. } catch (\Throwable $e) {
  9841. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9842. }
  9843. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9844. if ($poId <= 0) {
  9845. try {
  9846. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9847. } catch (\Throwable $e) {
  9848. $poId = 0;
  9849. }
  9850. }
  9851. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9852. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9853. 'scydgy_id' => $sid,
  9854. 'company_name' => $companyName,
  9855. ]);
  9856. }
  9857. /**
  9858. * 查询询价 — 查看各供应商报价(单价)
  9859. */
  9860. public function rfqquotes()
  9861. {
  9862. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  9863. $this->error(__('You have no permission'));
  9864. }
  9865. $sid = (int)$this->request->param('scydgy_id', 0);
  9866. if ($sid >= 0) {
  9867. $this->error('仅支持手工新增询价单');
  9868. }
  9869. $po = $this->loadManualRfqOrderForNotify($sid);
  9870. $rows = [];
  9871. try {
  9872. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9873. $q = Db::table('purchase_order_detail')
  9874. ->where('scydgy_id', $sid)
  9875. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9876. ->order('id', 'asc');
  9877. $this->applyActivePurchaseOrderDetailWhere($q);
  9878. $rows = $q->select();
  9879. } catch (\Throwable $e) {
  9880. try {
  9881. $q = Db::table('purchase_order_detail')
  9882. ->where('scydgy_id', $sid)
  9883. ->order('id', 'asc');
  9884. $this->applyActivePurchaseOrderDetailWhere($q);
  9885. $rows = $q->select();
  9886. } catch (\Throwable $e2) {
  9887. $rows = [];
  9888. }
  9889. }
  9890. if (!is_array($rows)) {
  9891. $rows = [];
  9892. }
  9893. $list = [];
  9894. foreach ($rows as $row) {
  9895. if (!is_array($row)) {
  9896. continue;
  9897. }
  9898. $amount = trim((string)($row['amount'] ?? ''));
  9899. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9900. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9901. $oper = '';
  9902. if ($isQuoted) {
  9903. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9904. if ($oper === '') {
  9905. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9906. }
  9907. }
  9908. $list[] = [
  9909. 'id' => (int)($row['id'] ?? 0),
  9910. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9911. 'amount' => $amount,
  9912. 'amount_text' => $isQuoted ? $amount : '',
  9913. 'is_quoted' => $isQuoted,
  9914. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9915. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9916. 'oper_time' => $oper,
  9917. ];
  9918. }
  9919. $this->success('', null, [
  9920. 'scydgy_id' => $sid,
  9921. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9922. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9923. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9924. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9925. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9926. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9927. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9928. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9929. 'list' => $list,
  9930. ]);
  9931. }
  9932. /**
  9933. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9934. */
  9935. protected function isRfqOrderIssued(array $po): bool
  9936. {
  9937. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9938. return true;
  9939. }
  9940. $sid = (int)($po['scydgy_id'] ?? 0);
  9941. if ($sid >= 0) {
  9942. return false;
  9943. }
  9944. try {
  9945. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9946. $this->applyActivePurchaseOrderDetailWhere($q);
  9947. return (int)$q->count() > 0;
  9948. } catch (\Throwable $e) {
  9949. return false;
  9950. }
  9951. }
  9952. /**
  9953. * 批量:已有下发明细的手工询价 scydgy_id
  9954. *
  9955. * @param int[] $scydgyIds
  9956. * @return array<int, bool>
  9957. */
  9958. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9959. {
  9960. $set = [];
  9961. $ids = [];
  9962. foreach ($scydgyIds as $sid) {
  9963. $sid = (int)$sid;
  9964. if ($sid < 0) {
  9965. $ids[$sid] = true;
  9966. }
  9967. }
  9968. if ($ids === []) {
  9969. return $set;
  9970. }
  9971. try {
  9972. $q = Db::table('purchase_order_detail')
  9973. ->where('scydgy_id', 'in', array_keys($ids))
  9974. ->field('scydgy_id');
  9975. $this->applyActivePurchaseOrderDetailWhere($q);
  9976. $rows = $q->select();
  9977. } catch (\Throwable $e) {
  9978. return $set;
  9979. }
  9980. if (!is_array($rows)) {
  9981. return $set;
  9982. }
  9983. foreach ($rows as $row) {
  9984. if (!is_array($row)) {
  9985. continue;
  9986. }
  9987. $sid = (int)($row['scydgy_id'] ?? 0);
  9988. if ($sid < 0) {
  9989. $set[$sid] = true;
  9990. }
  9991. }
  9992. return $set;
  9993. }
  9994. /**
  9995. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9996. *
  9997. * @param int[] $scydgyIds
  9998. * @return array<int, bool>
  9999. */
  10000. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  10001. {
  10002. $set = [];
  10003. $ids = [];
  10004. foreach ($scydgyIds as $sid) {
  10005. $sid = (int)$sid;
  10006. if ($sid < 0) {
  10007. $ids[$sid] = true;
  10008. }
  10009. }
  10010. if ($ids === []) {
  10011. return $set;
  10012. }
  10013. try {
  10014. $q = Db::table('purchase_order_detail')
  10015. ->where('scydgy_id', 'in', array_keys($ids))
  10016. ->field('scydgy_id,amount');
  10017. $this->applyActivePurchaseOrderDetailWhere($q);
  10018. $rows = $q->select();
  10019. } catch (\Throwable $e) {
  10020. return $set;
  10021. }
  10022. if (!is_array($rows)) {
  10023. return $set;
  10024. }
  10025. foreach ($rows as $row) {
  10026. if (!is_array($row)) {
  10027. continue;
  10028. }
  10029. $amount = trim((string)($row['amount'] ?? ''));
  10030. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10031. continue;
  10032. }
  10033. $sid = (int)($row['scydgy_id'] ?? 0);
  10034. if ($sid < 0) {
  10035. $set[$sid] = true;
  10036. }
  10037. }
  10038. return $set;
  10039. }
  10040. /**
  10041. * 已下发且至少一家供应商已报价,才允许通知业务员
  10042. */
  10043. protected function canRfqNotifySalesman(array $po): bool
  10044. {
  10045. if (!$this->isRfqOrderIssued($po)) {
  10046. return false;
  10047. }
  10048. $sid = (int)($po['scydgy_id'] ?? 0);
  10049. if ($sid >= 0) {
  10050. return false;
  10051. }
  10052. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10053. return isset($quoted[$sid]);
  10054. }
  10055. protected function assertRfqCanNotifySalesman(array $po): void
  10056. {
  10057. if (!$this->isRfqOrderIssued($po)) {
  10058. $this->error('请先询价并等待供应商报价后再通知业务员');
  10059. }
  10060. if (!$this->canRfqNotifySalesman($po)) {
  10061. $this->error('供应商尚未报价,暂不能通知业务员');
  10062. }
  10063. }
  10064. /**
  10065. * 加载手工询价单(含可见性校验)
  10066. *
  10067. * @return array<string, mixed>
  10068. */
  10069. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10070. {
  10071. try {
  10072. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10073. } catch (\Throwable $e) {
  10074. $po = null;
  10075. }
  10076. if (!is_array($po)) {
  10077. $this->error('订单不存在');
  10078. }
  10079. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10080. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10081. $this->error('订单不存在');
  10082. }
  10083. if ($this->auth->isSuperAdmin()) {
  10084. return $po;
  10085. }
  10086. if ($this->canViewManualRfqOrder($po)) {
  10087. return $po;
  10088. }
  10089. $this->error('无权操作该订单');
  10090. }
  10091. /**
  10092. * @return string[]
  10093. */
  10094. protected function splitRfqSalesmanNames(string $raw): array
  10095. {
  10096. $parts = [];
  10097. $raw = trim($raw);
  10098. if ($raw === '') {
  10099. return [];
  10100. }
  10101. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10102. $v = trim((string)$piece);
  10103. if ($v !== '' && !in_array($v, $parts, true)) {
  10104. $parts[] = $v;
  10105. }
  10106. }
  10107. return $parts;
  10108. }
  10109. /**
  10110. * 按姓名匹配 fa_admin 邮箱
  10111. *
  10112. * @param string[] $names
  10113. * @return array<int, array{admin_id:int,name:string,email:string}>
  10114. */
  10115. protected function resolveRfqSalesmanContactRows(array $names): array
  10116. {
  10117. $out = [];
  10118. foreach ($names as $name) {
  10119. $name = trim((string)$name);
  10120. if ($name === '') {
  10121. continue;
  10122. }
  10123. $adminId = 0;
  10124. $email = '';
  10125. try {
  10126. $row = Db::name('admin')
  10127. ->where(function ($q) use ($name) {
  10128. $q->where('nickname', $name)->whereOr('username', $name);
  10129. })
  10130. ->where('status', 'normal')
  10131. ->order('id', 'asc')
  10132. ->field('id,nickname,username,email')
  10133. ->find();
  10134. } catch (\Throwable $e) {
  10135. $row = null;
  10136. }
  10137. if (is_array($row)) {
  10138. $adminId = (int)($row['id'] ?? 0);
  10139. $email = trim((string)($row['email'] ?? ''));
  10140. $disp = trim((string)($row['nickname'] ?? ''));
  10141. if ($disp === '') {
  10142. $disp = trim((string)($row['username'] ?? ''));
  10143. }
  10144. if ($disp !== '') {
  10145. $name = $disp;
  10146. }
  10147. }
  10148. $out[] = [
  10149. 'admin_id' => $adminId,
  10150. 'name' => $name,
  10151. 'email' => $email,
  10152. ];
  10153. }
  10154. return $out;
  10155. }
  10156. /**
  10157. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10158. */
  10159. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10160. {
  10161. if ($scydgyId >= 0) {
  10162. return;
  10163. }
  10164. try {
  10165. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10166. } catch (\Throwable $e) {
  10167. $po = null;
  10168. }
  10169. if (!is_array($po)) {
  10170. $this->error('订单不存在');
  10171. }
  10172. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10173. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10174. $this->error('订单不存在');
  10175. }
  10176. if ($this->auth->isSuperAdmin()) {
  10177. return;
  10178. }
  10179. [, $adminName] = $this->GetUseName();
  10180. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10181. if ($cywy !== '' && $cywy === $adminName) {
  10182. return;
  10183. }
  10184. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10185. try {
  10186. if ($this->auth->check($rule)) {
  10187. return;
  10188. }
  10189. } catch (\Throwable $e) {
  10190. }
  10191. }
  10192. $this->error('无权查看该订单');
  10193. }
  10194. /**
  10195. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10196. */
  10197. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10198. {
  10199. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10200. return ProcuremenStatus::PO_COMPLETED;
  10201. }
  10202. $sid = (int)($row['scydgy_id'] ?? 0);
  10203. if ($sid < 0) {
  10204. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10205. return '已通知业务员';
  10206. }
  10207. if ($hasQuoted) {
  10208. return '供应商已报价';
  10209. }
  10210. if ($hasIssued
  10211. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10212. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10213. return '待报价';
  10214. }
  10215. try {
  10216. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10217. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10218. if ((int)$detCntQuery->count() > 0) {
  10219. return '待报价';
  10220. }
  10221. } catch (\Throwable $e) {
  10222. }
  10223. return '待询价';
  10224. }
  10225. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10226. return '待入库评分';
  10227. }
  10228. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10229. return '待采购确认';
  10230. }
  10231. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10232. return '待确认供应商';
  10233. }
  10234. return '待协助下发';
  10235. }
  10236. /**
  10237. * 协助初选列表 — 批量软删除
  10238. */
  10239. public function pickDelete()
  10240. {
  10241. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10242. $this->error(__('Invalid parameters'));
  10243. }
  10244. if (!$this->procuremenCanPickDelete()) {
  10245. $this->error(__('You have no permission'));
  10246. }
  10247. $rowsRaw = $this->request->post('rows_json', '[]');
  10248. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10249. if (!is_array($rows) || $rows === []) {
  10250. $this->error('请至少勾选一条工序');
  10251. }
  10252. $done = 0;
  10253. Db::startTrans();
  10254. try {
  10255. foreach ($rows as $row) {
  10256. if (!is_array($row)) {
  10257. continue;
  10258. }
  10259. $this->softDeleteProcuremenPickRow($row);
  10260. $done++;
  10261. }
  10262. if ($done < 1) {
  10263. throw new \Exception('没有可删除的工序');
  10264. }
  10265. Db::commit();
  10266. } catch (\InvalidArgumentException $e) {
  10267. Db::rollback();
  10268. $this->error($e->getMessage());
  10269. } catch (\Throwable $e) {
  10270. Db::rollback();
  10271. $this->error($e->getMessage());
  10272. }
  10273. $this->pickHiddenScydgySetCache = null;
  10274. $this->success('已删除 ' . $done . ' 条工序');
  10275. }
  10276. /**
  10277. * 下发 — 手工新增工序(弹窗)
  10278. */
  10279. public function pickAdd()
  10280. {
  10281. if ($this->request->isPost()) {
  10282. $params = $this->request->post('row/a');
  10283. if (!is_array($params)) {
  10284. $this->error(__('Parameter %s can not be empty', ''));
  10285. }
  10286. try {
  10287. $sid = $this->saveManualPickOrder($params);
  10288. } catch (\InvalidArgumentException $e) {
  10289. $this->error($e->getMessage());
  10290. } catch (\Throwable $e) {
  10291. $this->error($e->getMessage());
  10292. }
  10293. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10294. }
  10295. return $this->view->fetch('procuremen/pick_add');
  10296. }
  10297. /**
  10298. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10299. */
  10300. public function pickSubmit()
  10301. {
  10302. if (!$this->request->isPost()) {
  10303. $this->error(__('Invalid parameters'));
  10304. }
  10305. // ---------- 接口订单数据 ----------
  10306. $rowJson = $this->request->post('row_json', '');
  10307. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10308. $companiesJson = $this->request->post('companies_json', '[]');
  10309. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10310. $companies = json_decode($companiesJson, true);
  10311. if (!is_array($companies)) {
  10312. $this->error('供应商数据无效');
  10313. }
  10314. $issueCompanies = $this->normalizePickCompanies($companies);
  10315. if ($issueCompanies === []) {
  10316. $this->error('请至少选择一家合作供应商');
  10317. }
  10318. $issueNameLabels = [];
  10319. foreach ($issueCompanies as $pc) {
  10320. $issueNameLabels[] = $pc['name'];
  10321. }
  10322. $issueNamesSummary = implode('、', $issueNameLabels);
  10323. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10324. if ($sysRq === '') {
  10325. $this->error('请选择招标截止日期');
  10326. }
  10327. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10328. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10329. (string)$this->request->post('delivery_deadline', ''),
  10330. true
  10331. );
  10332. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10333. if ($scoreRuleId <= 0) {
  10334. $this->error('请选择订单类型');
  10335. }
  10336. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10337. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10338. $this->error('订单类型无效,请刷新后重选');
  10339. }
  10340. $scoreRuleId = (int)$scoreRule['id'];
  10341. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10342. $isMerge = count($mergeRows) > 1;
  10343. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10344. $logMsg = '下发' . $procPart
  10345. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10346. $issueTime = date('Y-m-d H:i:s');
  10347. $logSidList = [];
  10348. foreach ($mergeRows as $row) {
  10349. if (!is_array($row)) {
  10350. continue;
  10351. }
  10352. $sid = $this->extractScydgyRowId($row);
  10353. if ($this->isValidScydgyRowId($sid)) {
  10354. $logSidList[$sid] = true;
  10355. }
  10356. }
  10357. $existingBySid = [];
  10358. if ($logSidList !== []) {
  10359. try {
  10360. $existingRows = Db::table('purchase_order')
  10361. ->where('scydgy_id', 'in', array_keys($logSidList))
  10362. ->select();
  10363. if (is_array($existingRows)) {
  10364. foreach ($existingRows as $poRow) {
  10365. if (!is_array($poRow)) {
  10366. continue;
  10367. }
  10368. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10369. if ($this->isValidScydgyRowId($sid)) {
  10370. $existingBySid[$sid] = $poRow;
  10371. }
  10372. }
  10373. }
  10374. } catch (\Throwable $e) {
  10375. $existingBySid = [];
  10376. }
  10377. }
  10378. Db::startTrans();
  10379. try {
  10380. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10381. foreach ($mergeRows as $row) {
  10382. if (!is_array($row)) {
  10383. continue;
  10384. }
  10385. $sid = $this->extractScydgyRowId($row);
  10386. $this->upsertPurchaseOrderFromRow(
  10387. $row,
  10388. $sysRqDb,
  10389. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10390. $issueTime,
  10391. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10392. $deliveryDeadlineDb,
  10393. $scoreRule
  10394. );
  10395. }
  10396. foreach ($issueCompanies as $c) {
  10397. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10398. }
  10399. Db::commit();
  10400. } catch (\Throwable $e) {
  10401. Db::rollback();
  10402. $this->error($e->getMessage());
  10403. }
  10404. $poIdBySid = [];
  10405. if ($logSidList !== []) {
  10406. try {
  10407. $poIdBySid = Db::table('purchase_order')
  10408. ->where('scydgy_id', 'in', array_keys($logSidList))
  10409. ->column('id', 'scydgy_id');
  10410. } catch (\Throwable $e) {
  10411. $poIdBySid = [];
  10412. }
  10413. }
  10414. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10415. if ($logSidList !== []) {
  10416. list($adminId, $adminName) = $this->GetUseName();
  10417. $logRows = [];
  10418. $seenLogSid = [];
  10419. foreach ($mergeRows as $row) {
  10420. if (!is_array($row)) {
  10421. continue;
  10422. }
  10423. $ids = $this->extractScydgyRowId($row);
  10424. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10425. continue;
  10426. }
  10427. $seenLogSid[$ids] = true;
  10428. $poIdLog = null;
  10429. if (isset($poIdBySid[$ids])) {
  10430. $tid = (int)$poIdBySid[$ids];
  10431. $poIdLog = $tid > 0 ? $tid : null;
  10432. }
  10433. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10434. $ids,
  10435. 'issue_submit',
  10436. $logMsg,
  10437. $poIdLog,
  10438. (int)$adminId,
  10439. (string)$adminName
  10440. );
  10441. }
  10442. if ($logRows !== []) {
  10443. try {
  10444. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10445. } catch (\Throwable $e) {
  10446. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10447. }
  10448. }
  10449. }
  10450. $notifyErrors = [];
  10451. $posNotify = [];
  10452. if ($logSidList !== []) {
  10453. try {
  10454. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10455. } catch (\Throwable $e) {
  10456. $posNotify = [];
  10457. }
  10458. }
  10459. if (!is_array($posNotify)) {
  10460. $posNotify = [];
  10461. }
  10462. foreach ($posNotify as $i => $prow) {
  10463. if (is_array($posNotify[$i])) {
  10464. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10465. }
  10466. }
  10467. $ccydhPick = '';
  10468. foreach ($mergeRows as $row) {
  10469. if (!is_array($row)) {
  10470. continue;
  10471. }
  10472. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10473. if ($ccydhPick !== '') {
  10474. break;
  10475. }
  10476. }
  10477. $notifyBundleBase = [
  10478. 'ccydh' => $ccydhPick,
  10479. 'pos' => $posNotify,
  10480. 'merge_rows' => $mergeRows,
  10481. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10482. ];
  10483. try {
  10484. $this->notifyDryRunPreview = [];
  10485. foreach ($issueCompanies as $c) {
  10486. if (!is_array($c)) {
  10487. continue;
  10488. }
  10489. $cname = trim((string)($c['name'] ?? ''));
  10490. if ($cname === '') {
  10491. continue;
  10492. }
  10493. try {
  10494. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10495. } catch (\Throwable $e) {
  10496. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10497. }
  10498. }
  10499. } catch (\Throwable $e) {
  10500. $this->error('通知发送失败:' . $e->getMessage());
  10501. }
  10502. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10503. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10504. }
  10505. if ($this->isProcuremenNotifyDryRun()) {
  10506. $this->success('【演练模式】已保存并生成通知预览', '', [
  10507. 'notify_dry_run' => true,
  10508. 'notify_preview' => $this->notifyDryRunPreview,
  10509. ]);
  10510. }
  10511. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10512. }
  10513. /**
  10514. * 确认供应商弹窗
  10515. */
  10516. public function auditIssue()
  10517. {
  10518. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10519. if (is_array($ids)) {
  10520. $ids = isset($ids[0]) ? $ids[0] : '';
  10521. }
  10522. $ids = trim((string)$ids);
  10523. if ($ids === '') {
  10524. $this->error(__('Invalid parameters'));
  10525. }
  10526. if ($this->request->isPost()) {
  10527. $this->error('请使用弹窗内「确认」提交');
  10528. }
  10529. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10530. $pos = $bundle['pos'];
  10531. if ($pos === []) {
  10532. $this->error('该订单不在待确认供应商状态');
  10533. }
  10534. $po = $pos[0];
  10535. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10536. if ($quoteGroups === []) {
  10537. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10538. }
  10539. $pickedName = '';
  10540. foreach ($pos as $poRow) {
  10541. if (!is_array($poRow)) {
  10542. continue;
  10543. }
  10544. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10545. if ($pn !== '') {
  10546. $pickedName = $pn;
  10547. break;
  10548. }
  10549. }
  10550. $this->view->assign('po', $po);
  10551. $this->view->assign('scydgyId', $ids);
  10552. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10553. $mergeRows = $bundle['merge_rows'];
  10554. $this->view->assign('processRows', $mergeRows);
  10555. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10556. $this->view->assign('processCount', count($mergeRows));
  10557. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10558. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10559. $this->view->assign('pickedCompanyName', $pickedName);
  10560. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10561. if ($sysRqForView === '') {
  10562. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10563. }
  10564. $this->view->assign('sysRq', $sysRqForView);
  10565. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10566. if ($deliveryDeadlineForView === '') {
  10567. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10568. }
  10569. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10570. $this->ensurePurchaseOrderManualPickColumns();
  10571. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10572. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10573. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10574. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10575. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10576. $pickedName = $manualPickInfo['company'];
  10577. $this->view->assign('pickedCompanyName', $pickedName);
  10578. }
  10579. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10580. $this->view->assign('manualPicked', $manualPicked);
  10581. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10582. $this->view->assign('quoteVisible', $quoteVisible);
  10583. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10584. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10585. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10586. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10587. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10588. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10589. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10590. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10591. return $this->view->fetch('procuremen/audit_issue');
  10592. }
  10593. /**
  10594. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10595. *
  10596. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10597. */
  10598. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10599. {
  10600. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10601. return false;
  10602. }
  10603. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10604. return false;
  10605. }
  10606. return true;
  10607. }
  10608. /**
  10609. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10610. *
  10611. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10612. */
  10613. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10614. {
  10615. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10616. return false;
  10617. }
  10618. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10619. return false;
  10620. }
  10621. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10622. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10623. return true;
  10624. }
  10625. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10626. }
  10627. /**
  10628. * 确认页 — 补加供应商弹窗
  10629. */
  10630. public function auditAppend()
  10631. {
  10632. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10633. $this->error(__('You have no permission'));
  10634. }
  10635. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10636. if (is_array($ids)) {
  10637. $ids = isset($ids[0]) ? $ids[0] : '';
  10638. }
  10639. $ids = trim((string)$ids);
  10640. if ($ids === '') {
  10641. $this->error(__('Invalid parameters'));
  10642. }
  10643. if ($this->request->isPost()) {
  10644. $this->error('请使用弹窗内「确认」提交');
  10645. }
  10646. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10647. if (($bundle['pos'] ?? []) === []) {
  10648. $this->error('该订单不在待确认供应商状态');
  10649. }
  10650. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10651. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10652. $this->error('已开标验证,不能再补加供应商');
  10653. }
  10654. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10655. $this->error('已指定供应商,不能再补加供应商');
  10656. }
  10657. $this->error('已经超过了招标截止日期,不可操作');
  10658. }
  10659. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10660. $existingNames = [];
  10661. foreach ($quoteGroups as $g) {
  10662. if (!is_array($g)) {
  10663. continue;
  10664. }
  10665. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10666. if ($n !== '') {
  10667. $existingNames[$n] = true;
  10668. }
  10669. }
  10670. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10671. $mergeRows = $bundle['merge_rows'] ?? [];
  10672. $this->view->assign('scydgyId', $ids);
  10673. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10674. $this->view->assign('po', $po);
  10675. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10676. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10677. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10678. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10679. if ($sysRqForView === '') {
  10680. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10681. }
  10682. $this->view->assign('sysRq', $sysRqForView);
  10683. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10684. if ($deliveryDeadlineForView === '') {
  10685. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10686. }
  10687. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10688. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10689. }
  10690. /**
  10691. * 确认页 — 补加供应商提交
  10692. */
  10693. public function auditAppendSubmit()
  10694. {
  10695. if (!$this->request->isPost()) {
  10696. $this->error(__('Invalid parameters'));
  10697. }
  10698. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10699. $this->error(__('You have no permission'));
  10700. }
  10701. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10702. if ($ids === '') {
  10703. $this->error(__('Invalid parameters'));
  10704. }
  10705. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10706. if (($bundle['pos'] ?? []) === []) {
  10707. $this->error('该订单不在待确认供应商状态');
  10708. }
  10709. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10710. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10711. $this->error('已开标验证,不能再补加供应商');
  10712. }
  10713. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10714. $this->error('已指定供应商,不能再补加供应商');
  10715. }
  10716. $this->error('已经超过了招标截止日期,不可操作');
  10717. }
  10718. $companiesJson = $this->request->post('companies_json', '[]');
  10719. $companies = json_decode((string)$companiesJson, true);
  10720. if (!is_array($companies)) {
  10721. $this->error('供应商数据无效');
  10722. }
  10723. $issueCompanies = $this->normalizePickCompanies($companies);
  10724. if ($issueCompanies === []) {
  10725. $this->error('请至少选择一家合作供应商');
  10726. }
  10727. $mergeRows = $bundle['merge_rows'] ?? [];
  10728. if (!is_array($mergeRows) || $mergeRows === []) {
  10729. $this->error('未找到工序行,无法补加');
  10730. }
  10731. $existingNames = [];
  10732. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10733. if (!is_array($g)) {
  10734. continue;
  10735. }
  10736. $n = trim((string)($g['company_name'] ?? ''));
  10737. if ($n !== '') {
  10738. $existingNames[$n] = true;
  10739. }
  10740. }
  10741. $toAdd = [];
  10742. foreach ($issueCompanies as $c) {
  10743. if (!is_array($c)) {
  10744. continue;
  10745. }
  10746. $n = trim((string)($c['name'] ?? ''));
  10747. if ($n === '' || isset($existingNames[$n])) {
  10748. continue;
  10749. }
  10750. $toAdd[] = $c;
  10751. }
  10752. if ($toAdd === []) {
  10753. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10754. }
  10755. $addedNames = [];
  10756. Db::startTrans();
  10757. try {
  10758. foreach ($toAdd as $c) {
  10759. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10760. $addedNames[] = trim((string)($c['name'] ?? ''));
  10761. }
  10762. Db::commit();
  10763. } catch (\Throwable $e) {
  10764. Db::rollback();
  10765. $this->error($e->getMessage());
  10766. }
  10767. $notifyErrors = [];
  10768. $notifyBundleBase = [
  10769. 'ccydh' => $bundle['ccydh'] ?? '',
  10770. 'pos' => $bundle['pos'] ?? [],
  10771. 'merge_rows' => $mergeRows,
  10772. ];
  10773. foreach ($toAdd as $c) {
  10774. if (!is_array($c)) {
  10775. continue;
  10776. }
  10777. $cname = trim((string)($c['name'] ?? ''));
  10778. if ($cname === '') {
  10779. continue;
  10780. }
  10781. try {
  10782. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10783. } catch (\Throwable $e) {
  10784. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10785. }
  10786. }
  10787. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10788. $seenLogSid = [];
  10789. foreach ($bundle['pos'] ?? [] as $poRow) {
  10790. if (!is_array($poRow)) {
  10791. continue;
  10792. }
  10793. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10794. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10795. continue;
  10796. }
  10797. $seenLogSid[$sid] = true;
  10798. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10799. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10800. }
  10801. if ($seenLogSid === []) {
  10802. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10803. if ($this->isValidScydgyRowId($logSid)) {
  10804. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10805. }
  10806. }
  10807. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10808. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10809. }
  10810. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10811. }
  10812. /**
  10813. * 开标双重验证 — 可选验证人列表
  10814. */
  10815. public function bidOpenUsers()
  10816. {
  10817. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10818. $this->error('无权限');
  10819. }
  10820. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10821. if ($scydgyId !== '') {
  10822. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10823. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10824. $this->success('已完成开标验证', null, [
  10825. 'verified' => 1,
  10826. 'users' => [],
  10827. ]);
  10828. }
  10829. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10830. $this->error('本单已指定供应商,无需再开标');
  10831. }
  10832. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10833. }
  10834. $this->success('', null, [
  10835. 'verified' => 0,
  10836. 'users' => $this->listBidOpenVerifierCandidates(),
  10837. ]);
  10838. }
  10839. /**
  10840. * 开标双重验证 — 向指定管理员发送短信验证码
  10841. */
  10842. public function bidOpenSendCode()
  10843. {
  10844. if (!$this->request->isPost()) {
  10845. $this->error(__('Invalid parameters'));
  10846. }
  10847. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10848. $this->error('无权限');
  10849. }
  10850. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10851. $adminId = (int)$this->request->post('admin_id', 0);
  10852. if ($scydgyId === '' || $adminId <= 0) {
  10853. $this->error('参数无效');
  10854. }
  10855. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10856. if ($bundle['pos'] === []) {
  10857. $this->error('该订单不在待确认供应商状态');
  10858. }
  10859. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10860. $this->success('已完成开标验证,无需重复发送');
  10861. }
  10862. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10863. $this->error('本单已指定供应商,无需再开标');
  10864. }
  10865. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10866. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10867. if ($ccydh === '') {
  10868. $this->error('订单号无效');
  10869. }
  10870. $admin = $this->loadBidOpenAdminUser($adminId);
  10871. if ($admin === null) {
  10872. $this->error('验证人无效或未绑定手机号');
  10873. }
  10874. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10875. $cd = max(30, min(120, $cd));
  10876. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10877. $this->error('发送过于频繁,请稍后再试');
  10878. }
  10879. $code = (string)random_int(100000, 999999);
  10880. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10881. $ttl = max(60, min(600, $ttl));
  10882. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10883. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10884. try {
  10885. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10886. } catch (\Throwable $e) {
  10887. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10888. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10889. $this->error($e->getMessage());
  10890. }
  10891. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10892. }
  10893. /**
  10894. * 开标双重验证 — 两人验证码校验并记录
  10895. */
  10896. public function bidOpenVerify()
  10897. {
  10898. if (!$this->request->isPost()) {
  10899. $this->error(__('Invalid parameters'));
  10900. }
  10901. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10902. $this->error('无权限');
  10903. }
  10904. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10905. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10906. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10907. $code1 = trim((string)$this->request->post('code1', ''));
  10908. $code2 = trim((string)$this->request->post('code2', ''));
  10909. if ($scydgyId === '') {
  10910. $this->error('参数无效');
  10911. }
  10912. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10913. $this->error('请选择两位验证人');
  10914. }
  10915. if ($verifier1Id === $verifier2Id) {
  10916. $this->error('两位验证人不能相同');
  10917. }
  10918. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10919. $this->error('请输入6位短信验证码');
  10920. }
  10921. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10922. if ($bundle['pos'] === []) {
  10923. $this->error('该订单不在待确认供应商状态');
  10924. }
  10925. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10926. if ($ccydh === '') {
  10927. $this->error('订单号无效');
  10928. }
  10929. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10930. $this->success('已完成开标验证');
  10931. }
  10932. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10933. $this->error('本单已指定供应商,无需再开标');
  10934. }
  10935. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10936. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10937. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10938. if ($verifier1 === null || $verifier2 === null) {
  10939. $this->error('验证人无效或未绑定手机号');
  10940. }
  10941. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10942. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10943. }
  10944. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10945. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10946. }
  10947. try {
  10948. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10949. } catch (\Throwable $e) {
  10950. $this->error($e->getMessage());
  10951. }
  10952. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10953. }
  10954. /**
  10955. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10956. */
  10957. public function auditManualPick()
  10958. {
  10959. if (!$this->request->isPost()) {
  10960. $this->error(__('Invalid parameters'));
  10961. }
  10962. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10963. $this->error('无权限');
  10964. }
  10965. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10966. if ($scydgyId === '') {
  10967. $this->error('参数无效');
  10968. }
  10969. $companyName = trim((string)$this->request->post('selected_company', ''));
  10970. $reason = trim((string)$this->request->post('pick_reason', ''));
  10971. if ($companyName === '') {
  10972. $this->error('请选择一家供应商');
  10973. }
  10974. if ($reason === '') {
  10975. $this->error('请填写选择说明');
  10976. }
  10977. if (mb_strlen($reason) > 500) {
  10978. $this->error('选择说明不能超过500字');
  10979. }
  10980. $this->ensurePurchaseOrderManualPickColumns();
  10981. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10982. $pos = $bundle['pos'];
  10983. if ($pos === []) {
  10984. $this->error('该订单不在待确认供应商状态');
  10985. }
  10986. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10987. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10988. }
  10989. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10990. if ($quoteGroups === []) {
  10991. $this->error('暂无供应商,请确认已完成协助初选通知');
  10992. }
  10993. $matched = null;
  10994. foreach ($quoteGroups as $g) {
  10995. if (!is_array($g)) {
  10996. continue;
  10997. }
  10998. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10999. $matched = $g;
  11000. break;
  11001. }
  11002. }
  11003. if ($matched === null) {
  11004. $this->error('所选供应商不在本单报价列表中');
  11005. }
  11006. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11007. Db::startTrans();
  11008. try {
  11009. foreach ($pos as $poRow) {
  11010. if (!is_array($poRow)) {
  11011. continue;
  11012. }
  11013. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11014. if (!$this->isValidScydgyRowId($sid)) {
  11015. continue;
  11016. }
  11017. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11018. 'pick_company_name' => $companyName,
  11019. 'manual_pick' => 1,
  11020. 'manual_pick_reason' => $reason,
  11021. ]);
  11022. }
  11023. Db::commit();
  11024. } catch (\Throwable $e) {
  11025. Db::rollback();
  11026. $this->error($e->getMessage());
  11027. }
  11028. foreach ($pos as $poRow) {
  11029. if (!is_array($poRow)) {
  11030. continue;
  11031. }
  11032. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11033. if (!$this->isValidScydgyRowId($sid)) {
  11034. continue;
  11035. }
  11036. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11037. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11038. }
  11039. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11040. try {
  11041. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11042. if ($ccydh !== '') {
  11043. // 重新加载以拿到未掩码报价参与计分
  11044. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11045. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11046. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11047. }
  11048. } catch (\Throwable $e) {
  11049. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11050. }
  11051. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11052. }
  11053. /**
  11054. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11055. */
  11056. public function auditSubmit()
  11057. {
  11058. if (!$this->request->isPost()) {
  11059. $this->error(__('Invalid parameters'));
  11060. }
  11061. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11062. if ($scydgyId === '') {
  11063. $this->error('参数无效');
  11064. }
  11065. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11066. $pos = $bundle['pos'];
  11067. $mergeRows = $bundle['merge_rows'];
  11068. if ($pos === [] || $mergeRows === []) {
  11069. $this->error('该订单不在待确认供应商状态');
  11070. }
  11071. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11072. if ($quoteGroups === []) {
  11073. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11074. }
  11075. $companyName = trim((string)$this->request->post('selected_company', ''));
  11076. if ($companyName === '') {
  11077. $this->error('请选择一家供应商');
  11078. }
  11079. $matched = null;
  11080. foreach ($quoteGroups as $g) {
  11081. if (!is_array($g)) {
  11082. continue;
  11083. }
  11084. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11085. $matched = $g;
  11086. break;
  11087. }
  11088. }
  11089. if ($matched === null) {
  11090. $this->error('所选供应商不在本单报价列表中');
  11091. }
  11092. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11093. if ($sysRqDb === '') {
  11094. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11095. } else {
  11096. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11097. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11098. }
  11099. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11100. $this->error('未到招标截止日期,暂不可确认');
  11101. }
  11102. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11103. && !$this->isProcuremenManualPickedForBundle($bundle)
  11104. ) {
  11105. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11106. }
  11107. $procCnt = count($mergeRows);
  11108. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11109. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11110. Db::startTrans();
  11111. try {
  11112. foreach ($pos as $poRow) {
  11113. if (!is_array($poRow)) {
  11114. continue;
  11115. }
  11116. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11117. if (!$this->isValidScydgyRowId($sid)) {
  11118. continue;
  11119. }
  11120. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11121. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11122. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11123. 'pick_company_name' => $companyName,
  11124. 'sys_rq' => $sysRqDb,
  11125. ]);
  11126. }
  11127. Db::commit();
  11128. } catch (\Throwable $e) {
  11129. Db::rollback();
  11130. $this->error($e->getMessage());
  11131. }
  11132. foreach ($pos as $poRow) {
  11133. if (!is_array($poRow)) {
  11134. continue;
  11135. }
  11136. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11137. if (!$this->isValidScydgyRowId($sid)) {
  11138. continue;
  11139. }
  11140. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11141. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11142. }
  11143. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11144. }
  11145. /**
  11146. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11147. */
  11148. public function auditResendSms()
  11149. {
  11150. if (!$this->request->isPost()) {
  11151. $this->error(__('Invalid parameters'));
  11152. }
  11153. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11154. if ($scydgyId === '') {
  11155. $this->error('参数无效');
  11156. }
  11157. $loaded = $this->loadAuditResendBundle($scydgyId);
  11158. $mergeRows = $loaded['merge_rows'];
  11159. $bundle = $loaded['bundle'];
  11160. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11161. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11162. if ($quoteGroups === []) {
  11163. $this->error('暂无可通知的供应商');
  11164. }
  11165. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11166. $companiesJson = (string)$this->request->post('companies_json', '');
  11167. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11168. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11169. }
  11170. /**
  11171. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11172. */
  11173. public function auditResendEmail()
  11174. {
  11175. if (!$this->request->isPost()) {
  11176. $this->error(__('Invalid parameters'));
  11177. }
  11178. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11179. if ($scydgyId === '') {
  11180. $this->error('参数无效');
  11181. }
  11182. $loaded = $this->loadAuditResendBundle($scydgyId);
  11183. $mergeRows = $loaded['merge_rows'];
  11184. $bundle = $loaded['bundle'];
  11185. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11186. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11187. if ($quoteGroups === []) {
  11188. $this->error('暂无可通知的供应商');
  11189. }
  11190. $companiesJson = (string)$this->request->post('companies_json', '');
  11191. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11192. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11193. if ($companiesJson === '' && $selectedCompany === '') {
  11194. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11195. }
  11196. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11197. }
  11198. /**
  11199. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11200. *
  11201. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11202. * @return array<int, true> 已处理的 scydgy_id 集合
  11203. */
  11204. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11205. {
  11206. $pos = $bundle['pos'] ?? [];
  11207. if (!is_array($pos) || $pos === []) {
  11208. return [];
  11209. }
  11210. $sids = [];
  11211. $poIdBySid = [];
  11212. foreach ($pos as $poRow) {
  11213. if (!is_array($poRow)) {
  11214. continue;
  11215. }
  11216. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11217. if ($this->isValidScydgyRowId($sid)) {
  11218. $sids[$sid] = true;
  11219. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11220. if ($poId > 0) {
  11221. $poIdBySid[$sid] = $poId;
  11222. }
  11223. }
  11224. }
  11225. if ($sids === []) {
  11226. return [];
  11227. }
  11228. $logMsg = '重新下发';
  11229. $suffix = trim((string)$logSuffix, ',, ');
  11230. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11231. $logMsg .= ':从历史存证退回协助初选';
  11232. } else {
  11233. $logMsg .= ':退回协助初选';
  11234. }
  11235. Db::table('purchase_order')
  11236. ->where('scydgy_id', 'in', array_keys($sids))
  11237. ->update([
  11238. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11239. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11240. 'pick_company_name' => '',
  11241. 'pick_time' => null,
  11242. 'sys_rq' => null,
  11243. 'mod_rq' => null,
  11244. ]);
  11245. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11246. foreach (array_keys($sids) as $sid) {
  11247. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11248. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11249. }
  11250. return $sids;
  11251. }
  11252. /**
  11253. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11254. *
  11255. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11256. */
  11257. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11258. {
  11259. $scydgyId = trim($scydgyId);
  11260. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11261. if ($scydgyId === '') {
  11262. return $empty;
  11263. }
  11264. try {
  11265. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11266. } catch (\Throwable $e) {
  11267. $anchor = null;
  11268. }
  11269. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11270. return $empty;
  11271. }
  11272. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11273. if ($ccydh === '') {
  11274. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11275. }
  11276. try {
  11277. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11278. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11279. $pos = $query->order('scydgy_id', 'asc')->select();
  11280. } catch (\Throwable $e) {
  11281. $pos = [$anchor];
  11282. }
  11283. if (!is_array($pos) || $pos === []) {
  11284. $pos = [$anchor];
  11285. }
  11286. return [
  11287. 'ccydh' => $ccydh,
  11288. 'pos' => $pos,
  11289. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11290. ];
  11291. }
  11292. protected function purchaseOrderRowIsCompleted(array $po): bool
  11293. {
  11294. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11295. }
  11296. /**
  11297. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11298. *
  11299. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11300. */
  11301. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11302. {
  11303. $scydgyId = trim($scydgyId);
  11304. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11305. if ($scydgyId === '') {
  11306. return $empty;
  11307. }
  11308. try {
  11309. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11310. } catch (\Throwable $e) {
  11311. $anchor = null;
  11312. }
  11313. if (!is_array($anchor)) {
  11314. return $empty;
  11315. }
  11316. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11317. if ($ccydh === '') {
  11318. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11319. }
  11320. try {
  11321. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11322. } catch (\Throwable $e) {
  11323. $pos = [$anchor];
  11324. }
  11325. if (!is_array($pos) || $pos === []) {
  11326. $pos = [$anchor];
  11327. }
  11328. return [
  11329. 'ccydh' => $ccydh,
  11330. 'pos' => $pos,
  11331. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11332. ];
  11333. }
  11334. /**
  11335. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11336. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11337. */
  11338. public function auditAbandon()
  11339. {
  11340. if (!$this->request->isPost()) {
  11341. $this->error(__('Invalid parameters'));
  11342. }
  11343. $anchorIds = [];
  11344. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11345. if ($batchRaw !== '') {
  11346. $decoded = json_decode($batchRaw, true);
  11347. if (is_array($decoded)) {
  11348. foreach ($decoded as $id) {
  11349. $s = trim((string)$id);
  11350. if ($s !== '') {
  11351. $anchorIds[] = $s;
  11352. }
  11353. }
  11354. }
  11355. }
  11356. if ($anchorIds === []) {
  11357. $single = trim((string)$this->request->post('scydgy_id', ''));
  11358. if ($single !== '') {
  11359. $anchorIds[] = $single;
  11360. }
  11361. }
  11362. if ($anchorIds === []) {
  11363. $this->error('请至少选择一条订单');
  11364. }
  11365. $processedCcydh = [];
  11366. $doneOrders = 0;
  11367. $allSids = [];
  11368. Db::startTrans();
  11369. try {
  11370. foreach ($anchorIds as $anchorId) {
  11371. $fromArchive = false;
  11372. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11373. if (($bundle['pos'] ?? []) === []) {
  11374. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11375. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11376. }
  11377. if (($bundle['pos'] ?? []) === []) {
  11378. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11379. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11380. }
  11381. if (($bundle['pos'] ?? []) === []) {
  11382. continue;
  11383. }
  11384. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11385. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11386. if (isset($processedCcydh[$dedupeKey])) {
  11387. continue;
  11388. }
  11389. $processedCcydh[$dedupeKey] = true;
  11390. $sids = $fromArchive
  11391. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11392. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11393. if ($sids === []) {
  11394. continue;
  11395. }
  11396. $doneOrders++;
  11397. foreach (array_keys($sids) as $sid) {
  11398. $allSids[(int)$sid] = true;
  11399. }
  11400. }
  11401. if ($doneOrders < 1) {
  11402. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11403. }
  11404. Db::commit();
  11405. } catch (\Throwable $e) {
  11406. Db::rollback();
  11407. $this->error($e->getMessage());
  11408. }
  11409. $this->pickHiddenScydgySetCache = null;
  11410. $msg = $doneOrders > 1
  11411. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11412. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11413. $this->success($msg);
  11414. }
  11415. /**
  11416. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11417. */
  11418. public function archiveAbandon()
  11419. {
  11420. return $this->auditAbandon();
  11421. }
  11422. /**
  11423. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11424. */
  11425. public function purchaseApprovalReject()
  11426. {
  11427. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11428. $this->error(__('Invalid parameters'));
  11429. }
  11430. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11431. $this->error(__('You have no permission'));
  11432. }
  11433. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11434. $decoded = json_decode($batchRaw, true);
  11435. if (!is_array($decoded) || $decoded === []) {
  11436. $this->error('提交数据无效');
  11437. }
  11438. $done = 0;
  11439. Db::startTrans();
  11440. try {
  11441. foreach ($decoded as $item) {
  11442. if (!is_array($item)) {
  11443. continue;
  11444. }
  11445. $sid = (int)($item['scydgy_id'] ?? 0);
  11446. if (!$this->isValidScydgyRowId($sid)) {
  11447. continue;
  11448. }
  11449. $this->runPurchaseApprovalRejectForSid($sid);
  11450. $done++;
  11451. }
  11452. if ($done < 1) {
  11453. throw new \Exception('所选订单均不在待审批状态');
  11454. }
  11455. Db::commit();
  11456. } catch (\Throwable $e) {
  11457. Db::rollback();
  11458. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11459. }
  11460. $this->pickHiddenScydgySetCache = null;
  11461. $this->success('已驳回并退回「协助审批下发」');
  11462. }
  11463. /**
  11464. * @throws \Exception
  11465. */
  11466. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11467. {
  11468. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11469. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11470. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11471. $allIds = $this->purchaseOrderDetail($sid);
  11472. if ($allIds === []) {
  11473. throw new \Exception('未找到下发明细');
  11474. }
  11475. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11476. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11477. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11478. 'pick_company_name' => '',
  11479. ]);
  11480. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11481. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11482. $poId = 0;
  11483. try {
  11484. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11485. if (is_array($po)) {
  11486. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11487. }
  11488. } catch (\Throwable $e) {
  11489. }
  11490. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11491. }
  11492. /**
  11493. * 审核弹窗(旧入口,POST 已关闭)
  11494. */
  11495. public function review()
  11496. {
  11497. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11498. $this->error(__('You have no permission'));
  11499. }
  11500. if ($this->request->isPost()) {
  11501. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11502. }
  11503. $this->view->assign('pickMode', 0);
  11504. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11505. }
  11506. /**
  11507. * 审核弹窗获取公司列表
  11508. */
  11509. public function reviewCompanies()
  11510. {
  11511. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11512. $this->error(__('You have no permission'));
  11513. }
  11514. if (!$this->request->isAjax()) {
  11515. $this->error(__('Invalid parameters'));
  11516. }
  11517. $list = [];
  11518. try {
  11519. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11520. $rows = Db::table('customer')
  11521. ->where(function ($q) {
  11522. $q->where('status', 1)
  11523. ->whereOr('status', '1')
  11524. ->whereOr('status', '')
  11525. ->whereNull('status');
  11526. })
  11527. ->order('id', 'desc')
  11528. ->select();
  11529. } catch (\Throwable $e) {
  11530. $this->success('', '', []);
  11531. return;
  11532. }
  11533. if (!is_array($rows)) {
  11534. $this->success('', '', []);
  11535. return;
  11536. }
  11537. $detailColCandidates = [
  11538. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11539. 'company_detail', 'company_desc', 'address',
  11540. ];
  11541. foreach ($rows as $row) {
  11542. if (!is_array($row)) {
  11543. continue;
  11544. }
  11545. $norm = [];
  11546. foreach ($row as $k => $v) {
  11547. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11548. }
  11549. $row = $norm;
  11550. $st = $row['status'] ?? '';
  11551. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11552. continue;
  11553. }
  11554. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11555. if ($payload === null) {
  11556. continue;
  11557. }
  11558. $detail = '';
  11559. foreach ($detailColCandidates as $dk) {
  11560. if (!isset($row[$dk])) {
  11561. continue;
  11562. }
  11563. $dv = trim((string)$row[$dk]);
  11564. if ($dv !== '') {
  11565. $detail = $dv;
  11566. break;
  11567. }
  11568. }
  11569. $payload['detail'] = $detail;
  11570. $list[] = $this->maskSupplierContactFields($payload);
  11571. }
  11572. $this->success('', '', $list);
  11573. }
  11574. /**
  11575. * 采购确认-下发明细弹窗:
  11576. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11577. */
  11578. public function outward_detail()
  11579. {
  11580. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11581. if (is_array($ids)) {
  11582. $ids = isset($ids[0]) ? $ids[0] : '';
  11583. }
  11584. $ids = trim((string)$ids);
  11585. if ($ids === '') {
  11586. $this->error(__('Invalid parameters'));
  11587. }
  11588. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11589. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11590. $wffTab = 'all';
  11591. }
  11592. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11593. $purchaseOrderId = 0;
  11594. $po = null;
  11595. try {
  11596. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11597. if (is_array($po)) {
  11598. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11599. }
  11600. } catch (\Throwable $e) {
  11601. $purchaseOrderId = 0;
  11602. $po = null;
  11603. }
  11604. if (!$isPurchaseConfirm && is_array($po)) {
  11605. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11606. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11607. $isPurchaseConfirm = true;
  11608. }
  11609. }
  11610. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11611. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11612. $confirmProcessCount = 1;
  11613. $confirmPickGroups = [];
  11614. $processDisplayRows = [];
  11615. $allDetailsBySid = [];
  11616. $requiredSidList = [];
  11617. $sidList = [$ids];
  11618. if ($isPurchaseConfirm) {
  11619. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11620. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11621. if ($mergeRows !== []) {
  11622. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11623. }
  11624. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11625. if ($confirmBundle['pos'] !== []) {
  11626. $sidList = [];
  11627. foreach ($confirmBundle['pos'] as $poRow) {
  11628. if (!is_array($poRow)) {
  11629. continue;
  11630. }
  11631. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11632. if (!$this->isValidScydgyRowId($sid)) {
  11633. continue;
  11634. }
  11635. $sidList[] = (string)$sid;
  11636. $requiredSidList[] = $sid;
  11637. }
  11638. }
  11639. if ($sidList === []) {
  11640. $sidList = [$ids];
  11641. $requiredSidList = [(int)$ids];
  11642. }
  11643. $confirmProcessCount = max(1, count($requiredSidList));
  11644. if (is_array($po) && $purchaseOrderId <= 0) {
  11645. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11646. }
  11647. }
  11648. $rows = [];
  11649. try {
  11650. if (count($sidList) === 1) {
  11651. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11652. } else {
  11653. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11654. }
  11655. } catch (\Throwable $e) {
  11656. $rows = [];
  11657. }
  11658. if ($isPurchaseConfirm) {
  11659. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11660. }
  11661. foreach ($rows as &$r) {
  11662. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11663. $r['id'] = $r['ID'];
  11664. }
  11665. if (isset($r['createtime'])) {
  11666. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11667. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11668. } else {
  11669. $r['createtime_text'] = (string)$r['createtime'];
  11670. }
  11671. } else {
  11672. $r['createtime_text'] = '';
  11673. }
  11674. if (is_array($r)) {
  11675. $r = $this->maskSupplierContactFields($r);
  11676. }
  11677. }
  11678. unset($r);
  11679. $pickedCompanyName = '';
  11680. $manualPicked = 0;
  11681. $manualPickReason = '';
  11682. $quoteVisible = 0;
  11683. $bidOpenVerified = 0;
  11684. if ($isPurchaseConfirm) {
  11685. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11686. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11687. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11688. }
  11689. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11690. $confirmBundle['pos'] = [$po];
  11691. }
  11692. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11693. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11694. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11695. if ($manualPickInfo['company'] !== '') {
  11696. $pickedCompanyName = $manualPickInfo['company'];
  11697. }
  11698. if ($pickedCompanyName === '') {
  11699. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11700. if (!is_array($poRow)) {
  11701. continue;
  11702. }
  11703. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11704. if ($pn !== '') {
  11705. $pickedCompanyName = $pn;
  11706. break;
  11707. }
  11708. }
  11709. }
  11710. // 再兜底:直接读当前主单字段
  11711. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11712. $manualPicked = 1;
  11713. if ($manualPickReason === '') {
  11714. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11715. }
  11716. if ($pickedCompanyName === '') {
  11717. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11718. }
  11719. }
  11720. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11721. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11722. }
  11723. $this->view->assign('rows', $rows ?: []);
  11724. $this->view->assign('rowCount', count($rows ?: []));
  11725. $this->view->assign('scydgyId', $ids);
  11726. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11727. $this->view->assign('headTitle', $headTitle);
  11728. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11729. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11730. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11731. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11732. $this->view->assign('processDisplayRows', $processDisplayRows);
  11733. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11734. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11735. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11736. $this->view->assign('manualPicked', $manualPicked);
  11737. $this->view->assign('manualPickReason', $manualPickReason);
  11738. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11739. $this->view->assign('quoteVisible', $quoteVisible);
  11740. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11741. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11742. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11743. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11744. $sysRqDisplay = '—';
  11745. if ($isPurchaseConfirm) {
  11746. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11747. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11748. );
  11749. }
  11750. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11751. $this->view->assign('sysRq', $isPurchaseConfirm
  11752. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11753. : '');
  11754. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11755. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11756. : '');
  11757. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11758. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11759. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11760. if ($isPurchaseConfirm) {
  11761. return $this->view->fetch();
  11762. }
  11763. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11764. $this->view->engine->layout(false);
  11765. try {
  11766. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11767. $this->view->assign('dialogBody', $bodyHtml);
  11768. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11769. } finally {
  11770. if ($restoreLayout) {
  11771. $this->view->engine->layout($restoreLayout);
  11772. }
  11773. }
  11774. }
  11775. /**
  11776. * 月度导出记录表(不存在时自动创建)
  11777. */
  11778. protected function ensurePurchaseMonthExportLogTable(): void
  11779. {
  11780. try {
  11781. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11782. } catch (\Throwable $e) {
  11783. Db::execute(
  11784. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11785. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11786. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11787. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11788. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11789. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11790. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11791. `createtime` int(10) unsigned DEFAULT NULL,
  11792. PRIMARY KEY (`id`),
  11793. KEY `idx_ym` (`ym`),
  11794. KEY `idx_ct` (`createtime`)
  11795. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11796. );
  11797. }
  11798. }
  11799. /**
  11800. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11801. *
  11802. * @param array<int, mixed> $dbRows
  11803. * @return array<int, array<string, mixed>>
  11804. */
  11805. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11806. {
  11807. $keyword = trim((string)$this->request->get('search', ''));
  11808. if ($keyword === '') {
  11809. $keyword = trim((string)$this->request->request('search', ''));
  11810. }
  11811. $filter = $this->request->get('filter', '');
  11812. $op = $this->request->get('op', '');
  11813. if (is_string($filter) && $filter !== '') {
  11814. $filterArr = (array)json_decode($filter, true);
  11815. } else {
  11816. $filterArr = is_array($filter) ? $filter : [];
  11817. }
  11818. if (is_string($op) && $op !== '') {
  11819. $opArr = (array)json_decode($op, true);
  11820. } else {
  11821. $opArr = is_array($op) ? $op : [];
  11822. }
  11823. if ($keyword === '' && $filterArr === []) {
  11824. return array_values(array_filter($dbRows, 'is_array'));
  11825. }
  11826. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11827. $out = [];
  11828. foreach ($dbRows as $row) {
  11829. if (!is_array($row)) {
  11830. continue;
  11831. }
  11832. if ($keyword !== '') {
  11833. $hit = false;
  11834. foreach ($searchFields as $f) {
  11835. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11836. $hit = true;
  11837. break;
  11838. }
  11839. }
  11840. if (!$hit) {
  11841. continue;
  11842. }
  11843. }
  11844. $passFilter = true;
  11845. foreach ($filterArr as $field => $val) {
  11846. $field = (string)$field;
  11847. $val = trim((string)$val);
  11848. if ($field === '' || $val === '') {
  11849. continue;
  11850. }
  11851. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11852. continue;
  11853. }
  11854. $cell = (string)($row[$field] ?? '');
  11855. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11856. if ($mode === '=' || $mode === 'EQUAL') {
  11857. if (strcasecmp($cell, $val) !== 0) {
  11858. $passFilter = false;
  11859. break;
  11860. }
  11861. } elseif (mb_stripos($cell, $val) === false) {
  11862. $passFilter = false;
  11863. break;
  11864. }
  11865. }
  11866. if (!$passFilter) {
  11867. continue;
  11868. }
  11869. $out[] = $row;
  11870. }
  11871. return $out;
  11872. }
  11873. /**
  11874. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11875. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11876. */
  11877. public function export_month_outward()
  11878. {
  11879. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11880. $this->error(__('You have no permission'));
  11881. }
  11882. $bundle = $this->prepareMonthOutwardExportBundle();
  11883. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11884. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11885. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11886. $spreadsheet = new Spreadsheet();
  11887. $sheet = $spreadsheet->getActiveSheet();
  11888. $sheet->setTitle('外协加工明细');
  11889. $mon = (int)substr($ym, 5, 2);
  11890. $sheet->mergeCells('A1:H1');
  11891. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11892. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11893. $sheet->getStyle('A1')->getAlignment()
  11894. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11895. ->setVertical(Alignment::VERTICAL_CENTER);
  11896. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11897. $col = 'A';
  11898. foreach ($headers as $h) {
  11899. $sheet->setCellValue($col . '2', $h);
  11900. $col++;
  11901. }
  11902. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11903. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11904. $rowNum = 3;
  11905. $sumSubtotalCounts = 0;
  11906. $grandAmount = 0.0;
  11907. $globalSeq = 0;
  11908. if ($groups === []) {
  11909. $sheet->mergeCells('A3:H3');
  11910. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11911. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11912. $rowNum = 4;
  11913. } else {
  11914. foreach ($groups as $items) {
  11915. if ($items === []) {
  11916. continue;
  11917. }
  11918. $groupLineCount = count($items);
  11919. $subAmount = 0.0;
  11920. foreach ($items as $line) {
  11921. $globalSeq++;
  11922. $dr = $line['detail'];
  11923. $amt = $this->procuremenExportAmount($dr);
  11924. $subAmount += $amt;
  11925. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11926. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11927. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11928. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11929. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11930. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11931. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11932. $sheet->setCellValue('H' . $rowNum, $amt);
  11933. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11934. $rowNum++;
  11935. }
  11936. $sumSubtotalCounts += $groupLineCount;
  11937. $grandAmount += $subAmount;
  11938. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11939. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11940. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11941. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11942. ->setVertical(Alignment::VERTICAL_CENTER);
  11943. $rowNum++;
  11944. }
  11945. }
  11946. $sheet->setCellValue('A' . $rowNum, '总计');
  11947. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11948. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11949. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11950. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11951. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11952. $lastRow = $rowNum;
  11953. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11954. 'borders' => [
  11955. 'allBorders' => [
  11956. 'borderStyle' => Border::BORDER_THIN,
  11957. 'color' => ['rgb' => '000000'],
  11958. ],
  11959. ],
  11960. ]);
  11961. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11962. if ($lastRow >= 3) {
  11963. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11964. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11965. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11966. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11967. }
  11968. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11969. $sheet->getColumnDimension('A')->setWidth(7);
  11970. $sheet->getColumnDimension('B')->setWidth(16);
  11971. $sheet->getColumnDimension('C')->setWidth(52);
  11972. $sheet->getColumnDimension('D')->setWidth(32);
  11973. $sheet->getColumnDimension('E')->setWidth(12);
  11974. $sheet->getColumnDimension('F')->setWidth(44);
  11975. $sheet->getColumnDimension('G')->setWidth(26);
  11976. $sheet->getColumnDimension('H')->setWidth(13);
  11977. $sheet->getRowDimension(1)->setRowHeight(28);
  11978. $ymCompact = str_replace('-', '', $ym);
  11979. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11980. $filename = $fileBase . '.xlsx';
  11981. try {
  11982. $this->ensurePurchaseMonthExportLogTable();
  11983. list($adminId, $adminName) = $this->GetUseName();
  11984. Db::table('purchase_month_export_log')->insert([
  11985. 'ym' => $ym,
  11986. 'admin_id' => (int)$adminId,
  11987. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11988. 'row_count' => count($exportLines),
  11989. 'total_amount' => round($grandAmount, 2),
  11990. 'createtime' => time(),
  11991. ]);
  11992. } catch (\Throwable $e) {
  11993. Log::write('month export log: ' . $e->getMessage(), 'error');
  11994. }
  11995. if (ob_get_length()) {
  11996. ob_end_clean();
  11997. }
  11998. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11999. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12000. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12001. header('Cache-Control: max-age=0');
  12002. $writer = new Xlsx($spreadsheet);
  12003. $writer->save('php://output');
  12004. $spreadsheet->disconnectWorksheets();
  12005. unset($spreadsheet);
  12006. exit;
  12007. }
  12008. /**
  12009. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12010. */
  12011. public function export_month_quote()
  12012. {
  12013. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12014. $this->error(__('You have no permission'));
  12015. }
  12016. $bundle = $this->prepareMonthOutwardExportBundle();
  12017. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12018. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12019. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12020. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12021. $spreadsheet = new Spreadsheet();
  12022. $sheet = $spreadsheet->getActiveSheet();
  12023. $sheet->setTitle('供应商报价明细');
  12024. $mon = (int)substr($ym, 5, 2);
  12025. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12026. $sheet->getColumnDimension('A')->setWidth(7);
  12027. $sheet->getColumnDimension('B')->setWidth(16);
  12028. $sheet->getColumnDimension('C')->setWidth(52);
  12029. $sheet->getColumnDimension('D')->setWidth(26);
  12030. $sheet->getColumnDimension('E')->setWidth(32);
  12031. $sheet->getColumnDimension('F')->setWidth(12);
  12032. $sheet->getColumnDimension('G')->setWidth(14);
  12033. $sheet->getColumnDimension('H')->setWidth(12);
  12034. if ($quoteLastRow < 1) {
  12035. $quoteLastRow = 3;
  12036. }
  12037. $ymCompact = str_replace('-', '', $ym);
  12038. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12039. if (ob_get_length()) {
  12040. ob_end_clean();
  12041. }
  12042. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12043. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12044. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12045. header('Cache-Control: max-age=0');
  12046. $writer = new Xlsx($spreadsheet);
  12047. $writer->save('php://output');
  12048. $spreadsheet->disconnectWorksheets();
  12049. unset($spreadsheet);
  12050. exit;
  12051. }
  12052. /**
  12053. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12054. *
  12055. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12056. */
  12057. protected function prepareMonthOutwardExportBundle(): array
  12058. {
  12059. $this->request->filter(['strip_tags', 'trim']);
  12060. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12061. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12062. $ym = date('Y-m');
  12063. }
  12064. $dbRows = [];
  12065. try {
  12066. $query = Db::table('purchase_order');
  12067. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12068. $dbRows = $query->select();
  12069. } catch (\Throwable $e) {
  12070. $dbRows = [];
  12071. }
  12072. if (!is_array($dbRows)) {
  12073. $dbRows = [];
  12074. }
  12075. $completeTsMap = [];
  12076. $sidList = [];
  12077. foreach ($dbRows as $dbRow) {
  12078. if (!is_array($dbRow)) {
  12079. continue;
  12080. }
  12081. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12082. if ($sid > 0) {
  12083. $sidList[$sid] = true;
  12084. }
  12085. }
  12086. if ($sidList !== []) {
  12087. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12088. }
  12089. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12090. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12091. if (!is_array($dbRow)) {
  12092. return false;
  12093. }
  12094. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12095. if ($done['ts'] <= 0) {
  12096. return false;
  12097. }
  12098. return date('Y-m', $done['ts']) === $ym;
  12099. }));
  12100. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12101. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12102. $mainBySid = [];
  12103. foreach ($pool as $rw) {
  12104. if (!is_array($rw)) {
  12105. continue;
  12106. }
  12107. $rid = (int)($rw['ID'] ?? 0);
  12108. if ($rid > 0) {
  12109. $mainBySid[$rid] = $rw;
  12110. }
  12111. }
  12112. if ($mainBySid === []) {
  12113. $detailRows = [];
  12114. } else {
  12115. try {
  12116. $detailRows = Db::table('purchase_order_detail')
  12117. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12118. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12119. ->order('status', 'desc')
  12120. ->order('CCYDH', 'asc')
  12121. ->order('company_name', 'asc')
  12122. ->order('id', 'asc')
  12123. ->select();
  12124. } catch (\Throwable $e) {
  12125. try {
  12126. $detailRows = Db::table('purchase_order_detail')
  12127. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12128. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12129. ->order('status', 'desc')
  12130. ->order('CCYDH', 'asc')
  12131. ->order('company_name', 'asc')
  12132. ->order('ID', 'asc')
  12133. ->select();
  12134. } catch (\Throwable $e2) {
  12135. $detailRows = [];
  12136. }
  12137. }
  12138. }
  12139. if (!is_array($detailRows)) {
  12140. $detailRows = [];
  12141. }
  12142. $exportLines = [];
  12143. $detailSidSeen = [];
  12144. foreach ($detailRows as $dr) {
  12145. if (!is_array($dr)) {
  12146. continue;
  12147. }
  12148. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12149. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12150. continue;
  12151. }
  12152. if (isset($detailSidSeen[$sid])) {
  12153. continue;
  12154. }
  12155. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12156. continue;
  12157. }
  12158. $detailSidSeen[$sid] = true;
  12159. $m = $mainBySid[$sid];
  12160. $exportLines[] = [
  12161. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12162. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12163. 'company_name' => (string)($dr['company_name'] ?? ''),
  12164. 'CDF' => (string)($m['CDF'] ?? ''),
  12165. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12166. 'gx' => $this->procuremenExportGxText($m),
  12167. 'detail' => $dr,
  12168. ];
  12169. }
  12170. foreach ($detailRows as $dr) {
  12171. if (!is_array($dr)) {
  12172. continue;
  12173. }
  12174. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12175. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12176. continue;
  12177. }
  12178. $detailSidSeen[$sid] = true;
  12179. $m = $mainBySid[$sid];
  12180. $exportLines[] = [
  12181. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12182. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12183. 'company_name' => (string)($dr['company_name'] ?? ''),
  12184. 'CDF' => (string)($m['CDF'] ?? ''),
  12185. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12186. 'gx' => $this->procuremenExportGxText($m),
  12187. 'detail' => $dr,
  12188. ];
  12189. }
  12190. foreach ($mainBySid as $sid => $m) {
  12191. if (isset($detailSidSeen[$sid])) {
  12192. continue;
  12193. }
  12194. $company = trim((string)($m['pick_company_name'] ?? ''));
  12195. $exportLines[] = [
  12196. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12197. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12198. 'company_name' => $company,
  12199. 'CDF' => (string)($m['CDF'] ?? ''),
  12200. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12201. 'gx' => $this->procuremenExportGxText($m),
  12202. 'detail' => [],
  12203. ];
  12204. }
  12205. $groups = [];
  12206. foreach ($exportLines as $line) {
  12207. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12208. if (!isset($groups[$k])) {
  12209. $groups[$k] = [];
  12210. }
  12211. $groups[$k][] = $line;
  12212. }
  12213. ksort($groups, SORT_STRING);
  12214. return [
  12215. 'ym' => $ym,
  12216. 'mainBySid' => $mainBySid,
  12217. 'detailRows' => $detailRows,
  12218. 'exportLines' => $exportLines,
  12219. 'groups' => $groups,
  12220. ];
  12221. }
  12222. /**
  12223. * 导出用:工序列文案
  12224. */
  12225. protected function procuremenExportGxText(array $r)
  12226. {
  12227. $a = trim((string)($r['CDXMC'] ?? ''));
  12228. $b = trim((string)($r['CGYMC'] ?? ''));
  12229. if ($a !== '' && $b !== '') {
  12230. return $a . ':' . $b;
  12231. }
  12232. return $a !== '' ? $a : $b;
  12233. }
  12234. /**
  12235. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12236. */
  12237. protected function procuremenExportAmount(array $r)
  12238. {
  12239. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12240. if (!array_key_exists($k, $r)) {
  12241. continue;
  12242. }
  12243. $v = $r[$k];
  12244. if ($v === null || $v === '') {
  12245. continue;
  12246. }
  12247. if (is_numeric($v)) {
  12248. return (float)$v;
  12249. }
  12250. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12251. if ($v !== '' && is_numeric($v)) {
  12252. return (float)$v;
  12253. }
  12254. }
  12255. return 0.0;
  12256. }
  12257. /**
  12258. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12259. *
  12260. * @param array<int, array<string, mixed>> $detailRows
  12261. * @param array<int, array<string, mixed>> $mainBySid
  12262. * @return array<int, array<string, mixed>>
  12263. */
  12264. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12265. {
  12266. $lines = [];
  12267. foreach ($detailRows as $dr) {
  12268. if (!is_array($dr)) {
  12269. continue;
  12270. }
  12271. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12272. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12273. continue;
  12274. }
  12275. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12276. continue;
  12277. }
  12278. $cn = trim((string)($dr['company_name'] ?? ''));
  12279. if ($cn === '') {
  12280. continue;
  12281. }
  12282. $m = $mainBySid[$sid];
  12283. $am = trim((string)($dr['amount'] ?? ''));
  12284. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12285. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12286. $amountText = $amountFilled
  12287. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12288. : '未填写';
  12289. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12290. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12291. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12292. $deliveryShow = $deliveryRaw;
  12293. }
  12294. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12295. ? $deliveryShow
  12296. : '未填写';
  12297. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12298. $lines[] = [
  12299. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12300. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12301. 'gx' => $this->procuremenExportGxText($m),
  12302. 'company_name' => $cn,
  12303. 'amount_text' => $amountText,
  12304. 'amount_num' => $amountFilled ? $amountNum : null,
  12305. 'delivery_text' => $deliveryText,
  12306. 'picked_text' => $picked ? '中标' : '未中标',
  12307. 'picked' => $picked,
  12308. ];
  12309. }
  12310. $winnerSupplierByOrder = [];
  12311. foreach ($lines as $line) {
  12312. $dh = trim((string)($line['CCYDH'] ?? ''));
  12313. $cn = trim((string)($line['company_name'] ?? ''));
  12314. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12315. $winnerSupplierByOrder[$dh][$cn] = true;
  12316. }
  12317. }
  12318. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12319. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12320. if ($c !== 0) {
  12321. return $c;
  12322. }
  12323. $dh = trim((string)($a['CCYDH'] ?? ''));
  12324. $aCn = trim((string)($a['company_name'] ?? ''));
  12325. $bCn = trim((string)($b['company_name'] ?? ''));
  12326. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12327. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12328. if ($aSupplierWin !== $bSupplierWin) {
  12329. return $aSupplierWin ? -1 : 1;
  12330. }
  12331. $c = strcmp($aCn, $bCn);
  12332. if ($c !== 0) {
  12333. return $c;
  12334. }
  12335. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12336. return !empty($a['picked']) ? -1 : 1;
  12337. }
  12338. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12339. if ($c !== 0) {
  12340. return $c;
  12341. }
  12342. return 0;
  12343. });
  12344. return $lines;
  12345. }
  12346. /**
  12347. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12348. *
  12349. * @param array<int, array<string, mixed>> $quoteLines
  12350. */
  12351. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12352. {
  12353. $mon = (int)substr($ym, 5, 2);
  12354. $titleRow = $startRow;
  12355. $headerRow = $startRow + 1;
  12356. $dataStartRow = $startRow + 2;
  12357. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12358. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12359. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12360. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12361. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12362. ->setVertical(Alignment::VERTICAL_CENTER);
  12363. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12364. $col = 'A';
  12365. foreach ($headers as $h) {
  12366. $sheet->setCellValue($col . $headerRow, $h);
  12367. $col++;
  12368. }
  12369. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12370. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12371. $rowNum = $dataStartRow;
  12372. if ($quoteLines === []) {
  12373. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12374. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12375. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12376. $rowNum = $dataStartRow + 1;
  12377. } else {
  12378. $i = 0;
  12379. foreach ($quoteLines as $line) {
  12380. $i++;
  12381. $sheet->setCellValue('A' . $rowNum, $i);
  12382. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12383. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12384. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12385. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12386. if ($line['amount_num'] !== null) {
  12387. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12388. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12389. } else {
  12390. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12391. }
  12392. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12393. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12394. if (!empty($line['picked'])) {
  12395. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12396. }
  12397. $rowNum++;
  12398. }
  12399. }
  12400. $lastRow = $rowNum - 1;
  12401. if ($lastRow >= $headerRow) {
  12402. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12403. 'borders' => [
  12404. 'allBorders' => [
  12405. 'borderStyle' => Border::BORDER_THIN,
  12406. 'color' => ['rgb' => '000000'],
  12407. ],
  12408. ],
  12409. ]);
  12410. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12411. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12412. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12413. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12414. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12415. if ($lastRow >= $dataStartRow) {
  12416. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12417. }
  12418. }
  12419. return $lastRow;
  12420. }
  12421. /**
  12422. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12423. */
  12424. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12425. {
  12426. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12427. return;
  12428. }
  12429. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12430. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12431. ->setVertical(Alignment::VERTICAL_CENTER);
  12432. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12433. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12434. ->setVertical(Alignment::VERTICAL_CENTER);
  12435. if ($lastCol > 'B') {
  12436. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12437. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12438. ->setVertical(Alignment::VERTICAL_CENTER);
  12439. }
  12440. }
  12441. /**
  12442. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12443. */
  12444. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12445. {
  12446. $s = trim($ccydh);
  12447. if ($s === '') {
  12448. return 'ORDER';
  12449. }
  12450. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12451. $s = trim($s, '._-');
  12452. if ($s === '') {
  12453. return 'ORDER';
  12454. }
  12455. if (function_exists('mb_substr')) {
  12456. return mb_substr($s, 0, 80, 'UTF-8');
  12457. }
  12458. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12459. }
  12460. /**
  12461. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12462. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12463. *
  12464. * @return array{objectKey: string, webPath: string}
  12465. */
  12466. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12467. {
  12468. $sid = (int)$scydgyId;
  12469. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12470. $y = date('Y');
  12471. $m = date('m');
  12472. $d = date('d');
  12473. $basename = $safeOrder . '_' . $sid . '.pdf';
  12474. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12475. return [
  12476. 'objectKey' => $objectKey,
  12477. 'webPath' => '/' . $objectKey,
  12478. ];
  12479. }
  12480. /**
  12481. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12482. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12483. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12484. *
  12485. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12486. */
  12487. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12488. {
  12489. if (!$this->isValidScydgyRowId($scydgyId)) {
  12490. return '';
  12491. }
  12492. $ids = trim((string)$scydgyId);
  12493. $prep = $this->prepareProcuremenDetailsView($ids);
  12494. if (!$prep['ok']) {
  12495. return '';
  12496. }
  12497. $ccydh = $prep['ccydh'];
  12498. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12499. $objectKey = $paths['objectKey'];
  12500. $webPath = $paths['webPath'];
  12501. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12502. $this->view->assign([
  12503. 'pdf_export' => 1,
  12504. 'pdfMetaLine' => $meta,
  12505. ]);
  12506. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12507. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12508. $this->view->engine->layout(false);
  12509. try {
  12510. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12511. } catch (\Throwable $e) {
  12512. if ($restoreLayout) {
  12513. $this->view->engine->layout($restoreLayout);
  12514. }
  12515. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12516. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12517. return '';
  12518. }
  12519. if ($restoreLayout) {
  12520. $this->view->engine->layout($restoreLayout);
  12521. }
  12522. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12523. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12524. if (!is_dir($tempDir)) {
  12525. @mkdir($tempDir, 0755, true);
  12526. }
  12527. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12528. try {
  12529. $mpdf = new \Mpdf\Mpdf([
  12530. 'mode' => 'utf-8',
  12531. 'format' => 'A4',
  12532. 'margin_left' => 12,
  12533. 'margin_right' => 12,
  12534. 'margin_top' => 14,
  12535. 'margin_bottom' => 14,
  12536. 'tempDir' => $tempDir,
  12537. 'autoScriptToLang' => true,
  12538. 'autoLangToFont' => true,
  12539. ]);
  12540. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12541. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12542. $mpdf->SetBasePath('http://127.0.0.1/');
  12543. $mpdf->WriteHTML($html);
  12544. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12545. } catch (\Throwable $e) {
  12546. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12547. if (is_file($tempPdf)) {
  12548. @unlink($tempPdf);
  12549. }
  12550. return '';
  12551. }
  12552. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12553. if ($ossUrl !== '') {
  12554. @unlink($tempPdf);
  12555. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12556. return $ossUrl;
  12557. }
  12558. $pi = pathinfo($objectKey);
  12559. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12560. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12561. if ($baseFile === '') {
  12562. @unlink($tempPdf);
  12563. return '';
  12564. }
  12565. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12566. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12567. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12568. @unlink($tempPdf);
  12569. return '';
  12570. }
  12571. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12572. if (!@copy($tempPdf, $fullPath)) {
  12573. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12574. @unlink($tempPdf);
  12575. return '';
  12576. }
  12577. @unlink($tempPdf);
  12578. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12579. return $webPath;
  12580. }
  12581. /**
  12582. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12583. */
  12584. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12585. {
  12586. if ($scydgyId <= 0 || $webPath === '') {
  12587. return;
  12588. }
  12589. try {
  12590. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12591. } catch (\Throwable $e) {
  12592. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12593. }
  12594. }
  12595. /**
  12596. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12597. *
  12598. * @param array<string, string> $vars
  12599. * @return array<string, string>
  12600. */
  12601. protected function normalizeSmsTemplateVars(array $vars): array
  12602. {
  12603. $out = [];
  12604. foreach ($vars as $k => $v) {
  12605. $out[(string)$k] = trim((string)$v);
  12606. }
  12607. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12608. $out['contact_name'] = $out['company_name'];
  12609. }
  12610. return $out;
  12611. }
  12612. /**
  12613. * 按手机号或公司名称查 customer 表联系人姓名
  12614. */
  12615. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12616. {
  12617. $phone = trim($phone);
  12618. $companyName = trim($companyName);
  12619. try {
  12620. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12621. $row = Db::table('customer')
  12622. ->where(function ($q) use ($phone) {
  12623. $q->where('phone', $phone)->whereOr('account', $phone);
  12624. })
  12625. ->order('id', 'asc')
  12626. ->find();
  12627. if (is_array($row)) {
  12628. $nm = trim((string)($row['username'] ?? ''));
  12629. if ($nm !== '') {
  12630. return $nm;
  12631. }
  12632. }
  12633. }
  12634. if ($companyName !== '') {
  12635. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12636. if (is_array($row)) {
  12637. return trim((string)($row['username'] ?? ''));
  12638. }
  12639. }
  12640. } catch (\Throwable $e) {
  12641. }
  12642. return '';
  12643. }
  12644. /**
  12645. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  12646. */
  12647. protected function plainTextToHtmlEmailBody(string $text): string
  12648. {
  12649. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12650. $parts = explode("\n", $text);
  12651. $out = [];
  12652. foreach ($parts as $line) {
  12653. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12654. $out[] = $line;
  12655. } else {
  12656. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12657. $esc = preg_replace(
  12658. '#(https?://[^\s<>"\']+)#iu',
  12659. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  12660. $esc
  12661. );
  12662. $out[] = $esc;
  12663. }
  12664. }
  12665. return implode("<br>\n", $out);
  12666. }
  12667. /**
  12668. * 邮件末尾追加「点击进入平台」按钮(微信内打开邮件更易点)
  12669. */
  12670. protected function appendPlatformTapLinkToEmailHtml(string $mailBody, string $platformUrl): string
  12671. {
  12672. $platformUrl = trim($platformUrl);
  12673. if ($platformUrl === '' || !preg_match('#^https?://#i', $platformUrl)) {
  12674. return $mailBody;
  12675. }
  12676. $esc = htmlspecialchars($platformUrl, ENT_QUOTES, 'UTF-8');
  12677. // 已有同 href 的按钮文案则不重复追加
  12678. if (strpos($mailBody, '点击进入平台处理') !== false) {
  12679. return $mailBody;
  12680. }
  12681. $mailBody .= '<br><br>'
  12682. . '<p style="margin:16px 0 8px 0;">'
  12683. . '<a href="' . $esc . '" style="display:inline-block;padding:10px 18px;background:#1a73e8;color:#ffffff;text-decoration:none;border-radius:4px;font-size:15px;">点击进入平台处理</a>'
  12684. . '</p>'
  12685. . '<p style="margin:0;font-size:12px;color:#888888;word-break:break-all;line-height:1.5;">若按钮无法打开,请复制到浏览器访问:<br>' . $esc . '</p>';
  12686. return $mailBody;
  12687. }
  12688. /**
  12689. * 短信场景:去掉链接类变量,避免误填 URL
  12690. *
  12691. * @param array<string, string> $vars
  12692. * @return array<string, string>
  12693. */
  12694. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12695. {
  12696. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12697. return $vars;
  12698. }
  12699. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12700. $vars[$k] = '';
  12701. }
  12702. return $vars;
  12703. }
  12704. /**
  12705. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12706. *
  12707. * @param array<string, string> $vars
  12708. */
  12709. protected function renderNotifyTemplate(string $scene, array $vars): string
  12710. {
  12711. $vars = $this->normalizeSmsTemplateVars($vars);
  12712. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12713. $row = $this->loadNotifyTemplateRow($scene);
  12714. if ($row === null) {
  12715. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12716. }
  12717. $tpl = trim((string)($row['content'] ?? ''));
  12718. if ($tpl === '') {
  12719. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12720. }
  12721. foreach ($vars as $k => $v) {
  12722. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12723. }
  12724. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12725. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12726. return $tpl;
  12727. }
  12728. protected function resolveProcuremenEmailSubject(string $scene): string
  12729. {
  12730. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  12731. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  12732. $row = $this->loadNotifyTemplateRow($scene);
  12733. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12734. if ($title !== '') {
  12735. return $title;
  12736. }
  12737. $fallback = [
  12738. 'rfq_supplier_email' => '供应商询价通知',
  12739. 'rfq_salesman_email' => '协助采购询价通知',
  12740. 'confirm_ok_email' => '采购确认结果:已通过',
  12741. 'confirm_fail_email' => '采购确认结果:未通过',
  12742. ];
  12743. return $fallback[$scene] ?? '协助采购通知';
  12744. }
  12745. $map = [
  12746. 'review_email' => '您有新的协助加工订单',
  12747. ];
  12748. $subject = trim((string)($map[$scene] ?? ''));
  12749. if ($subject === '') {
  12750. $this->error('未配置邮件主题:' . $scene);
  12751. }
  12752. return $subject;
  12753. }
  12754. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12755. {
  12756. $map = [
  12757. 'review_email' => '协助下发-邮箱',
  12758. 'review_sms' => '协助下发-短信',
  12759. 'confirm_ok' => '采购确认-通过',
  12760. 'confirm_fail' => '采购确认-未通过',
  12761. 'confirm_ok_email' => '采购确认通过-邮箱',
  12762. 'confirm_fail_email' => '采购确认未通过-邮箱',
  12763. 'bid_open' => '开标双重验证',
  12764. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12765. 'rfq_supplier_email' => '供应商询价通知',
  12766. ];
  12767. $label = $map[$scene] ?? $scene;
  12768. if ($titleRequired) {
  12769. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12770. }
  12771. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12772. }
  12773. /**
  12774. * 是否开启协助通知演练(不发真实短信/邮件)
  12775. */
  12776. protected function isProcuremenNotifyDryRun(): bool
  12777. {
  12778. return (bool)Config::get('procuremen_notify_dry_run');
  12779. }
  12780. /**
  12781. * @param array<string, mixed> $payload
  12782. */
  12783. protected function recordNotifyDryRunPreview(array $payload): void
  12784. {
  12785. $this->notifyDryRunPreview[] = $payload;
  12786. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12787. }
  12788. /**
  12789. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12790. * @throws \Exception
  12791. */
  12792. protected function smsbao($phone, $content)
  12793. {
  12794. if ($this->isProcuremenNotifyDryRun()) {
  12795. $this->recordNotifyDryRunPreview([
  12796. 'scene' => 'sms_only',
  12797. 'phone' => $phone,
  12798. 'sms_content' => $content,
  12799. ]);
  12800. return;
  12801. }
  12802. $statusStr = [
  12803. '0' => '短信发送成功',
  12804. '-1' => '参数不全',
  12805. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12806. '30' => '密码错误',
  12807. '40' => '账号不存在',
  12808. '41' => '余额不足',
  12809. '42' => '帐户已过期',
  12810. '43' => 'IP地址限制',
  12811. '50' => '内容含有敏感词',
  12812. ];
  12813. $smsapi = 'http://api.smsbao.com/';
  12814. $user = 'zhuwei123';
  12815. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12816. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12817. $result = @file_get_contents($sendurl);
  12818. if ($result === false) {
  12819. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12820. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12821. }
  12822. $result = trim((string)$result);
  12823. if ($result !== '0') {
  12824. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12825. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12826. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12827. }
  12828. }
  12829. }