Procuremen.php 368 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenSupplierScore;
  9. use app\common\library\ProcuremenTime;
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use think\Config;
  12. use think\Cache;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use think\Db;
  19. use think\Log;
  20. class Procuremen extends Backend
  21. {
  22. /**
  23. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  24. */
  25. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  26. /**
  27. * Procuremen模型对象
  28. * @var \app\admin\model\Procuremen
  29. */
  30. protected $model = null;
  31. /**
  32. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  33. */
  34. protected $notifyDryRunPreview = [];
  35. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  36. protected $procuremenRedisCache = null;
  37. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  38. protected $pickHiddenScydgySetCache = null;
  39. /** 邮件发送日志表结构已就绪缓存键 */
  40. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  41. /**
  42. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  43. * @var array
  44. */
  45. protected $noNeedRight = [
  46. 'pickreview', 'review', 'reviewcompanies',
  47. ];
  48. public function _initialize()
  49. {
  50. parent::_initialize();
  51. $this->model = new \app\admin\model\Procuremen;
  52. $this->maybeMigrateLegacyWflowStatusText();
  53. $this->assignProcuremenAuthConfig();
  54. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  55. $this->ensurePurchaseEmailSendLogTableOnce();
  56. }
  57. }
  58. /**
  59. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  60. */
  61. protected function maybeMigrateLegacyWflowStatusText(): void
  62. {
  63. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  64. if (is_file($flagFile)) {
  65. return;
  66. }
  67. $map = [
  68. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  69. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  70. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  71. '3' => ProcuremenStatus::WFLOW_APPROVED,
  72. ];
  73. try {
  74. foreach ($map as $num => $text) {
  75. Db::table('purchase_order')
  76. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  77. ->update(['wflow_status' => $text]);
  78. }
  79. @file_put_contents($flagFile, date('c'));
  80. } catch (\Throwable $e) {
  81. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  82. }
  83. }
  84. /**
  85. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  86. *
  87. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  88. */
  89. protected function hasProcuremenPerm(array $actions): bool
  90. {
  91. foreach ($actions as $action) {
  92. $action = strtolower(trim((string)$action));
  93. if ($action === '') {
  94. continue;
  95. }
  96. if (strpos($action, 'procuremen/') !== 0) {
  97. $action = 'procuremen/' . $action;
  98. }
  99. if ($this->auth->check($action)) {
  100. return true;
  101. }
  102. }
  103. $suffixes = [];
  104. foreach ($actions as $action) {
  105. $action = strtolower(trim((string)$action));
  106. $action = preg_replace('#^procuremen/#', '', $action);
  107. if ($action !== '') {
  108. $suffixes[$action] = true;
  109. }
  110. }
  111. if ($suffixes === []) {
  112. return false;
  113. }
  114. try {
  115. foreach ($this->auth->getRuleList() as $rule) {
  116. $rule = strtolower((string)$rule);
  117. if (strpos($rule, 'procuremen/') !== 0) {
  118. continue;
  119. }
  120. foreach (array_keys($suffixes) as $suffix) {
  121. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  122. return true;
  123. }
  124. }
  125. }
  126. } catch (\Throwable $e) {
  127. }
  128. return false;
  129. }
  130. /**
  131. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  132. *
  133. * @param string[] $actions
  134. */
  135. protected function hasProcuremenPermStrict(array $actions): bool
  136. {
  137. foreach ($actions as $action) {
  138. $action = strtolower(trim((string)$action));
  139. if ($action === '') {
  140. continue;
  141. }
  142. if (strpos($action, 'procuremen/') !== 0) {
  143. $action = 'procuremen/' . $action;
  144. }
  145. if ($this->auth->check($action)) {
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. /**
  152. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  153. *
  154. * @param string[] $titles
  155. */
  156. protected function authHasAssignedRuleTitle(array $titles): bool
  157. {
  158. $titles = array_values(array_filter(array_map('trim', $titles)));
  159. if ($titles === []) {
  160. return false;
  161. }
  162. try {
  163. $ids = $this->auth->getRuleIds();
  164. if (in_array('*', $ids, true)) {
  165. return true;
  166. }
  167. if ($ids === []) {
  168. return false;
  169. }
  170. $rows = Db::name('auth_rule')
  171. ->where('status', 'normal')
  172. ->whereIn('id', $ids)
  173. ->column('title');
  174. foreach ($rows as $title) {
  175. $t = trim((string)$title);
  176. if ($t !== '' && in_array($t, $titles, true)) {
  177. return true;
  178. }
  179. }
  180. } catch (\Throwable $e) {
  181. }
  182. return false;
  183. }
  184. protected function procuremenCanPickDelete(): bool
  185. {
  186. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  187. return true;
  188. }
  189. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  190. }
  191. protected function procuremenCanComplete(): bool
  192. {
  193. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  194. return true;
  195. }
  196. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  197. }
  198. protected function procuremenCanDispatch(): bool
  199. {
  200. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  201. }
  202. /**
  203. * 前端按钮显隐(Config.procuremenAuth)
  204. */
  205. protected function assignProcuremenAuthConfig(): void
  206. {
  207. $authMap = [
  208. 'pickreview' => $this->procuremenCanDispatch(),
  209. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  210. 'pickdelete' => $this->procuremenCanPickDelete(),
  211. 'completedirectly' => $this->procuremenCanComplete(),
  212. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  213. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  214. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  215. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  216. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  217. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  218. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  219. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  220. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  221. 'details' => $this->hasProcuremenPerm(['details']),
  222. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  223. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  224. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  225. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  226. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  228. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  229. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  230. 'add' => $this->hasProcuremenPerm(['add']),
  231. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  232. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  233. ];
  234. $this->assignconfig('procuremenAuth', $authMap);
  235. }
  236. /**
  237. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  238. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  239. *
  240. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  241. */
  242. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  243. {
  244. static $mprocCfgLoaded = false;
  245. if (!$mprocCfgLoaded) {
  246. $mprocCfgLoaded = true;
  247. if (is_file(APP_PATH . 'extra/mproc.php')) {
  248. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  249. }
  250. }
  251. $eid = (int)$purchaseOrderDetailId;
  252. $base = $this->resolveMprocMobilePublicBaseUrl();
  253. if ($base === '') {
  254. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  255. }
  256. $path = trim((string)Config::get('mproc.mobile_index_path'));
  257. if ($path === '') {
  258. $path = '/index.php/index/index/index';
  259. } else {
  260. $path = '/' . ltrim($path, '/');
  261. }
  262. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  263. if ($eid > 0) {
  264. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  265. }
  266. return $base . $path . '?main_tab=orders';
  267. }
  268. /**
  269. * 邮件/短信外链:须为带点的公网域名
  270. */
  271. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  272. {
  273. $u = trim((string)$baseUrl);
  274. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  275. return false;
  276. }
  277. $host = parse_url($u, PHP_URL_HOST);
  278. if (!is_string($host) || $host === '') {
  279. return false;
  280. }
  281. if (strcasecmp($host, 'localhost') === 0) {
  282. return false;
  283. }
  284. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  285. return false;
  286. }
  287. if (strpos($host, '.') === false) {
  288. return false;
  289. }
  290. return true;
  291. }
  292. /**
  293. * 解析用于协助邮件/短信的手机端站点根
  294. */
  295. protected function resolveMprocMobilePublicBaseUrl()
  296. {
  297. $candidates = [];
  298. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  299. $candidates[] = trim((string)Config::get('site.indexurl'));
  300. $cdn = trim((string)Config::get('site.cdnurl'));
  301. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  302. $candidates[] = rtrim($cdn, '/');
  303. }
  304. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  305. $candidates[] = $reqBase;
  306. foreach ($candidates as $c) {
  307. if ($c === '') {
  308. continue;
  309. }
  310. $c = rtrim($c, '/');
  311. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  312. return $c;
  313. }
  314. }
  315. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  316. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  317. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  318. return $reqBase;
  319. }
  320. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  321. return '';
  322. }
  323. /**
  324. * 获取 Redis 中 procuremen_redis
  325. */
  326. protected function ProcuremenRedis(): array
  327. {
  328. if ($this->procuremenRedisCache !== null) {
  329. return $this->procuremenRedisCache;
  330. }
  331. try {
  332. $redis = redis();
  333. $raw = $redis->get('procuremen_redis');
  334. if ($raw === false || $raw === '') {
  335. $this->procuremenRedisCache = [];
  336. return $this->procuremenRedisCache;
  337. }
  338. $decoded = json_decode($raw, true);
  339. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  340. $this->procuremenRedisCache = [];
  341. return $this->procuremenRedisCache;
  342. }
  343. $this->procuremenRedisCache = $decoded['data'];
  344. return $this->procuremenRedisCache;
  345. } catch (\Throwable $e) {
  346. $this->procuremenRedisCache = [];
  347. return $this->procuremenRedisCache;
  348. }
  349. }
  350. /**
  351. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  352. *
  353. * @return array<int, array<string, mixed>>
  354. */
  355. protected function procuremenFetchErpPoolFromDb(): array
  356. {
  357. try {
  358. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  359. $endTime = date('Y-m-d 23:59:59');
  360. $list = Db::table('scydgy')
  361. ->alias('a')
  362. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  363. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  364. ->where([
  365. 'a.bwjg' => 1,
  366. 'a.iEndBz' => 0,
  367. 'a.iType' => 0,
  368. 'a.iStatus' => 10,
  369. ])
  370. ->where('a.dStamp', '>=', $startTime)
  371. ->where('a.dStamp', '<=', $endTime)
  372. ->order('a.dStamp', 'desc')
  373. ->select();
  374. if (!is_array($list)) {
  375. return [];
  376. }
  377. try {
  378. $redis = redis();
  379. $payload = [
  380. 'code' => 200,
  381. 'msg' => 'success',
  382. 'data' => $list,
  383. ];
  384. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  385. $this->procuremenRedisCache = $list;
  386. } catch (\Throwable $e) {
  387. }
  388. return $list;
  389. } catch (\Throwable $e) {
  390. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  391. return [];
  392. }
  393. }
  394. /**
  395. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  396. *
  397. * @return array<int, array<string, mixed>>
  398. */
  399. protected function procuremenEnsureRedisPool(): array
  400. {
  401. $pool = $this->ProcuremenRedis();
  402. if (is_array($pool) && $pool !== []) {
  403. return $pool;
  404. }
  405. static $warmed = false;
  406. if ($warmed) {
  407. return is_array($pool) ? $pool : [];
  408. }
  409. $warmed = true;
  410. return $this->procuremenFetchErpPoolFromDb();
  411. }
  412. /**
  413. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  414. *
  415. * @param array<string, mixed> $row
  416. */
  417. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  418. {
  419. $t = $this->procuremenRowListSortTime($row, $primary);
  420. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  421. return null;
  422. }
  423. $mo = (int)$m[2];
  424. if ($mo < 1 || $mo > 12) {
  425. return null;
  426. }
  427. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  428. }
  429. /**
  430. * @param array<int, array{year:string, months:array}> $sidebar
  431. * @return array<int, array{year:string, months:array}>
  432. */
  433. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  434. {
  435. $ym = trim($ym);
  436. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  437. return $sidebar;
  438. }
  439. foreach ($sidebar as $block) {
  440. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  441. continue;
  442. }
  443. foreach ($block['months'] as $item) {
  444. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  445. return $sidebar;
  446. }
  447. }
  448. }
  449. $y = substr($ym, 0, 4);
  450. $mo = (int)substr($ym, 5, 2);
  451. $sidebar[] = [
  452. 'year' => $y,
  453. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  454. ];
  455. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  456. }
  457. /**
  458. * @param array<int, array{year:string, months:array}> $sidebar
  459. * @return string[]
  460. */
  461. protected function flattenProcuremenSidebarYms(array $sidebar): array
  462. {
  463. $yms = [];
  464. foreach ($sidebar as $block) {
  465. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  466. continue;
  467. }
  468. foreach ($block['months'] as $item) {
  469. if (!is_array($item)) {
  470. continue;
  471. }
  472. $ym = trim((string)($item['ym'] ?? ''));
  473. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  474. $yms[$ym] = true;
  475. }
  476. }
  477. }
  478. return array_keys($yms);
  479. }
  480. /**
  481. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  482. */
  483. protected function GetIndexYearMonths()
  484. {
  485. $ymSet = [];
  486. $pool = $this->procuremenEnsureRedisPool();
  487. foreach ($pool as $r) {
  488. if (!is_array($r)) {
  489. continue;
  490. }
  491. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  492. if ($ym !== null) {
  493. $ymSet[$ym] = true;
  494. }
  495. }
  496. foreach ($this->loadPickManualOrderRows() as $r) {
  497. if (!is_array($r)) {
  498. continue;
  499. }
  500. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  501. if ($ym !== null) {
  502. $ymSet[$ym] = true;
  503. }
  504. }
  505. $ymList = array_keys($ymSet);
  506. if ($ymList === []) {
  507. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  508. }
  509. return $this->buildYearMonthSidebar($ymList);
  510. }
  511. /**
  512. * @param string[] $ymList 形如 2026-06
  513. * @return array<int, array{year:string, months:array}>
  514. */
  515. protected function buildYearMonthSidebar(array $ymList): array
  516. {
  517. rsort($ymList, SORT_STRING);
  518. $byYear = [];
  519. foreach ($ymList as $ym) {
  520. $y = substr($ym, 0, 4);
  521. $mo = (int)substr($ym, 5, 2);
  522. if (!isset($byYear[$y])) {
  523. $byYear[$y] = [];
  524. }
  525. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  526. }
  527. krsort($byYear, SORT_NUMERIC);
  528. foreach ($byYear as $y => $items) {
  529. usort($byYear[$y], function ($a, $b) {
  530. return strcmp($b['ym'], $a['ym']);
  531. });
  532. }
  533. $sidebar = [];
  534. foreach ($byYear as $y => $months) {
  535. $sidebar[] = ['year' => $y, 'months' => $months];
  536. }
  537. return $sidebar;
  538. }
  539. /**
  540. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  541. */
  542. protected function GetIssuedOrderYearMonths(string $stage): array
  543. {
  544. $ymSet = [];
  545. try {
  546. $query = Db::table('purchase_order');
  547. $this->applyPurchaseOrderNotDeletedWhere($query);
  548. if ($stage === 'audit') {
  549. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  550. } elseif ($stage === 'confirm') {
  551. $this->applyPurchaseOrderConfirmStageWhere($query);
  552. } else {
  553. return $this->GetIndexYearMonths();
  554. }
  555. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  556. if (is_array($rows)) {
  557. foreach ($rows as $r) {
  558. if (!is_array($r)) {
  559. continue;
  560. }
  561. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  562. if ($ym !== null) {
  563. $ymSet[$ym] = true;
  564. }
  565. }
  566. }
  567. } catch (\Throwable $e) {
  568. $ymSet = [];
  569. }
  570. $ymList = array_keys($ymSet);
  571. if ($ymList === []) {
  572. $def = $this->resolveProcuremenDefaultYm($stage);
  573. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  574. }
  575. return $this->buildYearMonthSidebar($ymList);
  576. }
  577. /**
  578. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  579. */
  580. protected function resolveProcuremenDefaultYm(string $stage): string
  581. {
  582. if ($stage === 'pick') {
  583. return date('Y-m');
  584. }
  585. try {
  586. $query = Db::table('purchase_order');
  587. $this->applyPurchaseOrderNotDeletedWhere($query);
  588. if ($stage === 'audit') {
  589. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  590. } elseif ($stage === 'confirm') {
  591. $this->applyPurchaseOrderConfirmStageWhere($query);
  592. } else {
  593. return date('Y-m');
  594. }
  595. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  596. if ($latest === null || $latest === '') {
  597. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  598. }
  599. $t = $this->formatProcuremenDetailTime($latest);
  600. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  601. return $m[1] . '-' . $m[2];
  602. }
  603. } catch (\Throwable $e) {
  604. }
  605. return date('Y-m');
  606. }
  607. protected function applyPurchaseOrderNotDeletedWhere($query): void
  608. {
  609. $query->whereRaw(
  610. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  611. );
  612. }
  613. /**
  614. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  615. */
  616. protected function applyPurchaseOrderConfirmStageWhere($query): void
  617. {
  618. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  619. $quoted = [];
  620. foreach ($vals as $v) {
  621. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  622. }
  623. if ($quoted === []) {
  624. $query->whereRaw('1 = 0');
  625. return;
  626. }
  627. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  628. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  629. }
  630. /**
  631. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  632. *
  633. * @param array<string, mixed> $row
  634. * @return array<string, mixed>
  635. */
  636. protected function normalizePurchaseOrderListTimeRow(array $row): array
  637. {
  638. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  639. $pick = trim((string)($row['pick_time'] ?? ''));
  640. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  641. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  642. $t = trim((string)($row[$key] ?? ''));
  643. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  644. $row['pick_time'] = $t;
  645. break;
  646. }
  647. }
  648. }
  649. return $row;
  650. }
  651. /**
  652. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  653. */
  654. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  655. {
  656. if (!in_array($stage, ['audit', 'confirm'], true)) {
  657. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  658. }
  659. if ($pool === []) {
  660. $def = $this->resolveProcuremenDefaultYm($stage);
  661. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  662. }
  663. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  664. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  665. return false;
  666. }
  667. $monthStart = $ym . '-01 00:00:00';
  668. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  669. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  670. return $probe !== [];
  671. };
  672. if ($tryYm($requestedYm)) {
  673. return $requestedYm;
  674. }
  675. $fallback = $this->resolveProcuremenDefaultYm($stage);
  676. if ($tryYm($fallback)) {
  677. return $fallback;
  678. }
  679. $bestYm = '';
  680. $bestTime = '';
  681. foreach ($pool as $row) {
  682. if (!is_array($row)) {
  683. continue;
  684. }
  685. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  686. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  687. continue;
  688. }
  689. $ymRow = $m[1];
  690. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  691. $bestTime = $t;
  692. $bestYm = $ymRow;
  693. }
  694. }
  695. if ($bestYm !== '') {
  696. return $bestYm;
  697. }
  698. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  699. }
  700. protected function isPurchaseOrderDetailVoid(array $row): bool
  701. {
  702. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  703. return true;
  704. }
  705. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  706. }
  707. /**
  708. * 仅当前有效下发明细(排除废弃归档)
  709. */
  710. protected function applyActivePurchaseOrderDetailWhere($query): void
  711. {
  712. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  713. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  714. }
  715. /**
  716. * @param array<string, mixed> $detailRow
  717. */
  718. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  719. {
  720. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  721. return false;
  722. }
  723. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  724. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  725. }
  726. /**
  727. * 废弃退回初选:下发明细标记归档,不物理删除
  728. *
  729. * @param array<int, int|string> $scydgyIds
  730. */
  731. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  732. {
  733. $ids = [];
  734. foreach ($scydgyIds as $sid) {
  735. $n = (int)$sid;
  736. if ($this->isValidScydgyRowId($n) || $n < 0) {
  737. $ids[$n] = true;
  738. }
  739. }
  740. if ($ids === []) {
  741. return;
  742. }
  743. $void = ProcuremenStatus::POD_VOID;
  744. Db::table('purchase_order_detail')
  745. ->where('scydgy_id', 'in', array_keys($ids))
  746. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  747. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  748. ->update([
  749. 'status' => $void,
  750. 'status_name' => $void,
  751. ]);
  752. }
  753. /**
  754. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  755. */
  756. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  757. {
  758. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  759. $norm = function (string $col) use ($p): string {
  760. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  761. };
  762. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  763. $parts = [];
  764. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  765. if ($key === 'createtime') {
  766. $parts[] = $createtime;
  767. } else {
  768. $parts[] = $norm($key);
  769. }
  770. }
  771. return 'COALESCE(' . implode(', ', $parts) . ')';
  772. }
  773. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  774. {
  775. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  776. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  777. }
  778. /**
  779. * @return array<int, array<string, mixed>>
  780. */
  781. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  782. {
  783. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  784. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  785. try {
  786. $query = Db::table('purchase_order')->field($fields);
  787. $this->applyPurchaseOrderNotDeletedWhere($query);
  788. if ($stage === 'audit') {
  789. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  790. } elseif ($stage === 'confirm') {
  791. $this->applyPurchaseOrderConfirmStageWhere($query);
  792. } else {
  793. return [];
  794. }
  795. $query->order('pick_time', 'desc')->order('id', 'desc');
  796. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  797. $monthStart = $ym . '-01 00:00:00';
  798. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  799. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  800. }
  801. $rows = $query->select();
  802. } catch (\Throwable $e) {
  803. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  804. $rows = [];
  805. }
  806. return is_array($rows) ? $rows : [];
  807. }
  808. /**
  809. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  810. */
  811. protected function resolveProcuremenListStage(): string
  812. {
  813. $tab = trim((string)$this->request->request('wff_tab', ''));
  814. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  815. return $tab;
  816. }
  817. $action = strtolower((string)$this->request->action());
  818. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  819. return $action;
  820. }
  821. return 'pick';
  822. }
  823. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  824. {
  825. $rootTrue = rtrim((string)$this->request->root(true), '/');
  826. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  827. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  828. $indexPhpRoot = $rootTrue . '/index.php';
  829. }
  830. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  831. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  832. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  833. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  834. $this->view->assign('defaultYm', $defaultYm);
  835. $this->view->assign('sidebarYearMonths', $sidebar);
  836. $this->view->assign('procuremenStage', $stage);
  837. $this->view->assign('procuremenPageTitle', $pageTitle);
  838. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  839. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  840. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  841. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  842. }
  843. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  844. public function pick()
  845. {
  846. $this->request->filter(['strip_tags', 'trim']);
  847. if (!$this->request->isAjax()) {
  848. $this->assignProcuremenListPage('pick', '协助下发');
  849. return $this->view->fetch('procuremen/index');
  850. }
  851. return $this->index();
  852. }
  853. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  854. public function audit()
  855. {
  856. $this->request->filter(['strip_tags', 'trim']);
  857. if (!$this->request->isAjax()) {
  858. $this->assignProcuremenListPage('audit', '确认供应商');
  859. return $this->view->fetch('procuremen/index');
  860. }
  861. return $this->index();
  862. }
  863. /** 采购确认(定标) */
  864. public function confirm()
  865. {
  866. $this->request->filter(['strip_tags', 'trim']);
  867. if (!$this->request->isAjax()) {
  868. $this->assignProcuremenListPage('confirm', '采购确认');
  869. return $this->view->fetch('procuremen/index');
  870. }
  871. return $this->index();
  872. }
  873. /**
  874. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  875. */
  876. public function index()
  877. {
  878. $this->request->filter(['strip_tags', 'trim']);
  879. if (!$this->request->isAjax()) {
  880. $this->assignProcuremenListPage('pick', '协助下发');
  881. return $this->view->fetch('procuremen/index');
  882. }
  883. if ($this->request->request('keyField')) {
  884. return $this->selectpage();
  885. }
  886. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  887. $limit = max(10, min(500, (int)$limit));
  888. $ym = $this->request->request('ym', '');
  889. $ym = is_string($ym) ? trim($ym) : '';
  890. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  891. $wffTab = $this->resolveProcuremenListStage();
  892. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  893. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  894. ? $this->resolveProcuremenDefaultYm($wffTab)
  895. : date('Y-m');
  896. }
  897. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  898. $ym = date('Y-m');
  899. }
  900. $monthStart = $ym . '-01 00:00:00';
  901. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  902. $search = trim((string)$this->request->get('search', ''));
  903. $hasActiveSearch = ($search !== '');
  904. if (!$hasActiveSearch) {
  905. $filterStr = $this->request->get('filter', '');
  906. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  907. $arr = json_decode($filterStr, true);
  908. if (is_array($arr) && count($arr) > 0) {
  909. foreach ($arr as $v) {
  910. if (is_array($v)) {
  911. if (array_filter($v, function ($x) {
  912. return $x !== '' && $x !== null;
  913. })) {
  914. $hasActiveSearch = true;
  915. break;
  916. }
  917. } elseif ($v !== '' && $v !== null) {
  918. $hasActiveSearch = true;
  919. break;
  920. }
  921. }
  922. }
  923. }
  924. }
  925. $applyMonthRange = !$hasActiveSearch;
  926. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  927. $opArr = (array)json_decode($this->request->get('op', ''), true);
  928. try {
  929. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  930. if ($wffTab === 'audit') {
  931. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  932. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  933. );
  934. } elseif ($wffTab === 'confirm') {
  935. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  936. if ($dbRows === []) {
  937. try {
  938. $dbRows = Db::table('purchase_order')
  939. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  940. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  941. ->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%\')')
  942. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  943. ->order('pick_time', 'desc')->order('id', 'desc')
  944. ->select();
  945. } catch (\Throwable $e) {
  946. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  947. $dbRows = [];
  948. }
  949. }
  950. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  951. if ($pool === []) {
  952. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  953. }
  954. } else {
  955. $pool = $this->procuremenEnsureRedisPool();
  956. if (!is_array($pool)) {
  957. $pool = [];
  958. }
  959. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  960. $hideSet = $this->loadPickHiddenScydgySet();
  961. if ($pool !== [] && $hideSet !== []) {
  962. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  963. if (!is_array($r)) {
  964. return false;
  965. }
  966. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  967. return $id <= 0 || !isset($hideSet[$id]);
  968. }));
  969. }
  970. $manualPool = $this->loadPickManualOrderRows();
  971. if ($manualPool !== []) {
  972. $pool = array_merge($pool, $manualPool);
  973. }
  974. if ($pool === []) {
  975. return json([
  976. 'total' => 0,
  977. 'rows' => [],
  978. ]);
  979. }
  980. }
  981. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  982. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  983. $monthStart = $ym . '-01 00:00:00';
  984. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  985. }
  986. $filtered = $this->filterProcuremenIndexPool(
  987. $pool,
  988. $monthStart,
  989. $monthEnd,
  990. $applyMonthRange,
  991. $search,
  992. $filterArr,
  993. $opArr,
  994. $listTimePrimary
  995. );
  996. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  997. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  998. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  999. }
  1000. $sortField = 'ID';
  1001. if (is_string($sort) && $sort !== '') {
  1002. $parts = explode(',', $sort);
  1003. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1004. if ($sortField === '') {
  1005. $sortField = 'ID';
  1006. }
  1007. }
  1008. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1009. $nFiltered = count($filtered);
  1010. if ($nFiltered > 1) {
  1011. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1012. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1013. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1014. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1015. if ($ta === $tb) {
  1016. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1017. }
  1018. if ($ta === '') {
  1019. return 1;
  1020. }
  1021. if ($tb === '') {
  1022. return -1;
  1023. }
  1024. return strcmp($ta, $tb) * $ord;
  1025. });
  1026. } elseif ($sortField === 'ID') {
  1027. $sortKeys = [];
  1028. foreach ($filtered as $i => $row) {
  1029. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1030. }
  1031. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1032. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1033. } elseif ($sortField === 'CCYDH') {
  1034. usort($filtered, function ($a, $b) use ($ord) {
  1035. $sa = trim((string)($a['CCYDH'] ?? ''));
  1036. $sb = trim((string)($b['CCYDH'] ?? ''));
  1037. if ($sa === $sb) {
  1038. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1039. }
  1040. if ($sa === '') {
  1041. return 1;
  1042. }
  1043. if ($sb === '') {
  1044. return -1;
  1045. }
  1046. return strcmp($sa, $sb) * $ord;
  1047. });
  1048. } else {
  1049. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1050. $va = $a[$sortField] ?? null;
  1051. $vb = $b[$sortField] ?? null;
  1052. $sa = (string)$va;
  1053. $sb = (string)$vb;
  1054. if ($sa === $sb) {
  1055. return 0;
  1056. }
  1057. return strcmp($sa, $sb) * $ord;
  1058. });
  1059. }
  1060. }
  1061. $offset = max(0, (int)$offset);
  1062. $limit = max(1, (int)$limit);
  1063. $rows = array_slice($filtered, $offset, $limit);
  1064. foreach ($rows as &$rw) {
  1065. if (!is_array($rw)) {
  1066. continue;
  1067. }
  1068. $rid = (int)($rw['ID'] ?? 0);
  1069. $rw['_iss_out'] = ($wffTab !== 'pick');
  1070. }
  1071. unset($rw);
  1072. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1073. $idList = [];
  1074. foreach ($rows as $rw) {
  1075. if (!is_array($rw)) {
  1076. continue;
  1077. }
  1078. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1079. foreach ($rw['_order_merge_rows'] as $mr) {
  1080. $mid = (int)($mr['ID'] ?? 0);
  1081. if ($this->isValidScydgyRowId($mid)) {
  1082. $idList[$mid] = true;
  1083. }
  1084. }
  1085. }
  1086. $id = (int)($rw['ID'] ?? 0);
  1087. if ($this->isValidScydgyRowId($id)) {
  1088. $idList[$id] = true;
  1089. }
  1090. }
  1091. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1092. foreach ($rows as &$rw) {
  1093. if (!is_array($rw)) {
  1094. continue;
  1095. }
  1096. $mergeIds = [];
  1097. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1098. foreach ($rw['_order_merge_rows'] as $mr) {
  1099. $mid = (int)($mr['ID'] ?? 0);
  1100. if ($this->isValidScydgyRowId($mid)) {
  1101. $mergeIds[$mid] = true;
  1102. }
  1103. }
  1104. }
  1105. $rid = (int)($rw['ID'] ?? 0);
  1106. if ($this->isValidScydgyRowId($rid)) {
  1107. $mergeIds[$rid] = true;
  1108. }
  1109. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1110. $rw['po_detail_count'] = $s['cnt'];
  1111. $rw['po_amount_fill_cnt'] = $s['amt'];
  1112. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1113. }
  1114. unset($rw);
  1115. }
  1116. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1117. $idList = [];
  1118. foreach ($rows as $rw) {
  1119. if (!is_array($rw)) {
  1120. continue;
  1121. }
  1122. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1123. foreach ($rw['_order_merge_rows'] as $mr) {
  1124. $mid = (int)($mr['ID'] ?? 0);
  1125. if ($this->isValidScydgyRowId($mid)) {
  1126. $idList[$mid] = true;
  1127. }
  1128. }
  1129. }
  1130. $id = (int)($rw['ID'] ?? 0);
  1131. if ($this->isValidScydgyRowId($id)) {
  1132. $idList[$id] = true;
  1133. }
  1134. }
  1135. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1136. $bidOpenSet = [];
  1137. if ($wffTab === 'audit') {
  1138. $ccydhList = [];
  1139. foreach ($rows as $rw0) {
  1140. if (!is_array($rw0)) {
  1141. continue;
  1142. }
  1143. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1144. if ($c0 !== '') {
  1145. $ccydhList[] = $c0;
  1146. }
  1147. }
  1148. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1149. }
  1150. foreach ($rows as &$rw) {
  1151. if (!is_array($rw)) {
  1152. continue;
  1153. }
  1154. $mergeIds = [];
  1155. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1156. foreach ($rw['_order_merge_rows'] as $mr) {
  1157. $mid = (int)($mr['ID'] ?? 0);
  1158. if ($this->isValidScydgyRowId($mid)) {
  1159. $mergeIds[$mid] = true;
  1160. }
  1161. }
  1162. }
  1163. $rid = (int)($rw['ID'] ?? 0);
  1164. if ($this->isValidScydgyRowId($rid)) {
  1165. $mergeIds[$rid] = true;
  1166. }
  1167. $buckets = [];
  1168. foreach (array_keys($mergeIds) as $mid) {
  1169. if (isset($quoteBucket[$mid])) {
  1170. $buckets[] = $quoteBucket[$mid];
  1171. }
  1172. }
  1173. $supplierText = $buckets !== []
  1174. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1175. : '';
  1176. if ($wffTab === 'confirm') {
  1177. $rw['picked_supplier_name'] = $supplierText;
  1178. } else {
  1179. $rw['notify_supplier_text'] = $supplierText;
  1180. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1181. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1182. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1183. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1184. }
  1185. }
  1186. unset($rw);
  1187. }
  1188. if ($wffTab === 'all' && count($rows) > 0) {
  1189. $this->mergePurchaseOrder($rows);
  1190. }
  1191. if ($wffTab === 'pick' && count($rows) > 0) {
  1192. $this->mergePurchaseOrder($rows);
  1193. }
  1194. foreach ($rows as &$rwClean) {
  1195. if (is_array($rwClean)) {
  1196. unset($rwClean['_order_merge_rows']);
  1197. if (array_key_exists('NGZL', $rwClean)) {
  1198. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1199. }
  1200. }
  1201. }
  1202. unset($rwClean);
  1203. return json([
  1204. 'total' => count($filtered),
  1205. 'rows' => $rows,
  1206. 'activeYm' => $ym,
  1207. ]);
  1208. } catch (\Throwable $e) {
  1209. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1210. return json([
  1211. 'total' => 0,
  1212. 'rows' => [],
  1213. ]);
  1214. }
  1215. }
  1216. /**
  1217. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1218. *
  1219. * @return array<int, true>
  1220. */
  1221. protected function loadPickHiddenScydgySet(): array
  1222. {
  1223. if ($this->pickHiddenScydgySetCache !== null) {
  1224. return $this->pickHiddenScydgySetCache;
  1225. }
  1226. $hideSet = [];
  1227. try {
  1228. $poIds = Db::table('purchase_order')
  1229. ->where(function ($q) {
  1230. $q->whereIn('wflow_status', array_merge(
  1231. ProcuremenStatus::wflowPendingConfirmValues(),
  1232. ProcuremenStatus::wflowPendingApprovalValues()
  1233. ))
  1234. ->whereOr(function ($q1) {
  1235. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1236. })
  1237. ->whereOr(function ($q2) {
  1238. $q2->whereNotNull('pick_time')
  1239. ->where('pick_time', '<>', '')
  1240. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1241. })
  1242. ->whereOr(function ($q3) {
  1243. $q3->whereNotNull('mod_rq')
  1244. ->where('mod_rq', '<>', '')
  1245. ->where('mod_rq', 'not like', '0000-00-00%');
  1246. });
  1247. })
  1248. ->column('scydgy_id');
  1249. if (is_array($poIds)) {
  1250. foreach ($poIds as $pid) {
  1251. $k = (int)$pid;
  1252. if ($k !== 0) {
  1253. $hideSet[$k] = true;
  1254. }
  1255. }
  1256. }
  1257. } catch (\Throwable $e) {
  1258. }
  1259. try {
  1260. $detIdsQuery = Db::table('purchase_order_detail');
  1261. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1262. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1263. if (is_array($detIds)) {
  1264. foreach ($detIds as $pid) {
  1265. $k = (int)$pid;
  1266. if ($this->isValidScydgyRowId($k)) {
  1267. $hideSet[$k] = true;
  1268. }
  1269. }
  1270. }
  1271. } catch (\Throwable $e) {
  1272. }
  1273. $this->pickHiddenScydgySetCache = $hideSet;
  1274. return $hideSet;
  1275. }
  1276. /**
  1277. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1278. *
  1279. * @return array<int, array<string, mixed>>
  1280. */
  1281. protected function loadPickManualOrderRows(): array
  1282. {
  1283. try {
  1284. $dbRows = Db::table('purchase_order')
  1285. ->where('scydgy_id', '<', 0)
  1286. ->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%\')')
  1287. ->order('scydgy_id', 'asc')
  1288. ->select();
  1289. } catch (\Throwable $e) {
  1290. try {
  1291. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1292. } catch (\Throwable $e2) {
  1293. return [];
  1294. }
  1295. }
  1296. if (!is_array($dbRows) || $dbRows === []) {
  1297. return [];
  1298. }
  1299. $detailSidSet = [];
  1300. try {
  1301. $negIds = [];
  1302. foreach ($dbRows as $dbRow) {
  1303. if (!is_array($dbRow)) {
  1304. continue;
  1305. }
  1306. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1307. if ($sid < 0) {
  1308. $negIds[$sid] = true;
  1309. }
  1310. }
  1311. if ($negIds !== []) {
  1312. $detQuery = Db::table('purchase_order_detail')
  1313. ->where('scydgy_id', 'in', array_keys($negIds));
  1314. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1315. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1316. if (is_array($detRows)) {
  1317. foreach ($detRows as $did) {
  1318. $detailSidSet[(int)$did] = true;
  1319. }
  1320. }
  1321. }
  1322. } catch (\Throwable $e) {
  1323. }
  1324. $pool = [];
  1325. foreach ($dbRows as $dbRow) {
  1326. if (!is_array($dbRow)) {
  1327. continue;
  1328. }
  1329. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1330. if ($sid >= 0) {
  1331. continue;
  1332. }
  1333. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1334. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1335. continue;
  1336. }
  1337. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1338. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1339. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1340. continue;
  1341. }
  1342. if (isset($detailSidSet[$sid])) {
  1343. continue;
  1344. }
  1345. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1346. $r['_is_manual'] = 1;
  1347. $pool[] = $r;
  1348. }
  1349. return $pool;
  1350. }
  1351. /**
  1352. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1353. */
  1354. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1355. {
  1356. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1357. foreach ($keys as $k) {
  1358. $t = trim((string)($row[$k] ?? ''));
  1359. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1360. return $t;
  1361. }
  1362. }
  1363. return '';
  1364. }
  1365. /**
  1366. * 分配手工新增工序行 ID(负数递减)
  1367. */
  1368. protected function allocateManualScydgyId(): int
  1369. {
  1370. try {
  1371. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1372. $min = (int)$min;
  1373. return $min < 0 ? $min - 1 : -1;
  1374. } catch (\Throwable $e) {
  1375. return -1;
  1376. }
  1377. }
  1378. /**
  1379. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1380. */
  1381. protected function allocateManualOrderCcydh(): string
  1382. {
  1383. $prefix = 'YW' . date('Ymd');
  1384. $maxSeq = 0;
  1385. try {
  1386. $rows = Db::table('purchase_order')
  1387. ->where('CCYDH', 'like', $prefix . '%')
  1388. ->column('CCYDH');
  1389. if (is_array($rows)) {
  1390. foreach ($rows as $ccydh) {
  1391. $ccydh = trim((string)$ccydh);
  1392. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1393. $maxSeq = max($maxSeq, (int)$m[1]);
  1394. }
  1395. }
  1396. }
  1397. } catch (\Throwable $e) {
  1398. }
  1399. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1400. }
  1401. /**
  1402. * purchase_order.mod_rq 是否有有效软删除时间
  1403. */
  1404. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1405. {
  1406. $t = trim((string)$modRq);
  1407. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1408. }
  1409. /**
  1410. * 列表行 → purchase_order 写入字段
  1411. *
  1412. * @return array<string, mixed>
  1413. */
  1414. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1415. {
  1416. return [
  1417. 'scydgy_id' => $scydgyId,
  1418. 'CCYDH' => $row['CCYDH'] ?? null,
  1419. 'CYJMC' => $row['CYJMC'] ?? null,
  1420. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1421. 'CDXMC' => $row['CDXMC'] ?? null,
  1422. 'CGYBH' => $row['CGYBH'] ?? null,
  1423. 'CGYMC' => $row['CGYMC'] ?? null,
  1424. 'CDW' => $row['CDW'] ?? null,
  1425. 'NGZL' => $row['NGZL'] ?? null,
  1426. 'CDF' => $row['CDF'] ?? null,
  1427. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1428. 'MBZ' => $row['MBZ'] ?? null,
  1429. 'bwjg' => $row['bwjg'] ?? null,
  1430. 'iStatus' => $row['iStatus'] ?? null,
  1431. 'dStamp' => $row['dStamp'] ?? null,
  1432. 'dputrecord' => $row['dputrecord'] ?? null,
  1433. 'cywyxm' => $row['cywyxm'] ?? null,
  1434. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1435. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1436. ];
  1437. }
  1438. /**
  1439. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1440. *
  1441. * @return array{po:?array<string,mixed>, hidden:bool}
  1442. */
  1443. protected function resolvePickRowPoContext(int $sid): array
  1444. {
  1445. $po = null;
  1446. try {
  1447. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1448. if (is_array($found)) {
  1449. $po = $found;
  1450. }
  1451. } catch (\Throwable $e) {
  1452. }
  1453. $hideSet = $this->loadPickHiddenScydgySet();
  1454. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1455. }
  1456. /**
  1457. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1458. */
  1459. protected function assertPickRowCanDelete(int $sid, array $row): void
  1460. {
  1461. $ctx = $this->resolvePickRowPoContext($sid);
  1462. $po = $ctx['po'];
  1463. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1464. return;
  1465. }
  1466. if (is_array($po)) {
  1467. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1468. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1469. }
  1470. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1471. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1472. }
  1473. }
  1474. if ($ctx['hidden']) {
  1475. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1476. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1477. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1478. }
  1479. }
  1480. /**
  1481. * 初选直接完结前校验
  1482. */
  1483. protected function assertPickRowCanComplete(int $sid, array $row): void
  1484. {
  1485. $ctx = $this->resolvePickRowPoContext($sid);
  1486. $po = $ctx['po'];
  1487. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1488. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1489. }
  1490. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1491. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1492. }
  1493. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1494. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1495. }
  1496. }
  1497. /**
  1498. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1499. */
  1500. protected function softDeleteProcuremenPickRow(array $row): void
  1501. {
  1502. $sid = $this->extractScydgyRowId($row);
  1503. if (!$this->isValidScydgyRowId($sid)) {
  1504. throw new \InvalidArgumentException('无效的行主键');
  1505. }
  1506. $this->assertPickRowCanDelete($sid, $row);
  1507. $po = $this->resolvePickRowPoContext($sid)['po'];
  1508. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1509. return;
  1510. }
  1511. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1512. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1513. }
  1514. $now = date('Y-m-d H:i:s');
  1515. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1516. if (is_array($exists)) {
  1517. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1518. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1519. } else {
  1520. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1521. $data['mod_rq'] = $now;
  1522. $data['createtime'] = $now;
  1523. Db::table('purchase_order')->insert($data);
  1524. $poIdLog = (int)Db::getLastInsID();
  1525. }
  1526. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1527. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1528. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1529. if ($gymcLog !== '') {
  1530. $logTail .= ' / ' . $gymcLog;
  1531. }
  1532. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1533. }
  1534. /**
  1535. * 手工新增协助工序(写入 purchase_order)
  1536. *
  1537. * @param array<string, mixed> $params
  1538. * @return int scydgy_id
  1539. */
  1540. protected function saveManualPickOrder(array $params): int
  1541. {
  1542. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1543. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1544. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1545. if ($ccydh === '') {
  1546. $ccydh = $this->allocateManualOrderCcydh();
  1547. }
  1548. $now = date('Y-m-d H:i:s');
  1549. $sid = $this->allocateManualScydgyId();
  1550. $data = [
  1551. 'scydgy_id' => $sid,
  1552. 'CCYDH' => $ccydh,
  1553. 'CYJMC' => $cyjmc,
  1554. 'CGYMC' => $cgymc,
  1555. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1556. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1557. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1558. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1559. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1560. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1561. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1562. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1563. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1564. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1565. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1566. 'createtime' => $now,
  1567. 'dStamp' => $now,
  1568. 'dputrecord' => $now,
  1569. ];
  1570. Db::table('purchase_order')->insert($data);
  1571. $poId = (int)Db::getLastInsID();
  1572. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1573. return $sid;
  1574. }
  1575. protected function formatProcuremenRowLabel(array $row): string
  1576. {
  1577. $dh = trim((string)($row['CCYDH'] ?? ''));
  1578. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1579. if ($dh !== '' && $gymc !== '') {
  1580. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1581. }
  1582. if ($dh !== '') {
  1583. return '订单「' . $dh . '」';
  1584. }
  1585. if ($gymc !== '') {
  1586. return '工序「' . $gymc . '」';
  1587. }
  1588. $id = $this->extractScydgyRowId($row);
  1589. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1590. }
  1591. /**
  1592. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1593. */
  1594. protected function extractScydgyRowId(array $row): int
  1595. {
  1596. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  1597. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  1598. return (int)$row['scydgy_id'];
  1599. }
  1600. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  1601. return (int)$row['SCYDGY_ID'];
  1602. }
  1603. return (int)($row['ID'] ?? $row['id'] ?? 0);
  1604. }
  1605. protected function isValidScydgyRowId(int $id): bool
  1606. {
  1607. return ProcuremenGuard::isValidScydgyId($id);
  1608. }
  1609. protected function isManualScydgyRowId(int $id): bool
  1610. {
  1611. return $id < 0;
  1612. }
  1613. /**
  1614. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1615. *
  1616. * @param int[] $scydgyIds
  1617. * @return array<int, string[]>
  1618. */
  1619. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1620. {
  1621. $out = [];
  1622. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1623. if ($scydgyIds === []) {
  1624. return $out;
  1625. }
  1626. try {
  1627. $rows = Db::table('purchase_order_detail')
  1628. ->where('scydgy_id', 'in', $scydgyIds)
  1629. ->field('scydgy_id,company_name')
  1630. ->order('company_name', 'asc')
  1631. ->select();
  1632. } catch (\Throwable $e) {
  1633. $rows = [];
  1634. }
  1635. if (!is_array($rows)) {
  1636. return $out;
  1637. }
  1638. foreach ($rows as $r) {
  1639. if (!is_array($r)) {
  1640. continue;
  1641. }
  1642. $sid = (int)($r['scydgy_id'] ?? 0);
  1643. $cn = trim((string)($r['company_name'] ?? ''));
  1644. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1645. continue;
  1646. }
  1647. if (!isset($out[$sid])) {
  1648. $out[$sid] = [];
  1649. }
  1650. if (!in_array($cn, $out[$sid], true)) {
  1651. $out[$sid][] = $cn;
  1652. }
  1653. }
  1654. return $out;
  1655. }
  1656. /**
  1657. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1658. *
  1659. * @param string[] $names
  1660. */
  1661. protected function formatNotifySupplierDisplay(array $names): string
  1662. {
  1663. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1664. return trim((string)$n);
  1665. }, $names))));
  1666. if ($names === []) {
  1667. return '';
  1668. }
  1669. sort($names, SORT_STRING);
  1670. return implode("\n", $names);
  1671. }
  1672. /**
  1673. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1674. *
  1675. * @param int[] $scydgyIds
  1676. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1677. */
  1678. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1679. {
  1680. $out = [];
  1681. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1682. if ($scydgyIds === []) {
  1683. return $out;
  1684. }
  1685. try {
  1686. $rows = Db::table('purchase_order_detail')
  1687. ->where('scydgy_id', 'in', $scydgyIds)
  1688. ->field('scydgy_id,company_name,amount')
  1689. ->select();
  1690. } catch (\Throwable $e) {
  1691. $rows = [];
  1692. }
  1693. if (!is_array($rows)) {
  1694. return $out;
  1695. }
  1696. foreach ($rows as $r) {
  1697. if (!is_array($r)) {
  1698. continue;
  1699. }
  1700. $sid = (int)($r['scydgy_id'] ?? 0);
  1701. $cn = trim((string)($r['company_name'] ?? ''));
  1702. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1703. continue;
  1704. }
  1705. if (!isset($out[$sid])) {
  1706. $out[$sid] = ['all' => [], 'quoted' => []];
  1707. }
  1708. $out[$sid]['all'][$cn] = true;
  1709. $am = trim((string)($r['amount'] ?? ''));
  1710. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1711. $out[$sid]['quoted'][$cn] = true;
  1712. }
  1713. }
  1714. return $out;
  1715. }
  1716. /**
  1717. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1718. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1719. */
  1720. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1721. {
  1722. $merged = ['all' => [], 'quoted' => []];
  1723. foreach ($buckets as $b) {
  1724. if (!is_array($b)) {
  1725. continue;
  1726. }
  1727. foreach ($b['all'] ?? [] as $cn => $_) {
  1728. $merged['all'][$cn] = true;
  1729. }
  1730. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1731. $merged['quoted'][$cn] = true;
  1732. }
  1733. }
  1734. return $merged;
  1735. }
  1736. /**
  1737. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1738. */
  1739. protected function formatQuotedSupplierLines(array $bucket): string
  1740. {
  1741. $all = array_keys($bucket['all'] ?? []);
  1742. if ($all === []) {
  1743. return '';
  1744. }
  1745. sort($all, SORT_STRING);
  1746. $lines = [];
  1747. foreach ($all as $cn) {
  1748. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1749. $lines[] = $cn . '(' . $status . ')';
  1750. }
  1751. return implode("\n", $lines);
  1752. }
  1753. /**
  1754. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1755. */
  1756. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1757. {
  1758. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1759. $this->view->engine->layout(false);
  1760. try {
  1761. $bodyHtml = $this->view->fetch($view);
  1762. $this->view->assign('dialogBody', $bodyHtml);
  1763. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1764. return $this->view->fetch('procuremen/dialog_lite_shell');
  1765. } finally {
  1766. if ($restoreLayout) {
  1767. $this->view->engine->layout($restoreLayout);
  1768. }
  1769. }
  1770. }
  1771. /**
  1772. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1773. */
  1774. protected function resolveBundleSysRq(array $bundle): string
  1775. {
  1776. foreach ($bundle['pos'] ?? [] as $po) {
  1777. if (!is_array($po)) {
  1778. continue;
  1779. }
  1780. $sr = trim((string)($po['sys_rq'] ?? ''));
  1781. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1782. return $sr;
  1783. }
  1784. }
  1785. return '';
  1786. }
  1787. /**
  1788. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1789. */
  1790. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1791. {
  1792. $raw = trim((string)$sysRq);
  1793. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1794. return true;
  1795. }
  1796. $ts = strtotime(str_replace('T', ' ', $raw));
  1797. if ($ts === false || $ts <= 0) {
  1798. return true;
  1799. }
  1800. return time() >= $ts;
  1801. }
  1802. /**
  1803. * 开标前校验:必须已过报价截止时间
  1804. *
  1805. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1806. */
  1807. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1808. {
  1809. $sysRq = $this->resolveBundleSysRq($bundle);
  1810. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1811. $this->error('未到招标截止日期');
  1812. }
  1813. }
  1814. /**
  1815. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1816. *
  1817. * @param array<string, mixed> $d
  1818. * @param string $deliveryYmd
  1819. */
  1820. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1821. {
  1822. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1823. return max(0, (int)$d['lead_days']);
  1824. }
  1825. if ($deliveryYmd === '') {
  1826. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1827. }
  1828. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1829. return null;
  1830. }
  1831. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1832. $t2 = strtotime($m[1] . ' 00:00:00');
  1833. if ($t1 === false || $t2 === false) {
  1834. return null;
  1835. }
  1836. return max(0, (int)round(($t2 - $t1) / 86400));
  1837. }
  1838. /**
  1839. * @param int|null $days
  1840. */
  1841. protected function formatProcuremenLeadDaysText($days): string
  1842. {
  1843. if ($days === null || $days === '') {
  1844. return '未填写';
  1845. }
  1846. if (!is_numeric($days)) {
  1847. return '未填写';
  1848. }
  1849. return ((int)$days) . '天';
  1850. }
  1851. /**
  1852. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  1853. *
  1854. * @param array<string, mixed> $line
  1855. */
  1856. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1857. {
  1858. $amountFilled = !empty($line['amount_filled']);
  1859. $deliveryFilled = !empty($line['delivery_filled']);
  1860. $leadFilled = !empty($line['lead_days_filled']);
  1861. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  1862. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1863. $line['amount_show'] = '';
  1864. if (array_key_exists('amount_text', $line)) {
  1865. $line['amount_text'] = $line['unit_price_text'];
  1866. }
  1867. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1868. $line['delivery_show'] = $deliveryText;
  1869. if (array_key_exists('delivery_text', $line)) {
  1870. $line['delivery_text'] = $deliveryText;
  1871. }
  1872. $line['delivery_ymd'] = '';
  1873. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  1874. $line['lead_days_show'] = $leadText;
  1875. $line['lead_days_text'] = $leadText;
  1876. $line['lead_days'] = '';
  1877. // 小计、操作时间与单价等同属报价信息,开标前不可见
  1878. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  1879. $line['subtotal_num'] = null;
  1880. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  1881. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1882. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1883. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  1884. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  1885. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  1886. $line['amount_filled'] = false;
  1887. $line['delivery_filled'] = false;
  1888. $line['lead_days_filled'] = false;
  1889. $line['is_quoted'] = false;
  1890. if (array_key_exists('quote_label', $line)) {
  1891. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  1892. }
  1893. }
  1894. protected function ensurePurchaseOrderBidOpenTable(): void
  1895. {
  1896. try {
  1897. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1898. } catch (\Throwable $e) {
  1899. Db::execute(
  1900. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1901. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1902. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1903. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1904. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1905. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1906. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1907. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1908. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1909. `createtime` datetime DEFAULT NULL,
  1910. PRIMARY KEY (`id`),
  1911. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1912. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1913. );
  1914. }
  1915. }
  1916. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1917. {
  1918. $ccydh = trim($ccydh);
  1919. if ($ccydh === '') {
  1920. return false;
  1921. }
  1922. $this->ensurePurchaseOrderBidOpenTable();
  1923. try {
  1924. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1925. return is_array($row);
  1926. } catch (\Throwable $e) {
  1927. return false;
  1928. }
  1929. }
  1930. /**
  1931. * 批量查询订单是否已开标验证
  1932. *
  1933. * @param array<int, string> $ccydhs
  1934. * @return array<string, bool> ccydh => true
  1935. */
  1936. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  1937. {
  1938. $set = [];
  1939. $list = [];
  1940. foreach ($ccydhs as $c) {
  1941. $c = trim((string)$c);
  1942. if ($c !== '') {
  1943. $list[$c] = true;
  1944. }
  1945. }
  1946. if ($list === []) {
  1947. return $set;
  1948. }
  1949. $this->ensurePurchaseOrderBidOpenTable();
  1950. try {
  1951. $rows = Db::table('purchase_order_bid_open')
  1952. ->where('ccydh', 'in', array_keys($list))
  1953. ->field('ccydh')
  1954. ->select();
  1955. foreach ($rows as $row) {
  1956. if (!is_array($row)) {
  1957. continue;
  1958. }
  1959. $c = trim((string)($row['ccydh'] ?? ''));
  1960. if ($c !== '') {
  1961. $set[$c] = true;
  1962. }
  1963. }
  1964. } catch (\Throwable $e) {
  1965. return [];
  1966. }
  1967. return $set;
  1968. }
  1969. /**
  1970. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  1971. *
  1972. * @param array<string, mixed> $group
  1973. */
  1974. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  1975. {
  1976. if ($quoteVisible) {
  1977. $group['remark_quote_pending'] = 0;
  1978. return;
  1979. }
  1980. $group['remark'] = '';
  1981. $group['remark_quote_pending'] = 0;
  1982. }
  1983. /**
  1984. * @param array{ccydh?:string} $bundle
  1985. */
  1986. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1987. {
  1988. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1989. }
  1990. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1991. {
  1992. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1993. }
  1994. protected function loadBidOpenAdminUser(int $adminId): ?array
  1995. {
  1996. if ($adminId <= 0) {
  1997. return null;
  1998. }
  1999. try {
  2000. $row = Db::name('admin')->where('id', $adminId)->find();
  2001. } catch (\Throwable $e) {
  2002. return null;
  2003. }
  2004. if (!is_array($row)) {
  2005. return null;
  2006. }
  2007. $status = strtolower(trim((string)($row['status'] ?? '')));
  2008. if ($status !== '' && $status !== 'normal') {
  2009. return null;
  2010. }
  2011. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2012. return null;
  2013. }
  2014. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2015. if (!preg_match('/^1\d{10}$/', $phone)) {
  2016. return null;
  2017. }
  2018. $name = trim((string)($row['nickname'] ?? ''));
  2019. if ($name === '') {
  2020. $name = trim((string)($row['username'] ?? ''));
  2021. }
  2022. return [
  2023. 'id' => (int)$row['id'],
  2024. 'username' => trim((string)($row['username'] ?? '')),
  2025. 'nickname' => $name,
  2026. 'mobile' => $phone,
  2027. ];
  2028. }
  2029. /**
  2030. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2031. */
  2032. protected function bidOpenVerifierAuthGroupRootId(): int
  2033. {
  2034. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2035. return $id > 0 ? $id : 10;
  2036. }
  2037. /**
  2038. * @return int[]
  2039. */
  2040. protected function loadBidOpenVerifierAuthGroupIds(): array
  2041. {
  2042. static $memo = [];
  2043. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2044. if (isset($memo[$rootId])) {
  2045. return $memo[$rootId];
  2046. }
  2047. try {
  2048. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2049. } catch (\Throwable $e) {
  2050. $memo[$rootId] = [$rootId];
  2051. return $memo[$rootId];
  2052. }
  2053. if (!is_array($groups) || $groups === []) {
  2054. $memo[$rootId] = [$rootId];
  2055. return $memo[$rootId];
  2056. }
  2057. $groupList = [];
  2058. foreach ($groups as $g) {
  2059. if (is_array($g)) {
  2060. $groupList[] = $g;
  2061. }
  2062. }
  2063. if ($groupList === []) {
  2064. $memo[$rootId] = [$rootId];
  2065. return $memo[$rootId];
  2066. }
  2067. $tree = \fast\Tree::instance();
  2068. $tree->init($groupList);
  2069. $ids = $tree->getChildrenIds($rootId, true);
  2070. if (!is_array($ids) || $ids === []) {
  2071. $memo[$rootId] = [$rootId];
  2072. return $memo[$rootId];
  2073. }
  2074. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2075. return $memo[$rootId];
  2076. }
  2077. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2078. {
  2079. if ($adminId <= 0) {
  2080. return false;
  2081. }
  2082. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2083. if ($groupIds === []) {
  2084. return false;
  2085. }
  2086. try {
  2087. return (bool)Db::name('auth_group_access')
  2088. ->where('uid', $adminId)
  2089. ->where('group_id', 'in', $groupIds)
  2090. ->count();
  2091. } catch (\Throwable $e) {
  2092. return false;
  2093. }
  2094. }
  2095. /**
  2096. * @return array<int, array<string, mixed>>
  2097. */
  2098. protected function listBidOpenVerifierCandidates(): array
  2099. {
  2100. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2101. if ($groupIds === []) {
  2102. return [];
  2103. }
  2104. try {
  2105. $adminIds = Db::name('auth_group_access')
  2106. ->where('group_id', 'in', $groupIds)
  2107. ->column('uid');
  2108. } catch (\Throwable $e) {
  2109. $adminIds = [];
  2110. }
  2111. $adminIds = is_array($adminIds)
  2112. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2113. : [];
  2114. if ($adminIds === []) {
  2115. return [];
  2116. }
  2117. try {
  2118. $rows = Db::name('admin')
  2119. ->where('status', 'normal')
  2120. ->where('id', 'in', $adminIds)
  2121. ->where('mobile', '<>', '')
  2122. ->order('id', 'asc')
  2123. ->select();
  2124. } catch (\Throwable $e) {
  2125. return [];
  2126. }
  2127. if (!is_array($rows)) {
  2128. return [];
  2129. }
  2130. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2131. $out = [];
  2132. foreach ($rows as $row) {
  2133. if (!is_array($row)) {
  2134. continue;
  2135. }
  2136. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2137. if ($one === null) {
  2138. continue;
  2139. }
  2140. $out[] = [
  2141. 'id' => $one['id'],
  2142. 'username' => $one['username'],
  2143. 'nickname' => $one['nickname'],
  2144. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2145. 'mobile' => mask_phone($one['mobile']),
  2146. ];
  2147. }
  2148. return $out;
  2149. }
  2150. /**
  2151. * @param int[] $adminIds
  2152. * @return array<int, string>
  2153. */
  2154. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2155. {
  2156. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2157. if ($adminIds === []) {
  2158. return [];
  2159. }
  2160. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2161. try {
  2162. $rows = Db::name('auth_group_access')
  2163. ->alias('aga')
  2164. ->join('auth_group ag', 'aga.group_id = ag.id')
  2165. ->where('aga.uid', 'in', $adminIds)
  2166. ->where('aga.group_id', 'in', $groupIds)
  2167. ->field('aga.uid,ag.name')
  2168. ->order('aga.uid', 'asc')
  2169. ->order('aga.group_id', 'asc')
  2170. ->select();
  2171. } catch (\Throwable $e) {
  2172. return [];
  2173. }
  2174. if (!is_array($rows)) {
  2175. return [];
  2176. }
  2177. $out = [];
  2178. foreach ($rows as $row) {
  2179. if (!is_array($row)) {
  2180. continue;
  2181. }
  2182. $uid = (int)($row['uid'] ?? 0);
  2183. $name = trim((string)($row['name'] ?? ''));
  2184. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2185. continue;
  2186. }
  2187. $out[$uid] = $name;
  2188. }
  2189. return $out;
  2190. }
  2191. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2192. {
  2193. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2194. }
  2195. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2196. {
  2197. return 'procuremen_bidopen_wait_' . $adminId;
  2198. }
  2199. protected function renderBidOpenVerifySms(string $code): string
  2200. {
  2201. $tpl = '';
  2202. try {
  2203. $row = $this->loadNotifyTemplateRow('bid_open');
  2204. if (is_array($row)) {
  2205. $tpl = trim((string)($row['content'] ?? ''));
  2206. }
  2207. } catch (\Throwable $e) {
  2208. $tpl = '';
  2209. }
  2210. if ($tpl === '') {
  2211. $tpl = '【可集达】您的短信验证码是{code}';
  2212. }
  2213. return str_replace('{code}', $code, $tpl);
  2214. }
  2215. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2216. {
  2217. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2218. }
  2219. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2220. {
  2221. $code = trim($code);
  2222. if (!preg_match('/^\d{6}$/', $code)) {
  2223. return false;
  2224. }
  2225. $mock = Config::get('mproc.mock_sms_code');
  2226. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2227. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2228. return true;
  2229. }
  2230. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2231. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2232. return false;
  2233. }
  2234. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2235. return true;
  2236. }
  2237. /**
  2238. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2239. */
  2240. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2241. {
  2242. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2243. if ($ccydh === '') {
  2244. throw new \InvalidArgumentException('订单号无效');
  2245. }
  2246. $this->ensurePurchaseOrderBidOpenTable();
  2247. list($operatorId, $operatorName) = $this->GetUseName();
  2248. $now = date('Y-m-d H:i:s');
  2249. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2250. $payload = [
  2251. 'ccydh' => $ccydh,
  2252. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2253. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2254. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2255. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2256. 'operator_id' => (int)$operatorId,
  2257. 'operator_name' => trim((string)$operatorName),
  2258. 'createtime' => $now,
  2259. ];
  2260. if (is_array($exists)) {
  2261. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2262. } else {
  2263. Db::table('purchase_order_bid_open')->insert($payload);
  2264. }
  2265. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2266. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2267. $orderPart = '(订单' . $ccydh . ')';
  2268. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2269. $seenSid = [];
  2270. foreach ($bundle['pos'] ?? [] as $poRow) {
  2271. if (!is_array($poRow)) {
  2272. continue;
  2273. }
  2274. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2275. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2276. continue;
  2277. }
  2278. $seenSid[$sid] = true;
  2279. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2280. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2281. }
  2282. if ($seenSid === []) {
  2283. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2284. if ($this->isValidScydgyRowId($anchor)) {
  2285. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2286. }
  2287. }
  2288. // 开标通过后计算并写入供应商服务评分
  2289. try {
  2290. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  2291. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  2292. } catch (\Throwable $e) {
  2293. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  2294. }
  2295. }
  2296. /**
  2297. * 报价行展示字段默认值(模板安全访问)
  2298. *
  2299. * @param array<string, mixed> $line
  2300. * @return array<string, mixed>
  2301. */
  2302. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2303. {
  2304. if (!array_key_exists('amount_quote_pending', $line)) {
  2305. $line['amount_quote_pending'] = 0;
  2306. }
  2307. if (!array_key_exists('delivery_quote_pending', $line)) {
  2308. $line['delivery_quote_pending'] = 0;
  2309. }
  2310. if (!array_key_exists('quote_before_deadline', $line)) {
  2311. $line['quote_before_deadline'] = 0;
  2312. }
  2313. if (!array_key_exists('amount_filled', $line)) {
  2314. $line['amount_filled'] = 0;
  2315. }
  2316. if (!array_key_exists('delivery_filled', $line)) {
  2317. $line['delivery_filled'] = 0;
  2318. }
  2319. if (!array_key_exists('lead_days_filled', $line)) {
  2320. $line['lead_days_filled'] = 0;
  2321. }
  2322. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2323. $line['lead_days_quote_pending'] = 0;
  2324. }
  2325. if (!array_key_exists('lead_days_show', $line)) {
  2326. $line['lead_days_show'] = '未填写';
  2327. }
  2328. if (!array_key_exists('lead_days_text', $line)) {
  2329. $line['lead_days_text'] = $line['lead_days_show'];
  2330. }
  2331. return $line;
  2332. }
  2333. /**
  2334. * 审核弹窗:按供应商汇总报价明细
  2335. *
  2336. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2337. * @return array<int, array<string, mixed>>
  2338. */
  2339. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2340. {
  2341. $sids = [];
  2342. foreach ($bundle['pos'] ?? [] as $po) {
  2343. if (!is_array($po)) {
  2344. continue;
  2345. }
  2346. $sid = (int)($po['scydgy_id'] ?? 0);
  2347. if ($this->isValidScydgyRowId($sid)) {
  2348. $sids[$sid] = true;
  2349. }
  2350. }
  2351. if ($sids === []) {
  2352. return [];
  2353. }
  2354. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2355. $gymcMap = [];
  2356. $qtyBySid = [];
  2357. $orderedSids = [];
  2358. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2359. if (!is_array($mr)) {
  2360. continue;
  2361. }
  2362. $gid = $this->extractScydgyRowId($mr);
  2363. if ($this->isValidScydgyRowId($gid)) {
  2364. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2365. $orderedSids[] = $gid;
  2366. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2367. if ($qty === '') {
  2368. $qty = trim((string)($mr['NGZL'] ?? ''));
  2369. }
  2370. $qtyBySid[$gid] = $qty;
  2371. }
  2372. }
  2373. foreach ($bundle['pos'] ?? [] as $po) {
  2374. if (!is_array($po)) {
  2375. continue;
  2376. }
  2377. $gid = (int)($po['scydgy_id'] ?? 0);
  2378. if ($this->isValidScydgyRowId($gid)) {
  2379. $nm = trim((string)($po['CGYMC'] ?? ''));
  2380. if ($nm !== '') {
  2381. $gymcMap[$gid] = $nm;
  2382. }
  2383. if (!in_array($gid, $orderedSids, true)) {
  2384. $orderedSids[] = $gid;
  2385. }
  2386. }
  2387. }
  2388. try {
  2389. $detailsQuery = Db::table('purchase_order_detail')
  2390. ->where('scydgy_id', 'in', array_keys($sids));
  2391. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2392. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2393. } catch (\Throwable $e) {
  2394. try {
  2395. $detailsQuery = Db::table('purchase_order_detail')
  2396. ->where('scydgy_id', 'in', array_keys($sids));
  2397. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2398. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2399. } catch (\Throwable $e2) {
  2400. $details = [];
  2401. }
  2402. }
  2403. if (!is_array($details)) {
  2404. $details = [];
  2405. }
  2406. $byCompany = [];
  2407. foreach ($details as $d) {
  2408. if (!is_array($d)) {
  2409. continue;
  2410. }
  2411. $cn = trim((string)($d['company_name'] ?? ''));
  2412. if ($cn === '') {
  2413. continue;
  2414. }
  2415. if (!isset($byCompany[$cn])) {
  2416. $ph = trim((string)($d['phone'] ?? ''));
  2417. $username = trim((string)($d['username'] ?? ''));
  2418. if ($username === '') {
  2419. $username = $this->resolveCustomerContactName($ph, $cn);
  2420. }
  2421. $byCompany[$cn] = [
  2422. 'name' => $cn,
  2423. 'email' => trim((string)($d['email'] ?? '')),
  2424. 'phone' => $ph,
  2425. 'username' => $username,
  2426. 'remark' => '',
  2427. 'has_quote' => false,
  2428. 'lines_map' => [],
  2429. ];
  2430. }
  2431. if ($byCompany[$cn]['remark'] === '') {
  2432. $rm = '';
  2433. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2434. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2435. $rm = trim((string)$d[$rk]);
  2436. break;
  2437. }
  2438. }
  2439. if ($rm !== '') {
  2440. $byCompany[$cn]['remark'] = $rm;
  2441. }
  2442. }
  2443. $sid = (int)($d['scydgy_id'] ?? 0);
  2444. $am = trim((string)($d['amount'] ?? ''));
  2445. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2446. if ($gymc === '') {
  2447. $gymc = '工序';
  2448. }
  2449. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2450. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2451. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2452. $deliveryShow = $deliveryRaw;
  2453. }
  2454. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2455. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2456. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2457. $subtotal = null;
  2458. if ($amountNum !== null) {
  2459. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2460. }
  2461. $unitPriceText = $amountFilled
  2462. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2463. : '未填写';
  2464. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2465. $leadFilled = ($leadDays !== null);
  2466. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2467. $lineRow = [
  2468. 'cgymc' => $gymc,
  2469. 'amount' => $am,
  2470. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2471. 'amount_filled' => $amountFilled,
  2472. 'unit_price_text' => $unitPriceText,
  2473. 'delivery' => $deliveryRaw,
  2474. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2475. 'delivery_filled' => $deliveryFilled,
  2476. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2477. 'lead_days' => $leadFilled ? $leadDays : '',
  2478. 'lead_days_filled'=> $leadFilled,
  2479. 'lead_days_show' => $leadText,
  2480. 'lead_days_text' => $leadText,
  2481. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2482. 'subtotal_num' => $subtotal,
  2483. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2484. 'is_quoted' => $amountFilled,
  2485. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2486. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2487. ];
  2488. if (!$quoteVisible) {
  2489. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2490. }
  2491. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2492. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2493. }
  2494. foreach ($byCompany as $cn => $g) {
  2495. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2496. $lines = [];
  2497. $usedSids = [];
  2498. foreach ($orderedSids as $sid) {
  2499. if (!isset($linesMap[$sid])) {
  2500. continue;
  2501. }
  2502. $lines[] = $linesMap[$sid];
  2503. $usedSids[$sid] = true;
  2504. }
  2505. foreach ($linesMap as $sid => $ln) {
  2506. if (isset($usedSids[$sid])) {
  2507. continue;
  2508. }
  2509. $lines[] = $ln;
  2510. }
  2511. $total = count($lines);
  2512. $quoted = 0;
  2513. $groupTotal = 0.0;
  2514. $groupHasTotal = false;
  2515. if ($quoteVisible) {
  2516. foreach ($lines as $ln) {
  2517. $am = trim((string)($ln['amount'] ?? ''));
  2518. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2519. $quoted++;
  2520. }
  2521. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2522. $groupTotal += (float)$ln['subtotal_num'];
  2523. $groupHasTotal = true;
  2524. }
  2525. }
  2526. }
  2527. unset($byCompany[$cn]['lines_map']);
  2528. $byCompany[$cn]['lines'] = $lines;
  2529. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2530. $byCompany[$cn]['line_count'] = $total;
  2531. $byCompany[$cn]['has_total'] = $total > 0;
  2532. $byCompany[$cn]['has_remark'] = $total > 0;
  2533. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2534. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2535. // 工序行 + 备注行 + 总计行
  2536. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2537. }
  2538. $groups = array_values($byCompany);
  2539. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2540. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  2541. }
  2542. /**
  2543. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2544. *
  2545. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2546. * @return array<int, array<string, mixed>>
  2547. */
  2548. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2549. {
  2550. $sids = [];
  2551. $poIdMap = [];
  2552. foreach ($bundle['pos'] ?? [] as $po) {
  2553. if (!is_array($po)) {
  2554. continue;
  2555. }
  2556. $sid = (int)($po['scydgy_id'] ?? 0);
  2557. if ($this->isValidScydgyRowId($sid)) {
  2558. $sids[$sid] = true;
  2559. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2560. }
  2561. }
  2562. if ($sids === []) {
  2563. return [];
  2564. }
  2565. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2566. $gymcMap = [];
  2567. $qtyBySid = [];
  2568. $orderedSids = [];
  2569. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2570. if (!is_array($mr)) {
  2571. continue;
  2572. }
  2573. $gid = $this->extractScydgyRowId($mr);
  2574. if ($this->isValidScydgyRowId($gid)) {
  2575. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2576. $orderedSids[] = $gid;
  2577. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2578. if ($qty === '') {
  2579. $qty = trim((string)($mr['NGZL'] ?? ''));
  2580. }
  2581. $qtyBySid[$gid] = $qty;
  2582. }
  2583. }
  2584. foreach ($bundle['pos'] ?? [] as $po) {
  2585. if (!is_array($po)) {
  2586. continue;
  2587. }
  2588. $gid = (int)($po['scydgy_id'] ?? 0);
  2589. if ($this->isValidScydgyRowId($gid)) {
  2590. $nm = trim((string)($po['CGYMC'] ?? ''));
  2591. if ($nm !== '') {
  2592. $gymcMap[$gid] = $nm;
  2593. }
  2594. }
  2595. }
  2596. try {
  2597. $details = Db::table('purchase_order_detail')
  2598. ->where('scydgy_id', 'in', array_keys($sids))
  2599. ->order('company_name', 'asc')
  2600. ->order('id', 'asc')
  2601. ->select();
  2602. } catch (\Throwable $e) {
  2603. try {
  2604. $details = Db::table('purchase_order_detail')
  2605. ->where('scydgy_id', 'in', array_keys($sids))
  2606. ->order('company_name', 'asc')
  2607. ->order('ID', 'asc')
  2608. ->select();
  2609. } catch (\Throwable $e2) {
  2610. $details = [];
  2611. }
  2612. }
  2613. if (!is_array($details)) {
  2614. $details = [];
  2615. }
  2616. $byCompany = [];
  2617. foreach ($details as $d) {
  2618. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2619. continue;
  2620. }
  2621. $cn = trim((string)($d['company_name'] ?? ''));
  2622. if ($cn === '') {
  2623. continue;
  2624. }
  2625. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2626. $sid = (int)($d['scydgy_id'] ?? 0);
  2627. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2628. continue;
  2629. }
  2630. if (!isset($byCompany[$cn])) {
  2631. $ph = trim((string)($d['phone'] ?? ''));
  2632. $username = trim((string)($d['username'] ?? ''));
  2633. if ($username === '') {
  2634. $username = $this->resolveCustomerContactName($ph, $cn);
  2635. }
  2636. $byCompany[$cn] = [
  2637. 'name' => $cn,
  2638. 'email' => trim((string)($d['email'] ?? '')),
  2639. 'phone' => $ph,
  2640. 'username' => $username,
  2641. 'remark' => '',
  2642. 'pick_lines' => [],
  2643. 'detail_picks' => [],
  2644. ];
  2645. }
  2646. if ($byCompany[$cn]['remark'] === '') {
  2647. $rm = '';
  2648. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2649. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2650. $rm = trim((string)$d[$rk]);
  2651. break;
  2652. }
  2653. }
  2654. if ($rm !== '') {
  2655. $byCompany[$cn]['remark'] = $rm;
  2656. }
  2657. }
  2658. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2659. if ($gymc === '') {
  2660. $gymc = '工序';
  2661. }
  2662. $am = trim((string)($d['amount'] ?? ''));
  2663. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2664. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2665. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2666. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2667. $deliveryShow = $deliveryRaw;
  2668. }
  2669. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2670. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2671. $subtotal = null;
  2672. if ($amountNum !== null) {
  2673. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2674. }
  2675. $unitPriceText = $amountFilled
  2676. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2677. : '未填写';
  2678. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2679. $leadFilled = ($leadDays !== null);
  2680. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2681. $pickLine = [
  2682. 'cgymc' => $gymc,
  2683. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  2684. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2685. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2686. 'amount_filled' => $amountFilled,
  2687. 'delivery_filled' => $deliveryFilled,
  2688. 'unit_price_text' => $unitPriceText,
  2689. 'lead_days' => $leadFilled ? $leadDays : '',
  2690. 'lead_days_filled'=> $leadFilled,
  2691. 'lead_days_show' => $leadText,
  2692. 'lead_days_text' => $leadText,
  2693. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2694. 'subtotal_num' => $subtotal,
  2695. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2696. 'is_quoted' => $amountFilled,
  2697. ];
  2698. if (!$quoteVisible) {
  2699. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2700. }
  2701. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2702. $byCompany[$cn]['detail_picks'][$sid] = [
  2703. 'scydgy_id' => $sid,
  2704. 'detail_id' => $detailId,
  2705. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2706. 'cgymc' => $gymc,
  2707. ];
  2708. }
  2709. $out = [];
  2710. foreach ($byCompany as $g) {
  2711. $pickLinesMap = $g['pick_lines'] ?? [];
  2712. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2713. continue;
  2714. }
  2715. $pickLines = [];
  2716. $usedLineSids = [];
  2717. foreach ($orderedSids as $sid) {
  2718. if (!isset($pickLinesMap[$sid])) {
  2719. continue;
  2720. }
  2721. $pickLines[] = $pickLinesMap[$sid];
  2722. $usedLineSids[$sid] = true;
  2723. }
  2724. foreach ($pickLinesMap as $sid => $ln) {
  2725. if (isset($usedLineSids[$sid])) {
  2726. continue;
  2727. }
  2728. $pickLines[] = $ln;
  2729. }
  2730. $groupTotal = 0.0;
  2731. $groupHasTotal = false;
  2732. if ($quoteVisible) {
  2733. foreach ($pickLines as $ln) {
  2734. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2735. $groupTotal += (float)$ln['subtotal_num'];
  2736. $groupHasTotal = true;
  2737. }
  2738. }
  2739. }
  2740. $lineCount = count($pickLines);
  2741. $g['pick_lines'] = $pickLines;
  2742. $g['line_count'] = $lineCount;
  2743. $g['has_total'] = $lineCount > 0;
  2744. $g['has_remark'] = $lineCount > 0;
  2745. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2746. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2747. // 工序行 + 备注行 + 总计行
  2748. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2749. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2750. $detailPicks = [];
  2751. $usedPickSids = [];
  2752. foreach ($orderedSids as $sid) {
  2753. if (!isset($detailPicksMap[$sid])) {
  2754. continue;
  2755. }
  2756. $detailPicks[] = $detailPicksMap[$sid];
  2757. $usedPickSids[$sid] = true;
  2758. }
  2759. foreach ($detailPicksMap as $sid => $dp) {
  2760. if (isset($usedPickSids[$sid])) {
  2761. continue;
  2762. }
  2763. $detailPicks[] = $dp;
  2764. }
  2765. $g['detail_picks'] = $detailPicks;
  2766. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2767. unset($g['detail_picks']);
  2768. $out[] = $g;
  2769. }
  2770. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2771. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  2772. }
  2773. /**
  2774. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2775. * @return array<int, int[]> scydgy_id => detail_id[]
  2776. */
  2777. protected function mapDetailIdsByScydgyId(array $details): array
  2778. {
  2779. $out = [];
  2780. foreach ($details as $d) {
  2781. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2782. continue;
  2783. }
  2784. $sid = (int)($d['scydgy_id'] ?? 0);
  2785. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2786. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2787. continue;
  2788. }
  2789. if (!isset($out[$sid])) {
  2790. $out[$sid] = [];
  2791. }
  2792. $out[$sid][] = $pk;
  2793. }
  2794. foreach ($out as $sid => $ids) {
  2795. $out[$sid] = array_values(array_unique($ids));
  2796. }
  2797. return $out;
  2798. }
  2799. /**
  2800. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2801. *
  2802. * @param array<string, mixed> $dbRow
  2803. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2804. */
  2805. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2806. {
  2807. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2808. $r = [
  2809. 'ID' => $sid,
  2810. 'scydgy_id' => $sid,
  2811. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2812. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2813. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2814. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2815. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2816. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2817. 'CDW' => $dbRow['CDW'] ?? '',
  2818. 'NGZL' => $dbRow['NGZL'] ?? '',
  2819. 'CDF' => $dbRow['CDF'] ?? '',
  2820. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2821. 'MBZ' => $dbRow['MBZ'] ?? '',
  2822. 'bwjg' => $dbRow['bwjg'] ?? '',
  2823. 'iStatus' => $dbRow['iStatus'] ?? '',
  2824. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2825. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2826. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2827. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2828. 'dStamp' => $dbRow['dStamp'] ?? '',
  2829. 'pick_time' => $dbRow['pick_time'] ?? '',
  2830. ];
  2831. if ($sid > 0 && isset($dStampMap[$sid])) {
  2832. $t = trim((string)$dStampMap[$sid]);
  2833. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2834. $r['dStamp'] = $dStampMap[$sid];
  2835. }
  2836. }
  2837. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2838. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2839. $ct = $dbRow['createtime'];
  2840. if (is_numeric($ct) && (int)$ct > 946684800) {
  2841. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2842. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2843. $r['dStamp'] = trim($ct);
  2844. }
  2845. }
  2846. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2847. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2848. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2849. $fallback = trim((string)($r['dStamp'] ?? ''));
  2850. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2851. $r['dputrecord'] = $fallback;
  2852. }
  2853. }
  2854. if (array_key_exists('id', $dbRow)) {
  2855. $r['purchase_order_id'] = (int)$dbRow['id'];
  2856. }
  2857. if ($sid < 0) {
  2858. $r['_is_manual'] = 1;
  2859. }
  2860. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2861. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2862. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2863. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2864. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2865. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2866. $r['pick_time'] = $pickFallback;
  2867. break;
  2868. }
  2869. }
  2870. }
  2871. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2872. if ($pickNm !== '') {
  2873. $r['pick_company_name'] = $pickNm;
  2874. $r['picked_supplier_name'] = $pickNm;
  2875. }
  2876. return $r;
  2877. }
  2878. /**
  2879. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2880. *
  2881. * @return array<int, array<string, mixed>>
  2882. */
  2883. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2884. {
  2885. $pool = [];
  2886. if (!is_array($dbRows) || $dbRows === []) {
  2887. return $pool;
  2888. }
  2889. $dStampMap = [];
  2890. $sidList = [];
  2891. foreach ($dbRows as $tmpRow) {
  2892. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2893. $sid = (int)$tmpRow['scydgy_id'];
  2894. if ($sid > 0) {
  2895. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2896. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2897. $sidList[$sid] = true;
  2898. }
  2899. }
  2900. }
  2901. }
  2902. if ($sidList !== []) {
  2903. try {
  2904. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2905. } catch (\Throwable $e) {
  2906. $dStampMap = [];
  2907. }
  2908. }
  2909. foreach ($dbRows as $dbRow) {
  2910. if (!is_array($dbRow)) {
  2911. continue;
  2912. }
  2913. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2914. }
  2915. return $pool;
  2916. }
  2917. /**
  2918. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2919. *
  2920. * @param int[] $scydgyIds
  2921. * @return array<int, array<string, mixed>>
  2922. */
  2923. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2924. {
  2925. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2926. if ($scydgyIds === []) {
  2927. return [];
  2928. }
  2929. try {
  2930. $list = Db::table('purchase_order_detail')
  2931. ->where('scydgy_id', 'in', $scydgyIds)
  2932. ->field('scydgy_id,company_name,amount,delivery')
  2933. ->select();
  2934. } catch (\Throwable $e) {
  2935. $list = [];
  2936. }
  2937. return is_array($list) ? $list : [];
  2938. }
  2939. /**
  2940. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2941. *
  2942. * @param int[] $scydgyIds
  2943. * @param array<int, array<string, mixed>> $allRows
  2944. * @return array{cnt:int, amt:int, deliv:int}
  2945. */
  2946. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2947. {
  2948. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2949. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2950. if ($scydgyIds === [] || $allRows === []) {
  2951. return $out;
  2952. }
  2953. $idSet = array_flip($scydgyIds);
  2954. $all = [];
  2955. $withAmt = [];
  2956. $withDeliv = [];
  2957. foreach ($allRows as $r) {
  2958. if (!is_array($r)) {
  2959. continue;
  2960. }
  2961. $sid = (int)($r['scydgy_id'] ?? 0);
  2962. if (!isset($idSet[$sid])) {
  2963. continue;
  2964. }
  2965. $cn = trim((string)($r['company_name'] ?? ''));
  2966. if ($cn === '') {
  2967. continue;
  2968. }
  2969. $all[$cn] = true;
  2970. $am = $r['amount'] ?? null;
  2971. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2972. $withAmt[$cn] = true;
  2973. }
  2974. $dv = $r['delivery'] ?? null;
  2975. if ($dv !== null && trim((string)$dv) !== '') {
  2976. $withDeliv[$cn] = true;
  2977. }
  2978. }
  2979. return [
  2980. 'cnt' => count($all),
  2981. 'amt' => count($withAmt),
  2982. 'deliv' => count($withDeliv),
  2983. ];
  2984. }
  2985. /**
  2986. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2987. *
  2988. * @param int[] $scydgyIds
  2989. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2990. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2991. */
  2992. protected function OrderDetailSummary(array $scydgyIds)
  2993. {
  2994. $out = [];
  2995. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2996. if ($scydgyIds === []) {
  2997. return $out;
  2998. }
  2999. $list = [];
  3000. try {
  3001. $list = Db::table('purchase_order_detail')
  3002. ->where('scydgy_id', 'in', $scydgyIds)
  3003. ->field('id,scydgy_id,amount,delivery')
  3004. ->select();
  3005. } catch (\Throwable $e) {
  3006. $list = [];
  3007. }
  3008. if (!is_array($list)) {
  3009. return $out;
  3010. }
  3011. foreach ($list as $r) {
  3012. if (!is_array($r)) {
  3013. continue;
  3014. }
  3015. $ids = (int)($r['scydgy_id'] ?? 0);
  3016. if (!$this->isValidScydgyRowId($ids)) {
  3017. continue;
  3018. }
  3019. if (!isset($out[$ids])) {
  3020. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3021. }
  3022. $out[$ids]['cnt']++;
  3023. $am = $r['amount'] ?? null;
  3024. if ($am !== null && $am !== '') {
  3025. if (!(is_string($am) && trim($am) === '')) {
  3026. $out[$ids]['amt']++;
  3027. }
  3028. }
  3029. $dv = $r['delivery'] ?? null;
  3030. if ($dv !== null && trim((string)$dv) !== '') {
  3031. $out[$ids]['deliv']++;
  3032. }
  3033. }
  3034. return $out;
  3035. }
  3036. /**
  3037. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3038. *
  3039. * @return array
  3040. */
  3041. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3042. {
  3043. $strContains = function ($haystack, $needle) {
  3044. if ($needle === '') {
  3045. return false;
  3046. }
  3047. $haystack = (string)$haystack;
  3048. if (function_exists('mb_stripos')) {
  3049. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3050. }
  3051. return stripos($haystack, $needle) !== false;
  3052. };
  3053. $stripAlias = function ($f) {
  3054. return preg_replace('/^[ab]\./i', '', (string)$f);
  3055. };
  3056. $searchColNames = [];
  3057. foreach (explode(',', $this->searchFields) as $colRaw) {
  3058. $c = $stripAlias(trim($colRaw));
  3059. if ($c !== '') {
  3060. $searchColNames[] = $c;
  3061. }
  3062. }
  3063. $filtered = [];
  3064. foreach ($pool as $r) {
  3065. if (!is_array($r)) {
  3066. continue;
  3067. }
  3068. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3069. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3070. if (!$isManual) {
  3071. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3072. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3073. continue;
  3074. }
  3075. if ($applyMonthRange) {
  3076. $mo = (int)$m[2];
  3077. if ($mo < 1 || $mo > 12) {
  3078. continue;
  3079. }
  3080. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3081. $rowMonthStart = $ymRow . '-01 00:00:00';
  3082. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3083. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3084. continue;
  3085. }
  3086. }
  3087. } elseif ($applyMonthRange) {
  3088. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3089. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3090. $ds = $listTime;
  3091. }
  3092. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3093. continue;
  3094. }
  3095. $mo = (int)$m[2];
  3096. if ($mo < 1 || $mo > 12) {
  3097. continue;
  3098. }
  3099. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3100. $rowMonthStart = $ymRow . '-01 00:00:00';
  3101. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3102. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3103. continue;
  3104. }
  3105. }
  3106. if ($search !== '') {
  3107. $hitSearch = false;
  3108. foreach ($searchColNames as $c) {
  3109. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3110. if ($cell !== '' && $strContains($cell, $search)) {
  3111. $hitSearch = true;
  3112. break;
  3113. }
  3114. }
  3115. if (!$hitSearch) {
  3116. continue;
  3117. }
  3118. }
  3119. foreach ($filterArr as $fk => $fv) {
  3120. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3121. continue;
  3122. }
  3123. if (is_array($fv)) {
  3124. continue;
  3125. }
  3126. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3127. continue;
  3128. }
  3129. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3130. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3131. $field = $stripAlias($fk);
  3132. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3133. $cellStr = trim((string)$cell);
  3134. switch ($sym) {
  3135. case '=':
  3136. if ((string)$cell !== (string)$fv) {
  3137. continue 3;
  3138. }
  3139. break;
  3140. case '<>':
  3141. if ((string)$cell === (string)$fv) {
  3142. continue 3;
  3143. }
  3144. break;
  3145. case 'LIKE':
  3146. case 'NOT LIKE':
  3147. $needle = trim((string)$fv);
  3148. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3149. if ($sym === 'LIKE' && !$hit) {
  3150. continue 3;
  3151. }
  3152. if ($sym === 'NOT LIKE' && $hit) {
  3153. continue 3;
  3154. }
  3155. break;
  3156. case '>':
  3157. case '>=':
  3158. case '<':
  3159. case '<=':
  3160. if (!is_numeric($cell) && $cellStr === '') {
  3161. continue 3;
  3162. }
  3163. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  3164. $vv = (float)$fv;
  3165. if ($sym === '>' && !($cv > $vv)) {
  3166. continue 3;
  3167. }
  3168. if ($sym === '>=' && !($cv >= $vv)) {
  3169. continue 3;
  3170. }
  3171. if ($sym === '<' && !($cv < $vv)) {
  3172. continue 3;
  3173. }
  3174. if ($sym === '<=' && !($cv <= $vv)) {
  3175. continue 3;
  3176. }
  3177. break;
  3178. case 'RANGE':
  3179. case 'NOT RANGE':
  3180. case 'BETWEEN':
  3181. case 'NOT BETWEEN':
  3182. case 'BETWEEN TIME':
  3183. case 'NOT BETWEEN TIME':
  3184. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  3185. $rawR = str_replace(' - ', ',', $rawR);
  3186. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  3187. if (count($arr) < 2) {
  3188. break;
  3189. }
  3190. $lo = $arr[0];
  3191. $hi = $arr[1];
  3192. if ($lo === '' && $hi === '') {
  3193. break;
  3194. }
  3195. $isNot = (strpos($sym, 'NOT') !== false);
  3196. if ($lo === '') {
  3197. $in = ($cellStr !== '' && $cellStr <= $hi);
  3198. if ($isNot ? $in : !$in) {
  3199. continue 3;
  3200. }
  3201. break;
  3202. }
  3203. if ($hi === '') {
  3204. $in = ($cellStr !== '' && $cellStr >= $lo);
  3205. if ($isNot ? $in : !$in) {
  3206. continue 3;
  3207. }
  3208. break;
  3209. }
  3210. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3211. if ($isNot ? $in : !$in) {
  3212. continue 3;
  3213. }
  3214. break;
  3215. case 'NULL':
  3216. case 'IS NULL':
  3217. if ($cell !== null && $cell !== '') {
  3218. continue 3;
  3219. }
  3220. break;
  3221. case 'NOT NULL':
  3222. case 'IS NOT NULL':
  3223. if ($cell === null || $cell === '') {
  3224. continue 3;
  3225. }
  3226. break;
  3227. default:
  3228. break;
  3229. }
  3230. }
  3231. $filtered[] = $r;
  3232. }
  3233. return $filtered;
  3234. }
  3235. /**
  3236. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3237. */
  3238. public function snapshotToProcure()
  3239. {
  3240. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3241. $this->error(__('Invalid parameters'));
  3242. }
  3243. $row = json_decode($this->request->post('row_json', ''), true);
  3244. if (!is_array($row)) {
  3245. $this->error(__('Invalid parameters'));
  3246. }
  3247. try {
  3248. $ids = $this->extractScydgyRowId($row);
  3249. if (!$this->isValidScydgyRowId($ids)) {
  3250. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3251. }
  3252. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3253. $data = [
  3254. 'scydgy_id' => $ids,
  3255. 'CCYDH' => $row['CCYDH'] ?? null,
  3256. 'CYJMC' => $row['CYJMC'] ?? null,
  3257. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3258. 'CDXMC' => $row['CDXMC'] ?? null,
  3259. 'CGYBH' => $row['CGYBH'] ?? null,
  3260. 'CGYMC' => $row['CGYMC'] ?? null,
  3261. 'CDW' => $row['CDW'] ?? null,
  3262. 'NGZL' => $row['NGZL'] ?? null,
  3263. 'CDF' => $row['CDF'] ?? null,
  3264. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3265. 'MBZ' => $row['MBZ'] ?? null,
  3266. 'bwjg' => $row['bwjg'] ?? null,
  3267. 'iStatus' => $row['iStatus'] ?? null,
  3268. 'dStamp' => $row['dStamp'] ?? null,
  3269. 'dputrecord' => $row['dputrecord'] ?? null,
  3270. 'cywyxm' => $row['cywyxm'] ?? null,
  3271. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3272. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3273. ];
  3274. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3275. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3276. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3277. $this->success('操作成功');
  3278. return;
  3279. }
  3280. if ($exists) {
  3281. $upd = $data;
  3282. unset($upd['scydgy_id'], $upd['status']);
  3283. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3284. } else {
  3285. // 新增:不写 status(空/走库默认);仅写创建时间
  3286. $data['createtime'] = date('Y-m-d H:i:s');
  3287. Db::table('purchase_order')->insert($data);
  3288. }
  3289. } catch (\Throwable $e) {
  3290. $this->error($e->getMessage());
  3291. }
  3292. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3293. $this->success('操作成功');
  3294. }
  3295. /**
  3296. * 未发列表
  3297. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3298. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3299. */
  3300. public function completeDirectly()
  3301. {
  3302. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3303. $this->error(__('参数错误'));
  3304. }
  3305. if (!$this->procuremenCanComplete()) {
  3306. $this->error(__('You have no permission'));
  3307. }
  3308. $row = json_decode($this->request->post('row_json', ''), true);
  3309. if (!is_array($row)) {
  3310. $this->error(__('Invalid parameters'));
  3311. }
  3312. $finishRaw = $this->request->post('finish', '1');
  3313. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3314. $poIdLog = null;
  3315. try {
  3316. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3317. $ids = $this->extractScydgyRowId($row);
  3318. if (!$this->isValidScydgyRowId($ids)) {
  3319. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3320. }
  3321. if ($asComplete) {
  3322. $this->assertPickRowCanComplete($ids, $row);
  3323. }
  3324. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3325. $data = [
  3326. 'scydgy_id' => $ids,
  3327. 'CCYDH' => $row['CCYDH'] ?? null,
  3328. 'CYJMC' => $row['CYJMC'] ?? null,
  3329. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3330. 'CDXMC' => $row['CDXMC'] ?? null,
  3331. 'CGYBH' => $row['CGYBH'] ?? null,
  3332. 'CGYMC' => $row['CGYMC'] ?? null,
  3333. 'CDW' => $row['CDW'] ?? null,
  3334. 'NGZL' => $row['NGZL'] ?? null,
  3335. 'CDF' => $row['CDF'] ?? null,
  3336. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3337. 'MBZ' => $row['MBZ'] ?? null,
  3338. 'bwjg' => $row['bwjg'] ?? null,
  3339. 'iStatus' => $row['iStatus'] ?? null,
  3340. 'dStamp' => $row['dStamp'] ?? null,
  3341. 'dputrecord' => $row['dputrecord'] ?? null,
  3342. 'cywyxm' => $row['cywyxm'] ?? null,
  3343. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3344. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3345. ];
  3346. if ($asComplete) {
  3347. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3348. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3349. }
  3350. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3351. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3352. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3353. $this->success('操作成功');
  3354. return;
  3355. }
  3356. if ($exists) {
  3357. $upd = $data;
  3358. unset($upd['scydgy_id']);
  3359. if (!$asComplete) {
  3360. unset($upd['status']);
  3361. }
  3362. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3363. } else {
  3364. // 新增:不写 status;完结时 $data 已含 status=1
  3365. $data['createtime'] = date('Y-m-d H:i:s');
  3366. Db::table('purchase_order')->insert($data);
  3367. }
  3368. } catch (\Throwable $e) {
  3369. $this->error($e->getMessage());
  3370. }
  3371. try {
  3372. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3373. if (is_array($rpo)) {
  3374. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3375. $poIdLog = $tid > 0 ? $tid : null;
  3376. }
  3377. } catch (\Throwable $e) {
  3378. $poIdLog = null;
  3379. }
  3380. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3381. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3382. if ($asComplete) {
  3383. $this->addOrderLog(
  3384. $ids,
  3385. 'mark_complete',
  3386. '点击「完结」,已标记为已完结',
  3387. $poIdLog
  3388. );
  3389. try {
  3390. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3391. if ($pdfPublicPath === '') {
  3392. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3393. }
  3394. } catch (\Throwable $e) {
  3395. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3396. }
  3397. } else {
  3398. $this->addOrderLog(
  3399. $ids,
  3400. 'save_qty_price',
  3401. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3402. $poIdLog
  3403. );
  3404. }
  3405. $this->pickHiddenScydgySetCache = null;
  3406. $this->success("操作成功");
  3407. }
  3408. /**
  3409. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3410. *
  3411. * @param array<int, array> $rows 引用传递当前页行
  3412. */
  3413. protected function mergePurchaseOrder(array &$rows)
  3414. {
  3415. if ($rows === []) {
  3416. return;
  3417. }
  3418. $ids = [];
  3419. foreach ($rows as $rw) {
  3420. if (!is_array($rw)) {
  3421. continue;
  3422. }
  3423. $id = (int)($rw['ID'] ?? 0);
  3424. if ($id > 0) {
  3425. $ids[$id] = true;
  3426. }
  3427. }
  3428. $idList = array_keys($ids);
  3429. if ($idList === []) {
  3430. return;
  3431. }
  3432. try {
  3433. $list = Db::table('purchase_order')
  3434. ->where('scydgy_id', 'in', $idList)
  3435. ->field('scydgy_id,This_quantity,ceilingPrice')
  3436. ->select();
  3437. } catch (\Throwable $e) {
  3438. return;
  3439. }
  3440. if (!is_array($list)) {
  3441. return;
  3442. }
  3443. $byId = [];
  3444. foreach ($list as $dbRow) {
  3445. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3446. continue;
  3447. }
  3448. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3449. }
  3450. foreach ($rows as &$rw) {
  3451. if (!is_array($rw)) {
  3452. continue;
  3453. }
  3454. $sid = (int)($rw['ID'] ?? 0);
  3455. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3456. continue;
  3457. }
  3458. $db = $byId[$sid];
  3459. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3460. if (array_key_exists('This_quantity', $db)) {
  3461. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3462. }
  3463. if (array_key_exists('ceilingPrice', $db)) {
  3464. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3465. } elseif (array_key_exists('ceiling_price', $db)) {
  3466. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3467. }
  3468. }
  3469. unset($rw);
  3470. }
  3471. /**
  3472. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3473. */
  3474. public function purchaseConfirmPick()
  3475. {
  3476. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3477. $this->error(__('Invalid parameters'));
  3478. }
  3479. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3480. $this->error(__('You have no permission'));
  3481. }
  3482. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3483. if ($batchRaw !== '') {
  3484. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3485. return;
  3486. }
  3487. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3488. $sid = (int)$scydgyId;
  3489. if (!$this->isValidScydgyRowId($sid)) {
  3490. $this->error('参数无效');
  3491. }
  3492. $parseIdList = function ($raw) {
  3493. if (is_array($raw)) {
  3494. $arr = $raw;
  3495. } else {
  3496. $decoded = json_decode((string)$raw, true);
  3497. $arr = is_array($decoded) ? $decoded : [];
  3498. }
  3499. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3500. };
  3501. $selectedRaw = $this->request->post('selected_ids', null);
  3502. if ($selectedRaw === null || $selectedRaw === '') {
  3503. $legacy = (int)$this->request->post('selected_id', 0);
  3504. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3505. } else {
  3506. $selectedIds = $parseIdList($selectedRaw);
  3507. }
  3508. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3509. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3510. try {
  3511. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3512. } catch (\InvalidArgumentException $e) {
  3513. $this->error($e->getMessage());
  3514. } catch (\Throwable $e) {
  3515. $this->error($e->getMessage());
  3516. }
  3517. $this->pickHiddenScydgySetCache = null;
  3518. $this->success('操作成功', '', $result);
  3519. }
  3520. /**
  3521. * 整单采购确认(多道工序一次提交)
  3522. */
  3523. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3524. {
  3525. $decoded = json_decode($batchRaw, true);
  3526. if (!is_array($decoded) || $decoded === []) {
  3527. $this->error('提交数据无效');
  3528. }
  3529. $picks = [];
  3530. foreach ($decoded as $item) {
  3531. if (!is_array($item)) {
  3532. continue;
  3533. }
  3534. $sid = (int)($item['scydgy_id'] ?? 0);
  3535. if (!$this->isValidScydgyRowId($sid)) {
  3536. continue;
  3537. }
  3538. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3539. if (!is_array($sel)) {
  3540. $sel = [(int)$sel];
  3541. }
  3542. $unsel = $item['unselected_ids'] ?? [];
  3543. if (!is_array($unsel)) {
  3544. $unsel = json_decode((string)$unsel, true);
  3545. $unsel = is_array($unsel) ? $unsel : [];
  3546. }
  3547. $picks[] = [
  3548. 'scydgy_id' => $sid,
  3549. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3550. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3551. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3552. ];
  3553. }
  3554. if ($picks === []) {
  3555. $this->error('提交数据无效');
  3556. }
  3557. Db::startTrans();
  3558. $results = [];
  3559. try {
  3560. foreach ($picks as $pick) {
  3561. $results[] = $this->runPurchaseConfirmPick(
  3562. (int)$pick['scydgy_id'],
  3563. $pick['selected_ids'],
  3564. $pick['unselected_ids'],
  3565. (int)$pick['purchase_order_id'],
  3566. false,
  3567. false
  3568. );
  3569. }
  3570. Db::commit();
  3571. } catch (\Throwable $e) {
  3572. Db::rollback();
  3573. $msg = $e->getMessage();
  3574. $this->error($msg !== '' ? $msg : '提交失败');
  3575. }
  3576. try {
  3577. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3578. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3579. } catch (\Throwable $e) {
  3580. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3581. }
  3582. $this->pickHiddenScydgySetCache = null;
  3583. $this->success('操作成功', '', ['batch' => $results]);
  3584. }
  3585. /**
  3586. * @return array<string, mixed>
  3587. */
  3588. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3589. {
  3590. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3591. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3592. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3593. $scydgyId = (string)$sid;
  3594. if ($selectedIds === []) {
  3595. throw new \InvalidArgumentException('请至少勾选一条明细');
  3596. }
  3597. $inter = array_intersect($selectedIds, $unselectedIds);
  3598. if ($inter !== []) {
  3599. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3600. }
  3601. $allIds = $this->purchaseOrderDetail($sid);
  3602. if ($allIds === []) {
  3603. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3604. }
  3605. foreach ($selectedIds as $id) {
  3606. if (!in_array($id, $allIds, true)) {
  3607. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3608. }
  3609. }
  3610. foreach ($unselectedIds as $id) {
  3611. if (!in_array($id, $allIds, true)) {
  3612. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3613. }
  3614. }
  3615. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3616. sort($union, SORT_NUMERIC);
  3617. $expect = $allIds;
  3618. sort($expect, SORT_NUMERIC);
  3619. if ($union !== $expect) {
  3620. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3621. }
  3622. if ($manageTransaction) {
  3623. Db::startTrans();
  3624. }
  3625. try {
  3626. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3627. $aff = 0;
  3628. try {
  3629. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3630. } catch (\Throwable $e) {
  3631. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3632. }
  3633. if ($aff < 1) {
  3634. throw new \Exception('更新选中状态失败');
  3635. }
  3636. $poPayload = [
  3637. 'status' => ProcuremenStatus::PO_COMPLETED,
  3638. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3639. ];
  3640. if ($purchaseOrderId > 0) {
  3641. $poAff = (int)Db::table('purchase_order')
  3642. ->where('id', $purchaseOrderId)
  3643. ->where('scydgy_id', $sid)
  3644. ->update($poPayload);
  3645. if ($poAff < 1) {
  3646. throw new \Exception('主表订单不存在或与工序行不匹配');
  3647. }
  3648. } else {
  3649. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3650. if ($poAff < 1) {
  3651. throw new \Exception('未找到');
  3652. }
  3653. }
  3654. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3655. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3656. if ($manageTransaction) {
  3657. Db::commit();
  3658. }
  3659. } catch (\Throwable $e) {
  3660. if ($manageTransaction) {
  3661. Db::rollback();
  3662. }
  3663. throw $e;
  3664. }
  3665. $poIdFinal = $purchaseOrderId;
  3666. if ($poIdFinal <= 0) {
  3667. try {
  3668. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3669. if (is_array($rpo)) {
  3670. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3671. }
  3672. } catch (\Throwable $e) {
  3673. $poIdFinal = 0;
  3674. }
  3675. }
  3676. $pickNames = [];
  3677. foreach ($selectedIds as $pid) {
  3678. $dr = $this->purchaseOrderDetai($sid, $pid);
  3679. $nm = trim((string)($dr['company_name'] ?? ''));
  3680. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3681. }
  3682. $this->addOrderLog(
  3683. $sid,
  3684. 'purchase_confirm',
  3685. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3686. $poIdFinal > 0 ? $poIdFinal : null
  3687. );
  3688. if ($sendNotifications) {
  3689. try {
  3690. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3691. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3692. 'scydgy_id' => $sid,
  3693. 'selected_ids' => $selectedIds,
  3694. 'unselected_ids' => $unselectedIds,
  3695. 'purchase_order_id' => $purchaseOrderId,
  3696. ]]);
  3697. } catch (\Throwable $e) {
  3698. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3699. }
  3700. }
  3701. Log::write(sprintf(
  3702. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3703. $scydgyId,
  3704. $purchaseOrderId,
  3705. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3706. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3707. ), 'notice');
  3708. $pdfPublicPath = '';
  3709. try {
  3710. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3711. } catch (\Throwable $e) {
  3712. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3713. }
  3714. return [
  3715. 'scydgy_id' => $scydgyId,
  3716. 'purchase_order_id' => $purchaseOrderId,
  3717. 'selected_ids' => $selectedIds,
  3718. 'unselected_ids' => $unselectedIds,
  3719. 'purchase_confirm_pdf' => $pdfPublicPath,
  3720. ];
  3721. }
  3722. /**
  3723. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3724. *
  3725. * @param int[]|string[] $scydgyIds
  3726. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3727. */
  3728. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3729. {
  3730. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3731. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3732. if ($scydgyIds === []) {
  3733. return $empty;
  3734. }
  3735. $pos = [];
  3736. try {
  3737. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3738. } catch (\Throwable $e) {
  3739. $rows = [];
  3740. }
  3741. if (is_array($rows)) {
  3742. foreach ($rows as $po) {
  3743. if (is_array($po)) {
  3744. $pos[] = $po;
  3745. }
  3746. }
  3747. }
  3748. if ($pos === []) {
  3749. return $empty;
  3750. }
  3751. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3752. return [
  3753. 'ccydh' => $ccydh,
  3754. 'pos' => $pos,
  3755. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3756. ];
  3757. }
  3758. /**
  3759. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3760. *
  3761. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3762. * @param array<int, array<string, mixed>> $picks
  3763. */
  3764. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3765. {
  3766. if ($picks === []) {
  3767. return;
  3768. }
  3769. $fallbackDetailId = 0;
  3770. $winners = [];
  3771. $losers = [];
  3772. foreach ($picks as $pick) {
  3773. if (!is_array($pick)) {
  3774. continue;
  3775. }
  3776. $sid = (int)($pick['scydgy_id'] ?? 0);
  3777. if (!$this->isValidScydgyRowId($sid)) {
  3778. continue;
  3779. }
  3780. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3781. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3782. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3783. $fallbackDetailId = (int)$selectedIds[0];
  3784. }
  3785. foreach ($selectedIds as $pid) {
  3786. $dr = $this->purchaseOrderDetai($sid, $pid);
  3787. if (!is_array($dr)) {
  3788. continue;
  3789. }
  3790. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3791. }
  3792. foreach ($unselectedIds as $pid) {
  3793. $dr = $this->purchaseOrderDetai($sid, $pid);
  3794. if (!is_array($dr)) {
  3795. continue;
  3796. }
  3797. $key = $this->notifySupplierDedupeKey($dr);
  3798. if (!isset($winners[$key])) {
  3799. $losers[$key] = $dr;
  3800. }
  3801. }
  3802. }
  3803. if ($winners === [] && $losers === []) {
  3804. return;
  3805. }
  3806. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3807. $sendSmsSafe = function ($phone, $content) {
  3808. $phone = trim((string)$phone);
  3809. if ($phone === '') {
  3810. return;
  3811. }
  3812. try {
  3813. $this->smsbao($phone, $content);
  3814. } catch (\Throwable $e) {
  3815. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3816. }
  3817. };
  3818. foreach ($winners as $dr) {
  3819. $cname = trim((string)($dr['company_name'] ?? ''));
  3820. $ph = trim((string)($dr['phone'] ?? ''));
  3821. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3822. 'company_name' => $cname,
  3823. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3824. 'phone' => $ph,
  3825. ]));
  3826. $sendSmsSafe($ph, $sms);
  3827. }
  3828. foreach ($losers as $dr) {
  3829. $cname = trim((string)($dr['company_name'] ?? ''));
  3830. $ph = trim((string)($dr['phone'] ?? ''));
  3831. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3832. 'company_name' => $cname,
  3833. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3834. 'phone' => $ph,
  3835. ]));
  3836. $sendSmsSafe($ph, $sms);
  3837. }
  3838. }
  3839. /**
  3840. * 短信去重键:优先手机号,否则公司名
  3841. */
  3842. protected function notifySupplierDedupeKey(array $detailRow): string
  3843. {
  3844. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3845. if ($ph !== '') {
  3846. return 'p:' . $ph;
  3847. }
  3848. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3849. return 'c:' . $cn;
  3850. }
  3851. /**
  3852. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3853. *
  3854. * @param int[] $detailIds
  3855. */
  3856. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3857. {
  3858. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3859. if ($detailIds === []) {
  3860. return;
  3861. }
  3862. $payload = ['status_name' => $statusName];
  3863. try {
  3864. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3865. } catch (\Throwable $e) {
  3866. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3867. }
  3868. }
  3869. /**
  3870. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3871. */
  3872. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3873. {
  3874. try {
  3875. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3876. } catch (\Throwable $e) {
  3877. return;
  3878. }
  3879. if (!is_array($rows)) {
  3880. return;
  3881. }
  3882. foreach ($rows as $dr) {
  3883. if (!is_array($dr)) {
  3884. continue;
  3885. }
  3886. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3887. if ($id <= 0) {
  3888. continue;
  3889. }
  3890. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3891. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3892. try {
  3893. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3894. } catch (\Throwable $e) {
  3895. }
  3896. }
  3897. }
  3898. /**
  3899. * @param array<string, mixed> $detailRow
  3900. */
  3901. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3902. {
  3903. $am = $detailRow['amount'] ?? null;
  3904. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3905. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3906. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3907. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3908. }
  3909. /**
  3910. * @return int[]
  3911. */
  3912. protected function purchaseOrderDetail(int $scydgyId): array
  3913. {
  3914. if (!$this->isValidScydgyRowId($scydgyId)) {
  3915. return [];
  3916. }
  3917. try {
  3918. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3919. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3920. $list = $listQuery->select();
  3921. } catch (\Throwable $e) {
  3922. return [];
  3923. }
  3924. if (!is_array($list)) {
  3925. return [];
  3926. }
  3927. $ids = [];
  3928. foreach ($list as $r) {
  3929. if (!is_array($r)) {
  3930. continue;
  3931. }
  3932. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3933. if ($pk > 0) {
  3934. $ids[] = $pk;
  3935. }
  3936. }
  3937. return array_values(array_unique($ids));
  3938. }
  3939. /**
  3940. * 获取当前登录用户信息 [id, 展示名]
  3941. */
  3942. protected function GetUseName(): array
  3943. {
  3944. $id = 0;
  3945. $name = '';
  3946. try {
  3947. if ($this->auth && $this->auth->isLogin()) {
  3948. $u = $this->auth->getUserInfo();
  3949. if (is_array($u)) {
  3950. $id = (int)($u['id'] ?? 0);
  3951. $name = trim((string)($u['nickname'] ?? ''));
  3952. if ($name === '') {
  3953. $name = trim((string)($u['username'] ?? ''));
  3954. }
  3955. }
  3956. }
  3957. } catch (\Throwable $e) {
  3958. }
  3959. if ($name === '') {
  3960. $name = '未知用户';
  3961. }
  3962. return [$id, $name];
  3963. }
  3964. /**
  3965. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3966. */
  3967. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3968. {
  3969. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3970. }
  3971. /**
  3972. * 按主键取一条
  3973. */
  3974. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3975. {
  3976. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3977. return [];
  3978. }
  3979. try {
  3980. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3981. if (is_array($one)) {
  3982. return $one;
  3983. }
  3984. } catch (\Throwable $e) {
  3985. }
  3986. try {
  3987. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3988. if (is_array($one)) {
  3989. return $one;
  3990. }
  3991. } catch (\Throwable $e) {
  3992. }
  3993. return [];
  3994. }
  3995. /**
  3996. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3997. */
  3998. protected function formatProcuremenDetailTime($v): string
  3999. {
  4000. if ($v === null || $v === '') {
  4001. return '';
  4002. }
  4003. if (is_numeric($v) && (int)$v > 946684800) {
  4004. return date('Y-m-d H:i:s', (int)$v);
  4005. }
  4006. return ProcuremenTime::formatDisplayDateTime($v);
  4007. }
  4008. /**
  4009. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  4010. */
  4011. protected function formatDeliveryYmd($v): string
  4012. {
  4013. if ($v === null || $v === '') {
  4014. return '';
  4015. }
  4016. $s = trim((string)$v);
  4017. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  4018. return '';
  4019. }
  4020. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4021. return $m[1];
  4022. }
  4023. $ts = strtotime($s);
  4024. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4025. }
  4026. /**
  4027. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4028. */
  4029. protected function detailRowSupplierOperated(array $r): bool
  4030. {
  4031. $am = $r['amount'] ?? null;
  4032. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4033. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4034. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4035. return $okAmt || $okDel;
  4036. }
  4037. /**
  4038. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4039. */
  4040. protected function resolveDetailSupplierOperTime(array $r): string
  4041. {
  4042. if (!$this->detailRowSupplierOperated($r)) {
  4043. return '';
  4044. }
  4045. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4046. if ($t !== '') {
  4047. return $t;
  4048. }
  4049. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4050. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4051. continue;
  4052. }
  4053. $t = $this->formatProcuremenDetailTime($r[$col]);
  4054. if ($t !== '') {
  4055. return $t;
  4056. }
  4057. }
  4058. return '';
  4059. }
  4060. /**
  4061. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4062. */
  4063. protected function detailRowSupplierAccepted(array $r): bool
  4064. {
  4065. $am = $r['amount'] ?? null;
  4066. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4067. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4068. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4069. return $okAmt && $okDel;
  4070. }
  4071. /**
  4072. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4073. */
  4074. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4075. {
  4076. if ($detailCount > 0) {
  4077. return true;
  4078. }
  4079. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4080. return true;
  4081. }
  4082. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4083. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4084. return true;
  4085. }
  4086. return false;
  4087. }
  4088. /**
  4089. * 下发时间:优先 pick_time,其次首条下发明细时间
  4090. */
  4091. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4092. {
  4093. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4094. if ($issueTime !== '') {
  4095. return $issueTime;
  4096. }
  4097. foreach ($details as $dr) {
  4098. if (!is_array($dr)) {
  4099. continue;
  4100. }
  4101. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4102. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4103. $issueTime = $t;
  4104. }
  4105. }
  4106. if ($issueTime !== '') {
  4107. return $issueTime;
  4108. }
  4109. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4110. }
  4111. /**
  4112. * 直接点「完结」时间:优先操作记录 mark_complete
  4113. */
  4114. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4115. {
  4116. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4117. }
  4118. /**
  4119. * 操作记录时间(取指定 action 最近一条)
  4120. *
  4121. * @param string|array<int, string> $actions
  4122. */
  4123. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4124. {
  4125. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4126. }
  4127. /**
  4128. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4129. *
  4130. * @param array $main purchase_order 一行
  4131. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4132. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4133. */
  4134. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4135. {
  4136. $issueCnt = count($details);
  4137. $acceptCnt = 0;
  4138. $pickedName = '';
  4139. $pickedTime = '';
  4140. foreach ($details as $dr) {
  4141. if (!is_array($dr)) {
  4142. continue;
  4143. }
  4144. if ($this->detailRowSupplierAccepted($dr)) {
  4145. $acceptCnt++;
  4146. }
  4147. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4148. if ($pickedName === '') {
  4149. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4150. }
  4151. if ($pickedTime === '') {
  4152. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4153. if ($pickedTime === '') {
  4154. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4155. }
  4156. }
  4157. }
  4158. }
  4159. $hasMain = $main !== [];
  4160. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4161. if ($poTime === '') {
  4162. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4163. }
  4164. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4165. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4166. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4167. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4168. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4169. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4170. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4171. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4172. $supplierTime = '';
  4173. if ($acceptCnt > 0) {
  4174. foreach ($details as $dr) {
  4175. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4176. continue;
  4177. }
  4178. $t = $this->resolveDetailSupplierOperTime($dr);
  4179. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4180. $supplierTime = $t;
  4181. }
  4182. }
  4183. }
  4184. $directComplete = ($mainCompleted && !$issued);
  4185. $doneTime = '';
  4186. if ($mainCompleted) {
  4187. if ($directComplete) {
  4188. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4189. }
  4190. if ($doneTime === '') {
  4191. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4192. }
  4193. if ($doneTime === '') {
  4194. foreach ($details as $dr) {
  4195. if (!is_array($dr)) {
  4196. continue;
  4197. }
  4198. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4199. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4200. $doneTime = $t;
  4201. }
  4202. }
  4203. }
  4204. if ($doneTime === '') {
  4205. $doneTime = $poTime;
  4206. }
  4207. if ($confirmApproveTime !== '') {
  4208. $doneTime = $confirmApproveTime;
  4209. }
  4210. }
  4211. if ($directComplete) {
  4212. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4213. $step1Done = $hasMain;
  4214. $step2Done = false;
  4215. $step3Done = false;
  4216. $step4Done = false;
  4217. $step5Done = false;
  4218. $step6Done = true;
  4219. } else {
  4220. $step1Done = $issued;
  4221. $step2Done = $issued;
  4222. $step3Done = $acceptCnt > 0;
  4223. $step4Done = $wflowPendingApproval;
  4224. if (!$step4Done) {
  4225. foreach ($details as $dr) {
  4226. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4227. $step4Done = true;
  4228. break;
  4229. }
  4230. }
  4231. }
  4232. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4233. $step6Done = $mainCompleted;
  4234. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4235. if ($mainCompleted && $issued) {
  4236. $step3Done = true;
  4237. $step4Done = true;
  4238. $step5Done = true;
  4239. if ($supplierTime === '') {
  4240. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4241. if ($fillT !== '') {
  4242. $supplierTime = $fillT;
  4243. }
  4244. }
  4245. if ($pickedTime === '') {
  4246. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4247. if ($fillT !== '') {
  4248. $pickedTime = $fillT;
  4249. }
  4250. }
  4251. if ($auditSelectTime === '') {
  4252. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4253. if ($fillT !== '') {
  4254. $auditSelectTime = $fillT;
  4255. }
  4256. }
  4257. if ($confirmApproveTime === '') {
  4258. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4259. if ($fillT !== '') {
  4260. $confirmApproveTime = $fillT;
  4261. }
  4262. }
  4263. }
  4264. }
  4265. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4266. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4267. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4268. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4269. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4270. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4271. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4272. $deadlineLines = [];
  4273. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4274. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4275. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4276. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4277. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  4278. }
  4279. }
  4280. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  4281. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  4282. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  4283. if ($deliveryDisp === '') {
  4284. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  4285. }
  4286. if ($deliveryDisp !== '') {
  4287. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  4288. }
  4289. }
  4290. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  4291. if ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') {
  4292. $deadlineLines[] = '操作时间:' . $issueOperTimeRaw;
  4293. }
  4294. $deadlineText = implode("\n", $deadlineLines);
  4295. $prefixOperTime = static function (string $t): string {
  4296. $t = trim($t);
  4297. if ($t === '' || $t === '—') {
  4298. return $t;
  4299. }
  4300. if (strpos($t, '操作时间') === 0) {
  4301. return $t;
  4302. }
  4303. return '操作时间:' . $t;
  4304. };
  4305. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  4306. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '';
  4307. $step6Time = $step6Done ? $doneTime : '';
  4308. $steps = [
  4309. [
  4310. 'title' => '未发',
  4311. 'subtitle' => '',
  4312. 'time' => $issued ? '—' : ($hasMain ? $prefixOperTime($poTime) : ''),
  4313. 'done' => $step1Done,
  4314. ],
  4315. [
  4316. 'title' => '下发',
  4317. 'subtitle' => $deadlineText,
  4318. 'time' => '',
  4319. 'done' => $step2Done,
  4320. ],
  4321. [
  4322. 'title' => '供应商接单',
  4323. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4324. 'time' => '',
  4325. 'done' => $step3Done,
  4326. ],
  4327. [
  4328. 'title' => '待确认',
  4329. 'subtitle' => $step4Done
  4330. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4331. : ($issued ? '待选供应商' : ''),
  4332. 'time' => $prefixOperTime($step4Time),
  4333. 'done' => $step4Done,
  4334. ],
  4335. [
  4336. 'title' => '待审批',
  4337. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4338. 'time' => $prefixOperTime($step5Time),
  4339. 'done' => $step5Done,
  4340. ],
  4341. [
  4342. 'title' => '已完结',
  4343. 'subtitle' => '',
  4344. 'time' => $prefixOperTime($step6Time),
  4345. 'done' => $step6Done,
  4346. ],
  4347. ];
  4348. $currentIdx = count($steps) - 1;
  4349. if (!$directComplete) {
  4350. foreach ($steps as $i => $s) {
  4351. if (!$s['done']) {
  4352. $currentIdx = $i;
  4353. break;
  4354. }
  4355. }
  4356. }
  4357. $nSteps = count($steps);
  4358. foreach ($steps as $idx => &$s) {
  4359. $s['current'] = ($idx === $currentIdx);
  4360. if ($idx === 0) {
  4361. $s['pdf_left_bg'] = '';
  4362. } else {
  4363. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4364. }
  4365. if ($idx >= $nSteps - 1) {
  4366. $s['pdf_right_bg'] = '';
  4367. } else {
  4368. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4369. }
  4370. }
  4371. unset($s);
  4372. $labelMap = [
  4373. 'CCYDH' => '订单号',
  4374. 'CYJMC' => '印件名称',
  4375. 'CCLBMMC' => '承揽部门',
  4376. 'CGYMC' => '工序名称',
  4377. 'CDW' => '单位',
  4378. 'NGZL' => '工作量',
  4379. 'CDF' => '单价',
  4380. 'cGzzxMc' => '工作中心',
  4381. 'MBZ' => '备注',
  4382. 'This_quantity' => '本次数量',
  4383. 'ceilingPrice' => '最高限价',
  4384. ];
  4385. $orderSummary = [];
  4386. foreach ($labelMap as $key => $lab) {
  4387. if (!array_key_exists($key, $main)) {
  4388. continue;
  4389. }
  4390. $val = $main[$key];
  4391. if ($val === null) {
  4392. $val = '';
  4393. } elseif (!is_scalar($val)) {
  4394. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4395. } else {
  4396. $val = (string)$val;
  4397. }
  4398. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4399. }
  4400. $orderSummaryGrid = [];
  4401. $n = count($orderSummary);
  4402. for ($i = 0; $i < $n; $i += 2) {
  4403. $left = $orderSummary[$i];
  4404. $hasRight = ($i + 1) < $n;
  4405. $orderSummaryGrid[] = [
  4406. 'l1' => $left['label'],
  4407. 'v1' => $left['value'],
  4408. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4409. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4410. ];
  4411. }
  4412. return [
  4413. 'steps' => $steps,
  4414. 'orderSummary' => $orderSummary,
  4415. 'orderSummaryGrid' => $orderSummaryGrid,
  4416. 'detailRows' => $details,
  4417. ];
  4418. }
  4419. /**
  4420. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4421. *
  4422. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4423. */
  4424. protected function prepareProcuremenDetailsView(string $ids): array
  4425. {
  4426. $main = [];
  4427. try {
  4428. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4429. $main = is_array($one) ? $one : [];
  4430. } catch (\Throwable $e) {
  4431. $main = [];
  4432. }
  4433. $details = [];
  4434. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4435. if ($mergeRows === []) {
  4436. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4437. if ($mergeRows === [] && $main !== []) {
  4438. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4439. }
  4440. }
  4441. $detailSidList = [];
  4442. $anchorSid = (int)$ids;
  4443. if ($anchorSid !== 0) {
  4444. $detailSidList[$anchorSid] = true;
  4445. }
  4446. foreach ($mergeRows as $mr) {
  4447. if (!is_array($mr)) {
  4448. continue;
  4449. }
  4450. $sid = $this->extractScydgyRowId($mr);
  4451. if ($sid !== 0) {
  4452. $detailSidList[$sid] = true;
  4453. }
  4454. }
  4455. try {
  4456. if ($detailSidList !== []) {
  4457. $details = Db::table('purchase_order_detail')
  4458. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4459. ->order('id', 'asc')
  4460. ->select();
  4461. }
  4462. } catch (\Throwable $e) {
  4463. $details = [];
  4464. }
  4465. if (!is_array($details)) {
  4466. $details = [];
  4467. }
  4468. foreach ($details as &$r) {
  4469. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4470. $r['id'] = $r['ID'];
  4471. }
  4472. if (isset($r['createtime'])) {
  4473. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4474. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4475. } else {
  4476. $r['createtime_text'] = (string)$r['createtime'];
  4477. }
  4478. } else {
  4479. $r['createtime_text'] = '';
  4480. }
  4481. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4482. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4483. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4484. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4485. if (is_array($r)) {
  4486. $r = $this->maskSupplierContactFields($r);
  4487. }
  4488. }
  4489. unset($r);
  4490. $activeDetails = [];
  4491. foreach ($details as $r) {
  4492. if (is_array($r) && empty($r['is_void'])) {
  4493. $activeDetails[] = $r;
  4494. }
  4495. }
  4496. $operLogs = [];
  4497. try {
  4498. $operSidList = array_keys($detailSidList);
  4499. if ($operSidList === [] && (int)$ids !== 0) {
  4500. $operSidList = [(int)$ids];
  4501. }
  4502. if ($operSidList !== []) {
  4503. $operLogs = Db::table('purchase_order_oper_log')
  4504. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  4505. ->order('id', 'asc')
  4506. ->select();
  4507. }
  4508. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  4509. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  4510. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  4511. if ($poId > 0) {
  4512. $operLogs = Db::table('purchase_order_oper_log')
  4513. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  4514. ->order('id', 'asc')
  4515. ->select();
  4516. }
  4517. }
  4518. } catch (\Throwable $e) {
  4519. $operLogs = [];
  4520. }
  4521. if (!is_array($operLogs)) {
  4522. $operLogs = [];
  4523. }
  4524. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4525. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4526. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4527. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4528. if ($ccydh === '') {
  4529. foreach ($details as $r) {
  4530. if (!is_array($r)) {
  4531. continue;
  4532. }
  4533. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4534. if ($ccydh !== '') {
  4535. break;
  4536. }
  4537. }
  4538. }
  4539. $this->view->assign('ccydh', $ccydh);
  4540. $this->view->assign('steps', $bundle['steps']);
  4541. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4542. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4543. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4544. $this->view->assign('processCount', count($mergeRows));
  4545. $this->view->assign('detailRows', $details);
  4546. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4547. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4548. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4549. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4550. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4551. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4552. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4553. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4554. $this->view->assign('operLogs', $operLogs);
  4555. $sg = $quoteView['supplier_groups'] ?? [];
  4556. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : []));
  4557. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : []) ? 1 : 0);
  4558. return [
  4559. 'ok' => $main !== [] || $details !== [],
  4560. 'ccydh' => $ccydh,
  4561. ];
  4562. }
  4563. /**
  4564. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4565. */
  4566. public function details()
  4567. {
  4568. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4569. if (is_array($ids)) {
  4570. $ids = isset($ids[0]) ? $ids[0] : '';
  4571. }
  4572. $ids = trim((string)$ids);
  4573. if ($ids === '') {
  4574. $this->error(__('Invalid parameters'));
  4575. }
  4576. $this->assertManualOrderDetailsViewable((int)$ids);
  4577. $this->prepareProcuremenDetailsView($ids);
  4578. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4579. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4580. $this->view->engine->layout(false);
  4581. try {
  4582. return $this->view->fetch('procuremen/details_dialog_shell');
  4583. } finally {
  4584. if ($restoreLayout) {
  4585. $this->view->engine->layout($restoreLayout);
  4586. }
  4587. }
  4588. }
  4589. /**
  4590. * 解析合并审核工序行(订单号须一致,且均未协助)
  4591. *
  4592. * @return array<int, array<string, mixed>>
  4593. */
  4594. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4595. {
  4596. $primary = json_decode($rowJson, true);
  4597. if (!is_array($primary)) {
  4598. $this->error(__('Invalid parameters'));
  4599. }
  4600. $merge = json_decode($mergeRowsJson, true);
  4601. if (!is_array($merge) || $merge === []) {
  4602. $merge = [$primary];
  4603. }
  4604. $seen = [];
  4605. $out = [];
  4606. foreach ($merge as $r) {
  4607. if (!is_array($r)) {
  4608. continue;
  4609. }
  4610. $id = $this->extractScydgyRowId($r);
  4611. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4612. continue;
  4613. }
  4614. $seen[$id] = true;
  4615. $out[] = $r;
  4616. }
  4617. if ($out === []) {
  4618. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4619. }
  4620. $ccydh = null;
  4621. foreach ($out as $r) {
  4622. $dh = trim((string)($r['CCYDH'] ?? ''));
  4623. if ($ccydh === null) {
  4624. $ccydh = $dh;
  4625. } elseif ($dh !== $ccydh) {
  4626. $this->error('合并审核要求所选行的订单号一致');
  4627. }
  4628. }
  4629. $ids = [];
  4630. foreach ($out as $r) {
  4631. $id = $this->extractScydgyRowId($r);
  4632. if ($this->isValidScydgyRowId($id)) {
  4633. $ids[$id] = true;
  4634. }
  4635. }
  4636. $poBySid = [];
  4637. $detCntBySid = [];
  4638. if ($ids !== []) {
  4639. $idList = array_keys($ids);
  4640. try {
  4641. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4642. if (is_array($poList)) {
  4643. foreach ($poList as $po) {
  4644. if (!is_array($po)) {
  4645. continue;
  4646. }
  4647. $sid = (int)($po['scydgy_id'] ?? 0);
  4648. if ($this->isValidScydgyRowId($sid)) {
  4649. $poBySid[$sid] = $po;
  4650. }
  4651. }
  4652. }
  4653. } catch (\Throwable $e) {
  4654. }
  4655. try {
  4656. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4657. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4658. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4659. if (is_array($detRows)) {
  4660. foreach ($detRows as $dr) {
  4661. if (!is_array($dr)) {
  4662. continue;
  4663. }
  4664. $sid = (int)($dr['scydgy_id'] ?? 0);
  4665. if ($this->isValidScydgyRowId($sid)) {
  4666. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4667. }
  4668. }
  4669. }
  4670. } catch (\Throwable $e) {
  4671. }
  4672. }
  4673. foreach ($out as $r) {
  4674. $id = $this->extractScydgyRowId($r);
  4675. if (!$this->isValidScydgyRowId($id)) {
  4676. continue;
  4677. }
  4678. $po = $poBySid[$id] ?? null;
  4679. if (!is_array($po)) {
  4680. continue;
  4681. }
  4682. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4683. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4684. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4685. }
  4686. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4687. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4688. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4689. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4690. }
  4691. }
  4692. return $out;
  4693. }
  4694. /**
  4695. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4696. */
  4697. protected function maskSupplierContactFields(array $item): array
  4698. {
  4699. if (array_key_exists('email', $item)) {
  4700. $item['email'] = mask_email((string)$item['email']);
  4701. }
  4702. if (array_key_exists('phone', $item)) {
  4703. $item['phone'] = mask_phone((string)$item['phone']);
  4704. }
  4705. return $item;
  4706. }
  4707. /**
  4708. * @param array<int, array<string, mixed>> $list
  4709. * @return array<int, array<string, mixed>>
  4710. */
  4711. protected function maskSupplierContactList(array $list): array
  4712. {
  4713. $out = [];
  4714. foreach ($list as $item) {
  4715. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4716. }
  4717. return $out;
  4718. }
  4719. /**
  4720. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4721. *
  4722. * @return array<string, string>|null
  4723. */
  4724. protected function buildCustomerContactPayloadFromRow($row): ?array
  4725. {
  4726. if (!is_array($row)) {
  4727. return null;
  4728. }
  4729. $norm = [];
  4730. foreach ($row as $k => $v) {
  4731. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4732. }
  4733. $row = $norm;
  4734. $st = $row['status'] ?? '';
  4735. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4736. return null;
  4737. }
  4738. $companyName = '';
  4739. foreach (['company_name', 'name'] as $nk) {
  4740. if (!empty($row[$nk])) {
  4741. $companyName = trim((string)$row[$nk]);
  4742. break;
  4743. }
  4744. }
  4745. if ($companyName === '') {
  4746. return null;
  4747. }
  4748. $username = '';
  4749. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4750. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4751. $username = trim((string)$row[$uk]);
  4752. break;
  4753. }
  4754. }
  4755. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4756. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4757. if ($phone === '' && isset($row['account'])) {
  4758. $phone = trim((string)$row['account']);
  4759. }
  4760. if ($phone === '' && isset($row['mobile'])) {
  4761. $phone = trim((string)$row['mobile']);
  4762. }
  4763. if ($email === '' && $phone === '') {
  4764. return null;
  4765. }
  4766. $category = '';
  4767. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4768. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4769. $category = trim((string)$row[$ck]);
  4770. break;
  4771. }
  4772. }
  4773. return [
  4774. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4775. 'name' => $companyName,
  4776. 'company_name' => $companyName,
  4777. 'username' => $username,
  4778. 'email' => $email,
  4779. 'phone' => $phone,
  4780. 'category' => $category,
  4781. 'company_type' => $category,
  4782. ];
  4783. }
  4784. /**
  4785. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4786. */
  4787. protected function resolveCustomerContactById(string $id): ?array
  4788. {
  4789. $id = trim($id);
  4790. if ($id === '' || !ctype_digit($id)) {
  4791. return null;
  4792. }
  4793. try {
  4794. $row = Db::table('customer')->where('id', (int)$id)->find();
  4795. } catch (\Throwable $e) {
  4796. return null;
  4797. }
  4798. return $this->buildCustomerContactPayloadFromRow($row);
  4799. }
  4800. /**
  4801. * 按供应商名称解析联系信息(兼容旧提交数据)
  4802. */
  4803. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4804. {
  4805. $name = trim($name);
  4806. if ($name === '') {
  4807. return null;
  4808. }
  4809. try {
  4810. $row = Db::table('customer')
  4811. ->where(function ($q) use ($name) {
  4812. $q->where('company_name', $name)->whereOr('name', $name);
  4813. })
  4814. ->order('id', 'desc')
  4815. ->find();
  4816. } catch (\Throwable $e) {
  4817. return null;
  4818. }
  4819. return $this->buildCustomerContactPayloadFromRow($row);
  4820. }
  4821. /**
  4822. * 规范化下发/确认时勾选的供应商
  4823. *
  4824. * @param array<int, mixed> $companies
  4825. * @return array<int, array<string, string>>
  4826. */
  4827. protected function normalizePickCompanies(array $companies): array
  4828. {
  4829. $out = [];
  4830. foreach ($companies as $c) {
  4831. if (!is_array($c)) {
  4832. continue;
  4833. }
  4834. $resolved = null;
  4835. $cid = trim((string)($c['id'] ?? ''));
  4836. if ($cid !== '') {
  4837. $resolved = $this->resolveCustomerContactById($cid);
  4838. }
  4839. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4840. if ($resolved === null && $name !== '') {
  4841. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4842. }
  4843. if ($resolved === null) {
  4844. continue;
  4845. }
  4846. $out[] = $resolved;
  4847. }
  4848. return $out;
  4849. }
  4850. /**
  4851. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4852. *
  4853. * @param array<int, array<string, mixed>> $pool
  4854. * @return array<int, array<string, mixed>>
  4855. */
  4856. protected function collapseProcuremenPoolByOrder(array $pool): array
  4857. {
  4858. if ($pool === []) {
  4859. return [];
  4860. }
  4861. $groups = [];
  4862. foreach ($pool as $row) {
  4863. if (!is_array($row)) {
  4864. continue;
  4865. }
  4866. $dh = trim((string)($row['CCYDH'] ?? ''));
  4867. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4868. if (!isset($groups[$key])) {
  4869. $groups[$key] = [];
  4870. }
  4871. $groups[$key][] = $row;
  4872. }
  4873. $out = [];
  4874. foreach ($groups as $ccydh => $rows) {
  4875. if ($rows === []) {
  4876. continue;
  4877. }
  4878. usort($rows, function ($a, $b) {
  4879. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4880. });
  4881. $head = $rows[0];
  4882. $gymcList = [];
  4883. foreach ($rows as $r) {
  4884. $g = trim((string)($r['CGYMC'] ?? ''));
  4885. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4886. $gymcList[] = $g;
  4887. }
  4888. }
  4889. $merged = $head;
  4890. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4891. $merged['process_count'] = count($rows);
  4892. $merged['_order_merge_rows'] = $rows;
  4893. if (count($rows) > 1) {
  4894. $merged['CGYMC'] = implode('、', $gymcList);
  4895. }
  4896. $mergedPickTime = '';
  4897. foreach ($rows as $r) {
  4898. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4899. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4900. $mergedPickTime = $t;
  4901. }
  4902. }
  4903. if ($mergedPickTime !== '') {
  4904. $merged['pick_time'] = $mergedPickTime;
  4905. }
  4906. $out[] = $merged;
  4907. }
  4908. usort($out, function ($a, $b) {
  4909. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4910. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4911. if ($ta === $tb) {
  4912. $ida = (int)($a['purchase_order_id'] ?? 0);
  4913. $idb = (int)($b['purchase_order_id'] ?? 0);
  4914. if ($ida !== $idb) {
  4915. return $idb <=> $ida;
  4916. }
  4917. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4918. }
  4919. if ($ta === '') {
  4920. return 1;
  4921. }
  4922. if ($tb === '') {
  4923. return -1;
  4924. }
  4925. return strcmp($tb, $ta);
  4926. });
  4927. return $out;
  4928. }
  4929. /**
  4930. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4931. *
  4932. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4933. */
  4934. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4935. {
  4936. $scydgyId = trim($scydgyId);
  4937. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4938. if ($scydgyId === '') {
  4939. return $empty;
  4940. }
  4941. try {
  4942. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4943. } catch (\Throwable $e) {
  4944. $anchor = null;
  4945. }
  4946. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4947. return $empty;
  4948. }
  4949. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4950. if ($ccydh === '') {
  4951. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4952. }
  4953. try {
  4954. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4955. } catch (\Throwable $e) {
  4956. $pos = [$anchor];
  4957. }
  4958. if (!is_array($pos) || $pos === []) {
  4959. $pos = [$anchor];
  4960. }
  4961. return [
  4962. 'ccydh' => $ccydh,
  4963. 'pos' => $pos,
  4964. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4965. ];
  4966. }
  4967. /**
  4968. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4969. */
  4970. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4971. {
  4972. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4973. return false;
  4974. }
  4975. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4976. return false;
  4977. }
  4978. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4979. return true;
  4980. }
  4981. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4982. $sid = (int)($po['scydgy_id'] ?? 0);
  4983. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4984. }
  4985. return false;
  4986. }
  4987. /**
  4988. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4989. *
  4990. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4991. */
  4992. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4993. {
  4994. $scydgyId = trim($scydgyId);
  4995. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4996. if ($scydgyId === '') {
  4997. return $empty;
  4998. }
  4999. try {
  5000. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5001. } catch (\Throwable $e) {
  5002. $anchor = null;
  5003. }
  5004. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  5005. return $empty;
  5006. }
  5007. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5008. if ($ccydh === '') {
  5009. return [
  5010. 'ccydh' => '',
  5011. 'pos' => [$anchor],
  5012. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  5013. ];
  5014. }
  5015. try {
  5016. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5017. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  5018. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  5019. } catch (\Throwable $e) {
  5020. $pos = [$anchor];
  5021. }
  5022. if (!is_array($pos) || $pos === []) {
  5023. $pos = [$anchor];
  5024. }
  5025. $pos = array_values(array_filter($pos, function ($po) {
  5026. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  5027. }));
  5028. if ($pos === []) {
  5029. $pos = [$anchor];
  5030. }
  5031. return [
  5032. 'ccydh' => $ccydh,
  5033. 'pos' => $pos,
  5034. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5035. ];
  5036. }
  5037. /**
  5038. * @param array<int, array<string, mixed>> $purchaseOrders
  5039. * @return array<int, array<string, mixed>>
  5040. */
  5041. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  5042. {
  5043. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  5044. $byId = [];
  5045. foreach ($pool as $r) {
  5046. if (!is_array($r)) {
  5047. continue;
  5048. }
  5049. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  5050. if ($this->isValidScydgyRowId($sid)) {
  5051. $byId[$sid] = $r;
  5052. }
  5053. }
  5054. $out = [];
  5055. foreach ($purchaseOrders as $po) {
  5056. if (!is_array($po)) {
  5057. continue;
  5058. }
  5059. $sid = (int)($po['scydgy_id'] ?? 0);
  5060. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  5061. $out[] = $byId[$sid];
  5062. }
  5063. }
  5064. return $out;
  5065. }
  5066. /**
  5067. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  5068. *
  5069. * @return array<int, array<string, mixed>>
  5070. */
  5071. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5072. {
  5073. $scydgyId = trim($scydgyId);
  5074. if ($scydgyId === '') {
  5075. return [];
  5076. }
  5077. try {
  5078. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5079. } catch (\Throwable $e) {
  5080. $anchor = null;
  5081. }
  5082. if (!is_array($anchor)) {
  5083. return [];
  5084. }
  5085. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5086. return [];
  5087. }
  5088. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5089. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5090. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5091. try {
  5092. $q = Db::table('purchase_order');
  5093. if ($ccydh !== '') {
  5094. $q->where('CCYDH', $ccydh);
  5095. } else {
  5096. $q->where('scydgy_id', $scydgyId);
  5097. }
  5098. if ($isValidPick) {
  5099. $q->where('pick_time', $pickTime);
  5100. }
  5101. $pos = $q->order('scydgy_id', 'asc')->select();
  5102. } catch (\Throwable $e) {
  5103. $pos = [$anchor];
  5104. }
  5105. if (!is_array($pos) || $pos === []) {
  5106. $pos = [$anchor];
  5107. }
  5108. $pos = array_values(array_filter($pos, function ($po) {
  5109. if (!is_array($po)) {
  5110. return false;
  5111. }
  5112. $mr = $po['mod_rq'] ?? null;
  5113. if ($mr === null || $mr === '') {
  5114. return true;
  5115. }
  5116. $mrs = trim((string)$mr);
  5117. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5118. }));
  5119. if ($pos === []) {
  5120. $pos = [$anchor];
  5121. }
  5122. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5123. if ($rows === []) {
  5124. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5125. }
  5126. return $rows;
  5127. }
  5128. /**
  5129. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5130. *
  5131. * @param array<int, array<string, mixed>> $mergeRows
  5132. * @return array<int, array<string, mixed>>
  5133. */
  5134. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5135. {
  5136. $list = array_values($mergeRows);
  5137. $n = count($list);
  5138. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5139. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5140. $mergeSame = $n > 1 && $orderKey0 !== '';
  5141. if ($mergeSame) {
  5142. foreach ($list as $rr) {
  5143. if (!is_array($rr)) {
  5144. $mergeSame = false;
  5145. break;
  5146. }
  5147. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5148. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5149. $mergeSame = false;
  5150. break;
  5151. }
  5152. }
  5153. }
  5154. $out = [];
  5155. foreach ($list as $idx => $r) {
  5156. if (!is_array($r)) {
  5157. continue;
  5158. }
  5159. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5160. if (is_scalar($qty)) {
  5161. $qty = trim((string)$qty);
  5162. } else {
  5163. $qty = '';
  5164. }
  5165. if ($qty === '') {
  5166. $gzl = $r['NGZL'] ?? '';
  5167. if (is_scalar($gzl)) {
  5168. $qty = trim((string)$gzl);
  5169. }
  5170. }
  5171. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5172. $sid = $this->extractScydgyRowId($r);
  5173. $out[] = [
  5174. 'seq' => $idx + 1,
  5175. 'scydgy_id' => $sid,
  5176. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5177. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5178. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5179. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5180. 'NGZL' => $r['NGZL'] ?? '',
  5181. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5182. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5183. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5184. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5185. 'show_order_cells' => !$mergeSame || $idx === 0,
  5186. 'order_rowspan' => $mergeSame ? $n : 1,
  5187. ];
  5188. }
  5189. return $out;
  5190. }
  5191. /**
  5192. * 解析金额/数量(去千分位等非数字字符)
  5193. */
  5194. protected function parseProcuremenMoneyNumber($value): ?float
  5195. {
  5196. if ($value === null || $value === '') {
  5197. return null;
  5198. }
  5199. if (is_numeric($value)) {
  5200. return (float)$value;
  5201. }
  5202. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5203. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5204. }
  5205. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5206. {
  5207. if ($amount === null) {
  5208. return '';
  5209. }
  5210. return (string)(int)round($amount);
  5211. }
  5212. /**
  5213. * 列表/详情展示:工作量为 0 时显示空
  5214. */
  5215. protected function formatProcuremenWorkloadDisplay($value): string
  5216. {
  5217. if ($value === null || $value === '') {
  5218. return '';
  5219. }
  5220. $s = trim((string)$value);
  5221. if ($s === '') {
  5222. return '';
  5223. }
  5224. if (is_numeric($s) && (float)$s == 0) {
  5225. return '';
  5226. }
  5227. return $s;
  5228. }
  5229. /**
  5230. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5231. */
  5232. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5233. {
  5234. foreach ($details as $d) {
  5235. if (!is_array($d)) {
  5236. continue;
  5237. }
  5238. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5239. $cn = trim((string)($d['company_name'] ?? ''));
  5240. if ($cn !== '') {
  5241. return $cn;
  5242. }
  5243. }
  5244. }
  5245. return trim((string)($main['pick_company_name'] ?? ''));
  5246. }
  5247. /**
  5248. * 详情报价小计:单价 × 本工序本次数量
  5249. */
  5250. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5251. {
  5252. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5253. if ($unit === null) {
  5254. return null;
  5255. }
  5256. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5257. if ($qty === null || $qty <= 0) {
  5258. return null;
  5259. }
  5260. return $unit * $qty;
  5261. }
  5262. /**
  5263. * 详情页:工序小计 + 供应商分组报价与总计
  5264. *
  5265. * @param array<int, array<string, mixed>> $mergeRows
  5266. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5267. * @return array{
  5268. * process_rows: array,
  5269. * supplier_groups: array,
  5270. * order_total_text: string,
  5271. * order_total_has: bool,
  5272. * selected_company: string
  5273. * }
  5274. */
  5275. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5276. {
  5277. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5278. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5279. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5280. $qtyBySid = [];
  5281. $gymcBySid = [];
  5282. $orderedSids = [];
  5283. foreach ($mergeRows as $mr) {
  5284. if (!is_array($mr)) {
  5285. continue;
  5286. }
  5287. $sid = $this->extractScydgyRowId($mr);
  5288. if ($this->isValidScydgyRowId($sid)) {
  5289. $orderedSids[] = $sid;
  5290. }
  5291. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5292. if ($qty === '') {
  5293. $qty = trim((string)($mr['NGZL'] ?? ''));
  5294. }
  5295. $qtyBySid[$sid] = $qty;
  5296. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5297. }
  5298. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5299. $detailByCompanySid = [];
  5300. foreach ($details as $d) {
  5301. if (!is_array($d)) {
  5302. continue;
  5303. }
  5304. $cn = trim((string)($d['company_name'] ?? ''));
  5305. $sid = (int)($d['scydgy_id'] ?? 0);
  5306. if ($cn === '' || $sid === 0) {
  5307. continue;
  5308. }
  5309. if (!isset($detailByCompanySid[$cn])) {
  5310. $detailByCompanySid[$cn] = [];
  5311. }
  5312. $detailByCompanySid[$cn][$sid] = $d;
  5313. }
  5314. $supplierGroups = [];
  5315. foreach ($detailByCompanySid as $cn => $bySid) {
  5316. $lines = [];
  5317. $groupTotal = 0.0;
  5318. $groupHas = false;
  5319. $groupVoid = true;
  5320. $usedSids = [];
  5321. $appendLine = function (int $sid, array $d) use (
  5322. &$lines,
  5323. &$groupTotal,
  5324. &$groupHas,
  5325. &$groupVoid,
  5326. $qtyBySid,
  5327. $gymcBySid,
  5328. $quoteVisible
  5329. ) {
  5330. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5331. if (!$isVoid) {
  5332. $groupVoid = false;
  5333. }
  5334. $qtyStr = $qtyBySid[$sid] ?? '';
  5335. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5336. $am = trim((string)($d['amount'] ?? ''));
  5337. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5338. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5339. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5340. $sub = null;
  5341. if (!$isVoid && $amountNum !== null) {
  5342. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5343. }
  5344. $ct = $this->resolveDetailSupplierOperTime($d);
  5345. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5346. $leadFilled = ($leadDays !== null);
  5347. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5348. $line = [
  5349. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5350. 'unit_price_text' => $amountFilled
  5351. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5352. : '未填写',
  5353. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5354. 'delivery_ymd' => $deliveryYmd,
  5355. 'amount_filled' => $amountFilled,
  5356. 'delivery_filled' => $deliveryFilled,
  5357. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5358. 'lead_days' => $leadFilled ? $leadDays : '',
  5359. 'lead_days_filled'=> $leadFilled,
  5360. 'lead_days_show' => $leadText,
  5361. 'lead_days_text' => $leadText,
  5362. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5363. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5364. 'is_void' => $isVoid,
  5365. 'oper_time_text' => $ct,
  5366. ];
  5367. if (!$quoteVisible && !$isVoid) {
  5368. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5369. } elseif ($sub !== null) {
  5370. $groupTotal += $sub;
  5371. $groupHas = true;
  5372. }
  5373. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5374. };
  5375. foreach ($orderedSids as $sid) {
  5376. if (!isset($bySid[$sid])) {
  5377. continue;
  5378. }
  5379. $usedSids[$sid] = true;
  5380. $appendLine($sid, $bySid[$sid]);
  5381. }
  5382. foreach ($bySid as $sid => $d) {
  5383. if (isset($usedSids[$sid])) {
  5384. continue;
  5385. }
  5386. $appendLine((int)$sid, $d);
  5387. }
  5388. $firstDetail = null;
  5389. foreach ($bySid as $d) {
  5390. if (is_array($d)) {
  5391. $firstDetail = $d;
  5392. break;
  5393. }
  5394. }
  5395. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5396. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5397. if ($username === '' && $ph !== '') {
  5398. $username = $this->resolveCustomerContactName($ph, $cn);
  5399. }
  5400. $remark = '';
  5401. foreach ($bySid as $d) {
  5402. if (!is_array($d)) {
  5403. continue;
  5404. }
  5405. $rm = '';
  5406. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5407. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5408. $rm = trim((string)$d[$rk]);
  5409. break;
  5410. }
  5411. }
  5412. if ($rm !== '') {
  5413. $remark = $rm;
  5414. break;
  5415. }
  5416. }
  5417. $lineCount = count($lines);
  5418. $hasRemark = $lineCount > 0;
  5419. $supplierGroup = [
  5420. 'company_name' => $cn,
  5421. 'username' => $username,
  5422. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5423. 'phone' => $ph,
  5424. 'remark' => $remark,
  5425. 'has_remark' => $hasRemark,
  5426. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5427. 'is_void' => $groupVoid,
  5428. 'lines' => $lines,
  5429. 'line_count' => $lineCount,
  5430. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5431. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5432. 'has_total' => $lineCount > 0,
  5433. ];
  5434. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5435. $supplierGroups[] = $supplierGroup;
  5436. }
  5437. usort($supplierGroups, function ($a, $b) {
  5438. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5439. return ($a['is_void'] ?? false) ? 1 : -1;
  5440. }
  5441. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5442. return ($a['is_selected'] ?? false) ? -1 : 1;
  5443. }
  5444. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5445. });
  5446. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  5447. return [
  5448. 'process_rows' => $processRows,
  5449. 'supplier_groups' => $supplierGroups,
  5450. 'order_total_text' => '',
  5451. 'order_total_has' => false,
  5452. 'selected_company' => $selectedCompany,
  5453. ];
  5454. }
  5455. /**
  5456. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5457. */
  5458. protected function buildProcessLinesPlain(array $mergeRows): string
  5459. {
  5460. $lines = [];
  5461. $i = 1;
  5462. foreach ($mergeRows as $r) {
  5463. if (!is_array($r)) {
  5464. continue;
  5465. }
  5466. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5467. $dw = trim((string)($r['CDW'] ?? ''));
  5468. $gzl = trim((string)($r['NGZL'] ?? ''));
  5469. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5470. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5471. if ($dw !== '') {
  5472. $parts[] = '单位:' . $dw;
  5473. }
  5474. if ($gzl !== '') {
  5475. $parts[] = '工作量:' . $gzl;
  5476. }
  5477. if ($qty !== '') {
  5478. $parts[] = '本次数量:' . $qty;
  5479. }
  5480. $lines[] = implode(' ', $parts);
  5481. $i++;
  5482. }
  5483. return implode("\n", $lines);
  5484. }
  5485. /**
  5486. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5487. *
  5488. * @return array<string, string>
  5489. */
  5490. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5491. {
  5492. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5493. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5494. }
  5495. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5496. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5497. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5498. $cyjmc = '';
  5499. foreach ($mergeRows as $mr) {
  5500. if (!is_array($mr)) {
  5501. continue;
  5502. }
  5503. if ($ccydh === '') {
  5504. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5505. }
  5506. if ($cyjmc === '') {
  5507. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5508. }
  5509. }
  5510. if ($pos !== []) {
  5511. $firstPo = $pos[0];
  5512. if (is_array($firstPo)) {
  5513. if ($ccydh === '') {
  5514. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5515. }
  5516. if ($cyjmc === '') {
  5517. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5518. }
  5519. }
  5520. }
  5521. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5522. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5523. if (is_array($any)) {
  5524. if ($ccydh === '') {
  5525. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5526. }
  5527. if ($cyjmc === '') {
  5528. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5529. }
  5530. }
  5531. }
  5532. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5533. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5534. $cgymc = '';
  5535. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5536. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5537. }
  5538. return [
  5539. 'ccydh' => $ccydh,
  5540. 'cyjmc' => $cyjmc,
  5541. 'cgymc' => $cgymc,
  5542. 'process_lines' => $processLines,
  5543. 'process_lines_html' => '',
  5544. ];
  5545. }
  5546. /**
  5547. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5548. */
  5549. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5550. {
  5551. $lines = [];
  5552. if ($ccydh !== '') {
  5553. $lines[] = '订单号:' . $ccydh;
  5554. }
  5555. if ($cyjmc !== '') {
  5556. $lines[] = '印件名称:' . $cyjmc;
  5557. }
  5558. if ($processPlain !== '') {
  5559. $lines[] = $processPlain;
  5560. }
  5561. return implode("\n", $lines);
  5562. }
  5563. /**
  5564. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5565. *
  5566. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5567. */
  5568. protected function buildPlatformLinksPlain(array $detailLinks): string
  5569. {
  5570. $lines = [];
  5571. $i = 1;
  5572. foreach ($detailLinks as $lk) {
  5573. if (!is_array($lk)) {
  5574. continue;
  5575. }
  5576. $url = trim((string)($lk['url'] ?? ''));
  5577. if ($url === '') {
  5578. continue;
  5579. }
  5580. $label = trim((string)($lk['cgymc'] ?? ''));
  5581. if ($label === '') {
  5582. $label = '工序' . $i;
  5583. }
  5584. $lines[] = $label . ':' . $url;
  5585. $i++;
  5586. }
  5587. return implode("\n", $lines);
  5588. }
  5589. /**
  5590. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5591. *
  5592. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5593. */
  5594. protected function buildPlatformLinksHtml(array $detailLinks): string
  5595. {
  5596. $parts = [];
  5597. $i = 1;
  5598. foreach ($detailLinks as $lk) {
  5599. if (!is_array($lk)) {
  5600. continue;
  5601. }
  5602. $url = trim((string)($lk['url'] ?? ''));
  5603. if ($url === '') {
  5604. continue;
  5605. }
  5606. $label = trim((string)($lk['cgymc'] ?? ''));
  5607. if ($label === '') {
  5608. $label = '工序' . $i;
  5609. }
  5610. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5611. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5612. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5613. $i++;
  5614. }
  5615. return implode("<br>\n", $parts);
  5616. }
  5617. /**
  5618. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5619. *
  5620. * @return array<string, mixed>
  5621. */
  5622. protected function loadMailerConfig(): array
  5623. {
  5624. try {
  5625. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5626. } catch (\Throwable $e) {
  5627. $cfg = [];
  5628. }
  5629. return is_array($cfg) ? $cfg : [];
  5630. }
  5631. protected function loadNotifyTemplateRow(string $scene): ?array
  5632. {
  5633. try {
  5634. $row = Db::table('purchase_sms_template')
  5635. ->where('scene', $scene)
  5636. ->where(function ($q) {
  5637. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5638. })
  5639. ->order('id', 'asc')
  5640. ->find();
  5641. } catch (\Throwable $e) {
  5642. return null;
  5643. }
  5644. if (!is_array($row) || $row === []) {
  5645. return null;
  5646. }
  5647. return [
  5648. 'title' => trim((string)($row['title'] ?? '')),
  5649. 'content' => trim((string)($row['content'] ?? '')),
  5650. ];
  5651. }
  5652. /**
  5653. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5654. */
  5655. protected function buildProcessLinesHtml(array $mergeRows): string
  5656. {
  5657. if (count($mergeRows) <= 1) {
  5658. $r = $mergeRows[0] ?? [];
  5659. if (!is_array($r)) {
  5660. return '';
  5661. }
  5662. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5663. $dw = trim((string)($r['CDW'] ?? ''));
  5664. $gzl = trim((string)($r['NGZL'] ?? ''));
  5665. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5666. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5667. if ($dw !== '') {
  5668. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5669. }
  5670. if ($gzl !== '') {
  5671. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5672. }
  5673. if ($qty !== '') {
  5674. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5675. }
  5676. return $html;
  5677. }
  5678. $rows = '';
  5679. $i = 1;
  5680. foreach ($mergeRows as $r) {
  5681. if (!is_array($r)) {
  5682. continue;
  5683. }
  5684. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5685. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5686. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5687. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5688. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5689. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5690. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5691. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5692. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5693. $i++;
  5694. }
  5695. if ($rows === '') {
  5696. return '';
  5697. }
  5698. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5699. . '<thead><tr style="background:#f5f5f5;">'
  5700. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5701. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5702. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5703. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5704. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5705. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5706. }
  5707. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5708. {
  5709. $sysRq = trim($sysRq);
  5710. if ($sysRq === '') {
  5711. if ($required) {
  5712. $this->error('请选择招标截止日期');
  5713. }
  5714. return '';
  5715. }
  5716. $ts = strtotime($sysRq);
  5717. if ($ts === false || $ts <= 0) {
  5718. $this->error('招标截止日期格式无效');
  5719. }
  5720. $ymd = date('Y-m-d', $ts);
  5721. if ($ymd < date('Y-m-d')) {
  5722. $this->error('招标截止日期不能早于今天');
  5723. }
  5724. if ($ts <= time()) {
  5725. $this->error('招标截止时间不能早于当前时间');
  5726. }
  5727. return date('Y-m-d H:i:s', $ts);
  5728. }
  5729. /**
  5730. * 确保 purchase_order.delivery_deadline 存在
  5731. */
  5732. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  5733. {
  5734. static $done = false;
  5735. if ($done) {
  5736. return;
  5737. }
  5738. $done = true;
  5739. try {
  5740. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  5741. if (empty($cols)) {
  5742. Db::execute(
  5743. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  5744. );
  5745. }
  5746. } catch (\Throwable $e) {
  5747. // ignore
  5748. }
  5749. }
  5750. /**
  5751. * 解析交货截止日期(仅年月日)
  5752. */
  5753. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  5754. {
  5755. $raw = trim($raw);
  5756. if ($raw === '') {
  5757. if ($required) {
  5758. $this->error('请选择交货截止日期');
  5759. }
  5760. return '';
  5761. }
  5762. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  5763. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  5764. } else {
  5765. $ts = strtotime(str_replace('/', '-', $raw));
  5766. if ($ts === false || $ts <= 0) {
  5767. $this->error('交货截止日期格式无效');
  5768. }
  5769. $ymd = date('Y-m-d', $ts);
  5770. }
  5771. if ($ymd < date('Y-m-d')) {
  5772. $this->error('交货截止日期不能早于今天');
  5773. }
  5774. return $ymd;
  5775. }
  5776. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  5777. {
  5778. $s = trim((string)$value);
  5779. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  5780. return '';
  5781. }
  5782. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5783. return $m[1];
  5784. }
  5785. $ts = strtotime(str_replace('/', '-', $s));
  5786. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  5787. }
  5788. /**
  5789. * @param array{pos?:array} $bundle
  5790. */
  5791. protected function resolveBundleDeliveryDeadline(array $bundle): string
  5792. {
  5793. foreach ($bundle['pos'] ?? [] as $po) {
  5794. if (!is_array($po)) {
  5795. continue;
  5796. }
  5797. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  5798. if ($d !== '') {
  5799. return $d;
  5800. }
  5801. }
  5802. return '';
  5803. }
  5804. protected function formatProcuremenSysRqForInput($sysRq): string
  5805. {
  5806. $sr = trim((string)$sysRq);
  5807. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5808. return '';
  5809. }
  5810. $ts = strtotime($sr);
  5811. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5812. }
  5813. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5814. {
  5815. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5816. if ($sr === '') {
  5817. return '—';
  5818. }
  5819. $ts = strtotime($sr);
  5820. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5821. }
  5822. /**
  5823. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5824. *
  5825. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5826. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5827. */
  5828. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5829. {
  5830. return $bundle;
  5831. }
  5832. /**
  5833. * 写入/更新 purchase_order(单道工序行)
  5834. */
  5835. protected function upsertPurchaseOrderFromRow(
  5836. array $row,
  5837. string $sysRqDb,
  5838. $wflowStatus = null,
  5839. ?string $pickTime = null,
  5840. ?array $exists = null,
  5841. ?string $deliveryDeadline = null
  5842. ): void {
  5843. $ids = $this->extractScydgyRowId($row);
  5844. if (!$this->isValidScydgyRowId($ids)) {
  5845. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5846. }
  5847. if ($exists === null) {
  5848. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5849. }
  5850. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  5851. $data = [
  5852. 'scydgy_id' => $ids,
  5853. 'CCYDH' => $row['CCYDH'] ?? null,
  5854. 'CYJMC' => $row['CYJMC'] ?? null,
  5855. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5856. 'CDXMC' => $row['CDXMC'] ?? null,
  5857. 'CGYBH' => $row['CGYBH'] ?? null,
  5858. 'CGYMC' => $row['CGYMC'] ?? null,
  5859. 'CDW' => $row['CDW'] ?? null,
  5860. 'NGZL' => $row['NGZL'] ?? null,
  5861. 'CDF' => $row['CDF'] ?? null,
  5862. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5863. 'MBZ' => $row['MBZ'] ?? null,
  5864. 'bwjg' => $row['bwjg'] ?? null,
  5865. 'iStatus' => $row['iStatus'] ?? null,
  5866. 'dStamp' => $row['dStamp'] ?? null,
  5867. 'dputrecord' => $row['dputrecord'] ?? null,
  5868. 'cywyxm' => $row['cywyxm'] ?? null,
  5869. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5870. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5871. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5872. 'sys_rq' => $sysRqDb,
  5873. ];
  5874. if ($deliveryDeadline !== null) {
  5875. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  5876. }
  5877. if ($wflowStatus !== null && $wflowStatus !== '') {
  5878. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5879. }
  5880. if ($pickTime !== null && $pickTime !== '') {
  5881. $data['pick_time'] = $pickTime;
  5882. $data['pick_company_name'] = '';
  5883. }
  5884. if ($exists) {
  5885. $upd = $data;
  5886. unset($upd['scydgy_id']);
  5887. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5888. } else {
  5889. $data['createtime'] = date('Y-m-d H:i:s');
  5890. Db::table('purchase_order')->insert($data);
  5891. }
  5892. }
  5893. /**
  5894. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5895. *
  5896. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5897. */
  5898. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5899. {
  5900. $toDb = function ($value) {
  5901. if ($value === null) {
  5902. return null;
  5903. }
  5904. if (is_scalar($value)) {
  5905. return $value;
  5906. }
  5907. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5908. };
  5909. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5910. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5911. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5912. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5913. if ($username === '') {
  5914. $username = $this->resolveCustomerContactName($phone, $companyName);
  5915. }
  5916. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5917. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5918. }
  5919. if ($phone === '') {
  5920. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5921. }
  5922. $detailLinks = [];
  5923. foreach ($mergeRows as $row) {
  5924. if (!is_array($row)) {
  5925. continue;
  5926. }
  5927. $sid = $this->extractScydgyRowId($row);
  5928. $detailId = 0;
  5929. if ($skipExisting) {
  5930. try {
  5931. $existsQuery = Db::table('purchase_order_detail')
  5932. ->where('scydgy_id', $sid)
  5933. ->where('company_name', $companyName);
  5934. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5935. $exists = $existsQuery->find();
  5936. } catch (\Throwable $e) {
  5937. $exists = null;
  5938. }
  5939. if (is_array($exists)) {
  5940. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5941. }
  5942. }
  5943. if ($detailId <= 0) {
  5944. $one = [
  5945. 'scydgy_id' => $toDb($sid),
  5946. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5947. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5948. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5949. 'username' => $username !== '' ? $username : null,
  5950. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5951. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5952. 'createtime' => date('Y-m-d H:i:s'),
  5953. 'status' => ProcuremenStatus::POD_UNPICKED,
  5954. 'status_name' => '未提交',
  5955. ];
  5956. Db::table('purchase_order_detail')->insert($one);
  5957. $detailId = (int)Db::getLastInsID();
  5958. }
  5959. $mprocUrl = '';
  5960. if ($buildMobileLinks && $detailId > 0) {
  5961. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5962. }
  5963. $detailLinks[] = [
  5964. 'detail_id' => $detailId,
  5965. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5966. 'url' => $mprocUrl,
  5967. ];
  5968. }
  5969. return $detailLinks;
  5970. }
  5971. /**
  5972. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5973. * @return array<string, mixed>
  5974. */
  5975. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5976. {
  5977. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5978. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5979. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5980. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5981. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5982. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5983. $isMerge = !empty($ctx['is_merge']);
  5984. $contactName = trim((string)($c['username'] ?? ''));
  5985. if ($contactName === '') {
  5986. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5987. }
  5988. $notifyVars = [
  5989. 'company_name' => $companyName,
  5990. 'contact_name' => $contactName,
  5991. 'phone' => $phone,
  5992. 'email' => $toEmail,
  5993. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5994. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5995. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5996. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5997. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5998. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5999. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  6000. 'platform_url' => $platformUrl,
  6001. 'platform_links' => $platformLinksPlain,
  6002. 'platform_links_html' => $platformLinksHtml,
  6003. ];
  6004. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  6005. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  6006. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  6007. return [
  6008. 'company_name' => $companyName,
  6009. 'phone' => $phone,
  6010. 'email' => $toEmail,
  6011. 'sms_content' => $smsContent,
  6012. 'mail_plain' => $mailPlain,
  6013. 'mail_body' => $mailBody,
  6014. 'notify_vars' => $notifyVars,
  6015. 'detail_links' => $detailLinks,
  6016. ];
  6017. }
  6018. /**
  6019. * @param array<string, mixed> $chosen
  6020. * @param array<int, array<string, mixed>> $mergeRows
  6021. * @param array{ccydh:string, pos:array} $bundle
  6022. */
  6023. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  6024. {
  6025. if (!$sendSms && !$sendEmail) {
  6026. return;
  6027. }
  6028. $companyName = trim((string)($chosen['name'] ?? ''));
  6029. $phone = trim((string)($chosen['phone'] ?? ''));
  6030. $toEmail = trim((string)($chosen['email'] ?? ''));
  6031. if ($companyName === '') {
  6032. throw new \Exception('供应商名称无效');
  6033. }
  6034. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  6035. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  6036. }
  6037. if ($sendSms && $phone === '') {
  6038. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  6039. }
  6040. $sids = [];
  6041. foreach ($mergeRows as $mr) {
  6042. if (!is_array($mr)) {
  6043. continue;
  6044. }
  6045. $sid = $this->extractScydgyRowId($mr);
  6046. if ($this->isValidScydgyRowId($sid)) {
  6047. $sids[$sid] = true;
  6048. }
  6049. }
  6050. if ($sids === []) {
  6051. throw new \Exception('未找到工序行,无法发送通知');
  6052. }
  6053. $sysRqNotify = '';
  6054. $pos = $bundle['pos'] ?? [];
  6055. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6056. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  6057. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  6058. $ts = strtotime($sr);
  6059. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  6060. }
  6061. }
  6062. try {
  6063. $detailsQuery = Db::table('purchase_order_detail')
  6064. ->where('scydgy_id', 'in', array_keys($sids))
  6065. ->where('company_name', $companyName);
  6066. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6067. $details = $detailsQuery->order('id', 'asc')->select();
  6068. } catch (\Throwable $e) {
  6069. $details = [];
  6070. }
  6071. if (!is_array($details) || $details === []) {
  6072. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6073. try {
  6074. $detailsQuery = Db::table('purchase_order_detail')
  6075. ->where('scydgy_id', 'in', array_keys($sids))
  6076. ->where('company_name', $companyName);
  6077. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6078. $details = $detailsQuery->order('id', 'asc')->select();
  6079. } catch (\Throwable $e) {
  6080. $details = [];
  6081. }
  6082. }
  6083. if (!is_array($details) || $details === []) {
  6084. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6085. }
  6086. $detailLinks = [];
  6087. foreach ($details as $d) {
  6088. if (!is_array($d)) {
  6089. continue;
  6090. }
  6091. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6092. if ($detailId <= 0) {
  6093. continue;
  6094. }
  6095. $sid = (int)($d['scydgy_id'] ?? 0);
  6096. $gymc = '';
  6097. foreach ($mergeRows as $mr) {
  6098. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6099. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6100. break;
  6101. }
  6102. }
  6103. $detailLinks[] = [
  6104. 'detail_id' => $detailId,
  6105. 'cgymc' => $gymc,
  6106. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6107. ];
  6108. }
  6109. if ($detailLinks === []) {
  6110. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6111. }
  6112. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6113. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6114. $notifyBundle['email_log_scene'] = $emailLogScene;
  6115. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6116. $poIdLog = 0;
  6117. $pos = $bundle['pos'] ?? [];
  6118. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6119. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6120. }
  6121. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6122. if ($sendEmail) {
  6123. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6124. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6125. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6126. }
  6127. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6128. $mailConfig = $this->loadMailerConfig();
  6129. if (!$this->isProcuremenNotifyDryRun()) {
  6130. if (empty($mailConfig['host'])) {
  6131. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6132. }
  6133. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6134. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6135. }
  6136. }
  6137. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6138. }
  6139. if ($sendSms) {
  6140. $this->issueSendSupplierSms($notifyBundle);
  6141. }
  6142. }
  6143. /**
  6144. * @param array<int, array<string, mixed>> $quoteGroups
  6145. * @return array<int, array<string, mixed>>
  6146. */
  6147. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6148. {
  6149. $names = [];
  6150. if (is_string($companiesJson) && $companiesJson !== '') {
  6151. $decoded = json_decode($companiesJson, true);
  6152. if (is_array($decoded)) {
  6153. foreach ($decoded as $nm) {
  6154. $nm = trim((string)$nm);
  6155. if ($nm !== '') {
  6156. $names[] = $nm;
  6157. }
  6158. }
  6159. }
  6160. }
  6161. $names = array_values(array_unique($names));
  6162. if ($names === [] && $selectedCompany !== '') {
  6163. $names = [$selectedCompany];
  6164. }
  6165. if ($names === []) {
  6166. return $quoteGroups;
  6167. }
  6168. $targets = [];
  6169. foreach ($quoteGroups as $g) {
  6170. if (!is_array($g)) {
  6171. continue;
  6172. }
  6173. $cn = trim((string)($g['name'] ?? ''));
  6174. if ($cn !== '' && in_array($cn, $names, true)) {
  6175. $targets[] = $g;
  6176. }
  6177. }
  6178. return $targets;
  6179. }
  6180. /**
  6181. * @return array{pos:array, merge_rows:array, bundle:array}
  6182. */
  6183. protected function loadAuditResendBundle(string $scydgyId): array
  6184. {
  6185. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6186. $pos = $bundle['pos'];
  6187. $mergeRows = $bundle['merge_rows'];
  6188. if ($pos === [] || $mergeRows === []) {
  6189. $this->error('该订单不在待确认供应商状态');
  6190. }
  6191. $sysRqDb = '';
  6192. if (isset($pos[0]) && is_array($pos[0])) {
  6193. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6194. }
  6195. foreach ($pos as $i => $poRow) {
  6196. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6197. $pos[$i]['sys_rq'] = $sysRqDb;
  6198. }
  6199. }
  6200. $bundle['pos'] = $pos;
  6201. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6202. }
  6203. /**
  6204. * @param array<int, array<string, mixed>> $targets
  6205. */
  6206. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6207. {
  6208. if ($targets === []) {
  6209. $this->error('未找到可通知的供应商');
  6210. }
  6211. $notifyErrors = [];
  6212. try {
  6213. $this->notifyDryRunPreview = [];
  6214. foreach ($targets as $g) {
  6215. if (!is_array($g)) {
  6216. continue;
  6217. }
  6218. $cname = trim((string)($g['name'] ?? ''));
  6219. if ($cname === '') {
  6220. continue;
  6221. }
  6222. $chosen = [
  6223. 'name' => $cname,
  6224. 'company_name' => $cname,
  6225. 'email' => trim((string)($g['email'] ?? '')),
  6226. 'phone' => trim((string)($g['phone'] ?? '')),
  6227. 'username' => trim((string)($g['username'] ?? '')),
  6228. ];
  6229. try {
  6230. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6231. } catch (\Throwable $e) {
  6232. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6233. }
  6234. }
  6235. } catch (\Throwable $e) {
  6236. $this->error('通知发送失败:' . $e->getMessage());
  6237. }
  6238. if ($notifyErrors !== []) {
  6239. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6240. }
  6241. if ($this->isProcuremenNotifyDryRun()) {
  6242. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6243. 'notify_dry_run' => true,
  6244. 'notify_preview' => $this->notifyDryRunPreview,
  6245. ]);
  6246. }
  6247. $nameLabels = [];
  6248. foreach ($targets as $g) {
  6249. if (!is_array($g)) {
  6250. continue;
  6251. }
  6252. $n = trim((string)($g['name'] ?? ''));
  6253. if ($n !== '') {
  6254. $nameLabels[] = $n;
  6255. }
  6256. }
  6257. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6258. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6259. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6260. $seenLogSid = [];
  6261. foreach ($bundle['pos'] ?? [] as $poRow) {
  6262. if (!is_array($poRow)) {
  6263. continue;
  6264. }
  6265. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6266. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6267. continue;
  6268. }
  6269. $seenLogSid[$sid] = true;
  6270. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6271. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6272. }
  6273. if ($seenLogSid === []) {
  6274. foreach ($mergeRows as $mr) {
  6275. if (!is_array($mr)) {
  6276. continue;
  6277. }
  6278. $sid = $this->extractScydgyRowId($mr);
  6279. if ($this->isValidScydgyRowId($sid)) {
  6280. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6281. break;
  6282. }
  6283. }
  6284. }
  6285. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6286. }
  6287. /**
  6288. * 协助下发 — 发送短信(一家供应商)
  6289. *
  6290. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6291. */
  6292. protected function issueSendSupplierSms(array $bundle): void
  6293. {
  6294. $companyName = (string)($bundle['company_name'] ?? '');
  6295. $phone = (string)($bundle['phone'] ?? '');
  6296. $smsContent = (string)($bundle['sms_content'] ?? '');
  6297. $this->logIssueNotifyDebug('短信', [
  6298. 'company' => $companyName,
  6299. 'phone' => $phone,
  6300. 'sms_content' => $smsContent,
  6301. ]);
  6302. if ($this->isProcuremenNotifyDryRun()) {
  6303. $this->recordNotifyDryRunPreview([
  6304. 'scene' => 'issue_sms',
  6305. 'company_name' => $companyName,
  6306. 'phone' => $phone,
  6307. 'sms_content' => $smsContent,
  6308. ]);
  6309. return;
  6310. }
  6311. $this->smsbao($phone, $smsContent);
  6312. }
  6313. /**
  6314. * 协助下发 — 发送邮件(一家供应商)
  6315. *
  6316. * @param array<string, mixed> $bundle
  6317. * @param array<string, mixed> $mailConfig
  6318. */
  6319. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6320. {
  6321. $companyName = (string)($bundle['company_name'] ?? '');
  6322. $toEmail = (string)($bundle['email'] ?? '');
  6323. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6324. $mailBody = (string)($bundle['mail_body'] ?? '');
  6325. $this->logIssueNotifyDebug('邮件', [
  6326. 'company' => $companyName,
  6327. 'email' => $toEmail,
  6328. 'mail_subject' => $mailSubject,
  6329. 'mail_body' => $mailPlain,
  6330. ]);
  6331. if ($this->isProcuremenNotifyDryRun()) {
  6332. $this->recordNotifyDryRunPreview([
  6333. 'scene' => 'issue_email',
  6334. 'company_name' => $companyName,
  6335. 'email' => $toEmail,
  6336. 'mail_subject' => $mailSubject,
  6337. 'mail_body' => $mailPlain,
  6338. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6339. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6340. 'detail_links' => $bundle['detail_links'] ?? [],
  6341. ]);
  6342. return;
  6343. }
  6344. $mail = new PHPMailer(true);
  6345. $mail->isSMTP();
  6346. $mail->Host = $mailConfig['host'];
  6347. $mail->SMTPAuth = true;
  6348. $mail->Username = $mailConfig['addr'];
  6349. $mail->Password = $mailConfig['pass'];
  6350. $mail->SMTPSecure = $mailConfig['security'];
  6351. $mail->Port = $mailConfig['port'];
  6352. $mail->CharSet = $mailConfig['charset'];
  6353. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6354. $mail->addAddress($toEmail, $companyName);
  6355. $mail->isHTML(true);
  6356. $mail->Subject = $mailSubject;
  6357. $mail->Body = $mailBody;
  6358. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6359. $sendOk = true;
  6360. $failReason = '';
  6361. try {
  6362. $mail->send();
  6363. } catch (\Throwable $e) {
  6364. $sendOk = false;
  6365. $failReason = $e->getMessage();
  6366. $this->persistEmailSendLog([
  6367. 'from_email' => $fromEmail,
  6368. 'to_email' => $toEmail,
  6369. 'send_time' => date('Y-m-d H:i:s'),
  6370. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6371. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6372. 'company_name' => $companyName,
  6373. 'mail_subject' => $mailSubject,
  6374. 'status' => 0,
  6375. 'fail_reason' => $failReason,
  6376. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6377. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6378. ]);
  6379. throw $e;
  6380. }
  6381. $this->persistEmailSendLog([
  6382. 'from_email' => $fromEmail,
  6383. 'to_email' => $toEmail,
  6384. 'send_time' => date('Y-m-d H:i:s'),
  6385. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6386. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6387. 'company_name' => $companyName,
  6388. 'mail_subject' => $mailSubject,
  6389. 'status' => 1,
  6390. 'fail_reason' => '',
  6391. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6392. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6393. ]);
  6394. }
  6395. /**
  6396. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6397. *
  6398. * @param array<int, array<string, mixed>> $mergeRows
  6399. * @return array<string, mixed>
  6400. */
  6401. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6402. {
  6403. $head = $mergeRows[0] ?? [];
  6404. $isMerge = count($mergeRows) > 1;
  6405. return [
  6406. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6407. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6408. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6409. 'is_merge' => $isMerge,
  6410. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6411. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6412. 'deadline' => $sysRqNotify,
  6413. ];
  6414. }
  6415. /**
  6416. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6417. *
  6418. * @param array<string, mixed> $data
  6419. */
  6420. protected function logIssueNotifyDebug(string $type, array $data): void
  6421. {
  6422. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6423. return;
  6424. }
  6425. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6426. }
  6427. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6428. {
  6429. try {
  6430. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6431. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6432. return;
  6433. } catch (\Throwable $e) {
  6434. }
  6435. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6436. if (is_file($sqlFile)) {
  6437. $sql = file_get_contents($sqlFile);
  6438. if (is_string($sql) && $sql !== '') {
  6439. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6440. $stmt = trim($stmt);
  6441. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6442. continue;
  6443. }
  6444. try {
  6445. Db::execute($stmt);
  6446. } catch (\Throwable $ignore) {
  6447. }
  6448. }
  6449. }
  6450. }
  6451. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6452. }
  6453. /**
  6454. * @param array<string, mixed> $row
  6455. */
  6456. protected function persistEmailSendLog(array $row): void
  6457. {
  6458. try {
  6459. $this->ensurePurchaseEmailSendLogTableOnce();
  6460. } catch (\Throwable $e) {
  6461. return;
  6462. }
  6463. list($adminId, $adminName) = $this->GetUseName();
  6464. $cut = function ($s, $max) {
  6465. $s = (string)$s;
  6466. if (function_exists('mb_substr')) {
  6467. return mb_substr($s, 0, $max, 'UTF-8');
  6468. }
  6469. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6470. };
  6471. $data = [
  6472. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6473. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6474. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6475. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6476. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6477. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6478. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6479. 'status' => !empty($row['status']) ? 1 : 0,
  6480. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6481. 'admin_id' => (int)$adminId,
  6482. 'admin_name' => $cut($adminName, 64),
  6483. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6484. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6485. 'createtime' => date('Y-m-d H:i:s'),
  6486. ];
  6487. try {
  6488. Db::table('purchase_email_send_log')->insert($data);
  6489. } catch (\Throwable $e) {
  6490. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6491. }
  6492. }
  6493. protected function formatEmailLogSceneText(string $scene): string
  6494. {
  6495. $map = [
  6496. 'pick_issue' => '初选下发',
  6497. 'audit_resend' => '确认页重发',
  6498. ];
  6499. return $map[$scene] ?? $scene;
  6500. }
  6501. /**
  6502. * 邮件发送日志列表
  6503. */
  6504. public function emailLog()
  6505. {
  6506. $this->relationSearch = false;
  6507. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6508. $this->request->filter(['strip_tags', 'trim']);
  6509. $bakModel = $this->model;
  6510. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6511. if ($this->request->isAjax()) {
  6512. $this->ensurePurchaseEmailSendLogTableOnce();
  6513. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6514. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6515. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6516. $list = $this->model
  6517. ->where($where)
  6518. ->order($sortField, $orderDir)
  6519. ->paginate($limit);
  6520. $rows = [];
  6521. foreach ($list->items() as $item) {
  6522. $row = is_array($item) ? $item : $item->toArray();
  6523. $scene = trim((string)($row['scene'] ?? ''));
  6524. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6525. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6526. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6527. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6528. $rows[] = $row;
  6529. }
  6530. $this->model = $bakModel;
  6531. return json(['total' => $list->total(), 'rows' => $rows]);
  6532. }
  6533. $this->model = $bakModel;
  6534. return $this->view->fetch('procuremen/emaillog');
  6535. }
  6536. /**
  6537. * 协助下发弹窗(选多家供应商并通知)
  6538. */
  6539. public function pickReview()
  6540. {
  6541. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6542. $this->error(__('You have no permission'));
  6543. }
  6544. if ($this->request->isPost()) {
  6545. $this->error('请使用弹窗内「确认下发」提交');
  6546. }
  6547. $this->view->assign('pickMode', 1);
  6548. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6549. }
  6550. /**
  6551. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6552. */
  6553. public function add()
  6554. {
  6555. if ($this->request->isPost()) {
  6556. $params = $this->request->post('row/a');
  6557. if (!is_array($params)) {
  6558. $this->error(__('Parameter %s can not be empty', ''));
  6559. }
  6560. [, $adminName] = $this->GetUseName();
  6561. $params['cywyxm'] = $adminName;
  6562. try {
  6563. $sid = $this->saveManualPickOrder($params);
  6564. } catch (\InvalidArgumentException $e) {
  6565. $this->error($e->getMessage());
  6566. } catch (\Throwable $e) {
  6567. $this->error($e->getMessage());
  6568. }
  6569. $this->success('新增成功', '', [
  6570. 'scydgy_id' => $sid,
  6571. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6572. ]);
  6573. }
  6574. [, $adminName] = $this->GetUseName();
  6575. $this->view->assign('adminNickname', $adminName);
  6576. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6577. $this->view->assign('defaultCclbmmc', '营销中心');
  6578. return $this->view->fetch();
  6579. }
  6580. /**
  6581. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6582. */
  6583. public function rfqlist()
  6584. {
  6585. $this->relationSearch = false;
  6586. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6587. $this->request->filter(['strip_tags', 'trim']);
  6588. if ($this->request->isAjax()) {
  6589. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6590. $limit = max(10, min(500, (int)$limit));
  6591. $applyFilters = function ($query) use ($where) {
  6592. $query->where('scydgy_id', '<', 0);
  6593. $query->whereRaw(
  6594. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6595. );
  6596. if (!$this->auth->isSuperAdmin()) {
  6597. [, $adminName] = $this->GetUseName();
  6598. $query->where('cywyxm', $adminName);
  6599. }
  6600. if (!empty($where)) {
  6601. $query->where($where);
  6602. }
  6603. };
  6604. $countQuery = Db::table('purchase_order');
  6605. $applyFilters($countQuery);
  6606. $total = (int)$countQuery->count();
  6607. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6608. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6609. $listQuery = Db::table('purchase_order');
  6610. $applyFilters($listQuery);
  6611. $rows = $listQuery
  6612. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6613. ->order($sortField, $orderDir)
  6614. ->limit($offset, $limit)
  6615. ->select();
  6616. if (!is_array($rows)) {
  6617. $rows = [];
  6618. }
  6619. $out = [];
  6620. foreach ($rows as $r) {
  6621. if (!is_array($r)) {
  6622. continue;
  6623. }
  6624. $sid = (int)($r['scydgy_id'] ?? 0);
  6625. if ($sid >= 0) {
  6626. continue;
  6627. }
  6628. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6629. if ($createdText === '') {
  6630. $createdText = trim((string)($r['dStamp'] ?? ''));
  6631. }
  6632. $out[] = [
  6633. 'id' => (int)($r['id'] ?? 0),
  6634. 'scydgy_id' => $sid,
  6635. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6636. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6637. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6638. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6639. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6640. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6641. 'createtime' => $r['createtime'] ?? null,
  6642. 'createtime_text' => $createdText,
  6643. ];
  6644. }
  6645. return json(['total' => $total, 'rows' => $out]);
  6646. }
  6647. [, $adminName] = $this->GetUseName();
  6648. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6649. $this->view->assign('adminNickname', $adminName);
  6650. return $this->view->fetch('procuremen/rfqlist');
  6651. }
  6652. /**
  6653. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6654. */
  6655. public function rfqlistDetails()
  6656. {
  6657. return $this->details();
  6658. }
  6659. /**
  6660. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6661. */
  6662. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6663. {
  6664. if ($scydgyId >= 0) {
  6665. return;
  6666. }
  6667. try {
  6668. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6669. } catch (\Throwable $e) {
  6670. $po = null;
  6671. }
  6672. if (!is_array($po)) {
  6673. $this->error('订单不存在');
  6674. }
  6675. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6676. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6677. $this->error('订单不存在');
  6678. }
  6679. if ($this->auth->isSuperAdmin()) {
  6680. return;
  6681. }
  6682. [, $adminName] = $this->GetUseName();
  6683. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6684. if ($cywy !== '' && $cywy === $adminName) {
  6685. return;
  6686. }
  6687. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6688. try {
  6689. if ($this->auth->check($rule)) {
  6690. return;
  6691. }
  6692. } catch (\Throwable $e) {
  6693. }
  6694. }
  6695. $this->error('无权查看该订单');
  6696. }
  6697. /**
  6698. * 手工新增协助工序进度文案
  6699. */
  6700. protected function formatProcuremenRfqProgressText(array $row): string
  6701. {
  6702. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6703. return ProcuremenStatus::PO_COMPLETED;
  6704. }
  6705. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6706. return '待采购确认';
  6707. }
  6708. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6709. return '待确认供应商';
  6710. }
  6711. $sid = (int)($row['scydgy_id'] ?? 0);
  6712. if ($sid < 0) {
  6713. try {
  6714. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6715. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6716. $detCnt = (int)$detCntQuery->count();
  6717. if ($detCnt > 0) {
  6718. return '已下发待确认';
  6719. }
  6720. } catch (\Throwable $e) {
  6721. }
  6722. }
  6723. return '待协助下发';
  6724. }
  6725. /**
  6726. * 协助初选列表 — 批量软删除
  6727. */
  6728. public function pickDelete()
  6729. {
  6730. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6731. $this->error(__('Invalid parameters'));
  6732. }
  6733. if (!$this->procuremenCanPickDelete()) {
  6734. $this->error(__('You have no permission'));
  6735. }
  6736. $rowsRaw = $this->request->post('rows_json', '[]');
  6737. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6738. if (!is_array($rows) || $rows === []) {
  6739. $this->error('请至少勾选一条工序');
  6740. }
  6741. $done = 0;
  6742. Db::startTrans();
  6743. try {
  6744. foreach ($rows as $row) {
  6745. if (!is_array($row)) {
  6746. continue;
  6747. }
  6748. $this->softDeleteProcuremenPickRow($row);
  6749. $done++;
  6750. }
  6751. if ($done < 1) {
  6752. throw new \Exception('没有可删除的工序');
  6753. }
  6754. Db::commit();
  6755. } catch (\InvalidArgumentException $e) {
  6756. Db::rollback();
  6757. $this->error($e->getMessage());
  6758. } catch (\Throwable $e) {
  6759. Db::rollback();
  6760. $this->error($e->getMessage());
  6761. }
  6762. $this->pickHiddenScydgySetCache = null;
  6763. $this->success('已删除 ' . $done . ' 条工序');
  6764. }
  6765. /**
  6766. * 下发 — 手工新增工序(弹窗)
  6767. */
  6768. public function pickAdd()
  6769. {
  6770. if ($this->request->isPost()) {
  6771. $params = $this->request->post('row/a');
  6772. if (!is_array($params)) {
  6773. $this->error(__('Parameter %s can not be empty', ''));
  6774. }
  6775. try {
  6776. $sid = $this->saveManualPickOrder($params);
  6777. } catch (\InvalidArgumentException $e) {
  6778. $this->error($e->getMessage());
  6779. } catch (\Throwable $e) {
  6780. $this->error($e->getMessage());
  6781. }
  6782. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6783. }
  6784. return $this->view->fetch('procuremen/pick_add');
  6785. }
  6786. /**
  6787. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6788. */
  6789. public function pickSubmit()
  6790. {
  6791. if (!$this->request->isPost()) {
  6792. $this->error(__('Invalid parameters'));
  6793. }
  6794. // ---------- 接口订单数据 ----------
  6795. $rowJson = $this->request->post('row_json', '');
  6796. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6797. $companiesJson = $this->request->post('companies_json', '[]');
  6798. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6799. $companies = json_decode($companiesJson, true);
  6800. if (!is_array($companies)) {
  6801. $this->error('供应商数据无效');
  6802. }
  6803. $issueCompanies = $this->normalizePickCompanies($companies);
  6804. if ($issueCompanies === []) {
  6805. $this->error('请至少选择一家合作供应商');
  6806. }
  6807. $issueNameLabels = [];
  6808. foreach ($issueCompanies as $pc) {
  6809. $issueNameLabels[] = $pc['name'];
  6810. }
  6811. $issueNamesSummary = implode('、', $issueNameLabels);
  6812. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6813. if ($sysRq === '') {
  6814. $this->error('请选择招标截止日期');
  6815. }
  6816. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  6817. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  6818. (string)$this->request->post('delivery_deadline', ''),
  6819. true
  6820. );
  6821. $isMerge = count($mergeRows) > 1;
  6822. $ccydhLog = '';
  6823. foreach ($mergeRows as $row) {
  6824. if (!is_array($row)) {
  6825. continue;
  6826. }
  6827. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6828. if ($ccydhLog !== '') {
  6829. break;
  6830. }
  6831. }
  6832. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6833. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6834. $logMsg = '下发' . $orderPart . $procPart
  6835. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6836. $issueTime = date('Y-m-d H:i:s');
  6837. $logSidList = [];
  6838. foreach ($mergeRows as $row) {
  6839. if (!is_array($row)) {
  6840. continue;
  6841. }
  6842. $sid = $this->extractScydgyRowId($row);
  6843. if ($this->isValidScydgyRowId($sid)) {
  6844. $logSidList[$sid] = true;
  6845. }
  6846. }
  6847. $existingBySid = [];
  6848. if ($logSidList !== []) {
  6849. try {
  6850. $existingRows = Db::table('purchase_order')
  6851. ->where('scydgy_id', 'in', array_keys($logSidList))
  6852. ->select();
  6853. if (is_array($existingRows)) {
  6854. foreach ($existingRows as $poRow) {
  6855. if (!is_array($poRow)) {
  6856. continue;
  6857. }
  6858. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6859. if ($this->isValidScydgyRowId($sid)) {
  6860. $existingBySid[$sid] = $poRow;
  6861. }
  6862. }
  6863. }
  6864. } catch (\Throwable $e) {
  6865. $existingBySid = [];
  6866. }
  6867. }
  6868. Db::startTrans();
  6869. try {
  6870. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6871. foreach ($mergeRows as $row) {
  6872. if (!is_array($row)) {
  6873. continue;
  6874. }
  6875. $sid = $this->extractScydgyRowId($row);
  6876. $this->upsertPurchaseOrderFromRow(
  6877. $row,
  6878. $sysRqDb,
  6879. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6880. $issueTime,
  6881. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  6882. $deliveryDeadlineDb
  6883. );
  6884. }
  6885. foreach ($issueCompanies as $c) {
  6886. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6887. }
  6888. Db::commit();
  6889. } catch (\Throwable $e) {
  6890. Db::rollback();
  6891. $this->error($e->getMessage());
  6892. }
  6893. $poIdBySid = [];
  6894. if ($logSidList !== []) {
  6895. try {
  6896. $poIdBySid = Db::table('purchase_order')
  6897. ->where('scydgy_id', 'in', array_keys($logSidList))
  6898. ->column('id', 'scydgy_id');
  6899. } catch (\Throwable $e) {
  6900. $poIdBySid = [];
  6901. }
  6902. }
  6903. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6904. if ($logSidList !== []) {
  6905. list($adminId, $adminName) = $this->GetUseName();
  6906. $logRows = [];
  6907. $seenLogSid = [];
  6908. foreach ($mergeRows as $row) {
  6909. if (!is_array($row)) {
  6910. continue;
  6911. }
  6912. $ids = $this->extractScydgyRowId($row);
  6913. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6914. continue;
  6915. }
  6916. $seenLogSid[$ids] = true;
  6917. $poIdLog = null;
  6918. if (isset($poIdBySid[$ids])) {
  6919. $tid = (int)$poIdBySid[$ids];
  6920. $poIdLog = $tid > 0 ? $tid : null;
  6921. }
  6922. $logRows[] = ProcuremenOperLog::buildInsertRow(
  6923. $ids,
  6924. 'issue_submit',
  6925. $logMsg,
  6926. $poIdLog,
  6927. (int)$adminId,
  6928. (string)$adminName
  6929. );
  6930. }
  6931. if ($logRows !== []) {
  6932. try {
  6933. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6934. } catch (\Throwable $e) {
  6935. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6936. }
  6937. }
  6938. }
  6939. $notifyErrors = [];
  6940. $posNotify = [];
  6941. if ($logSidList !== []) {
  6942. try {
  6943. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6944. } catch (\Throwable $e) {
  6945. $posNotify = [];
  6946. }
  6947. }
  6948. if (!is_array($posNotify)) {
  6949. $posNotify = [];
  6950. }
  6951. foreach ($posNotify as $i => $prow) {
  6952. if (is_array($posNotify[$i])) {
  6953. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6954. }
  6955. }
  6956. $ccydhPick = '';
  6957. foreach ($mergeRows as $row) {
  6958. if (!is_array($row)) {
  6959. continue;
  6960. }
  6961. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6962. if ($ccydhPick !== '') {
  6963. break;
  6964. }
  6965. }
  6966. $notifyBundleBase = [
  6967. 'ccydh' => $ccydhPick,
  6968. 'pos' => $posNotify,
  6969. 'merge_rows' => $mergeRows,
  6970. ];
  6971. try {
  6972. $this->notifyDryRunPreview = [];
  6973. foreach ($issueCompanies as $c) {
  6974. if (!is_array($c)) {
  6975. continue;
  6976. }
  6977. $cname = trim((string)($c['name'] ?? ''));
  6978. if ($cname === '') {
  6979. continue;
  6980. }
  6981. try {
  6982. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6983. } catch (\Throwable $e) {
  6984. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6985. }
  6986. }
  6987. } catch (\Throwable $e) {
  6988. $this->error('通知发送失败:' . $e->getMessage());
  6989. }
  6990. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6991. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6992. }
  6993. if ($this->isProcuremenNotifyDryRun()) {
  6994. $this->success('【演练模式】已保存并生成通知预览', '', [
  6995. 'notify_dry_run' => true,
  6996. 'notify_preview' => $this->notifyDryRunPreview,
  6997. ]);
  6998. }
  6999. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  7000. }
  7001. /**
  7002. * 确认供应商弹窗
  7003. */
  7004. public function auditIssue()
  7005. {
  7006. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7007. if (is_array($ids)) {
  7008. $ids = isset($ids[0]) ? $ids[0] : '';
  7009. }
  7010. $ids = trim((string)$ids);
  7011. if ($ids === '') {
  7012. $this->error(__('Invalid parameters'));
  7013. }
  7014. if ($this->request->isPost()) {
  7015. $this->error('请使用弹窗内「确认」提交');
  7016. }
  7017. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7018. $pos = $bundle['pos'];
  7019. if ($pos === []) {
  7020. $this->error('该订单不在待确认供应商状态');
  7021. }
  7022. $po = $pos[0];
  7023. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7024. if ($quoteGroups === []) {
  7025. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  7026. }
  7027. $pickedName = '';
  7028. foreach ($pos as $poRow) {
  7029. if (!is_array($poRow)) {
  7030. continue;
  7031. }
  7032. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7033. if ($pn !== '') {
  7034. $pickedName = $pn;
  7035. break;
  7036. }
  7037. }
  7038. $this->view->assign('po', $po);
  7039. $this->view->assign('scydgyId', $ids);
  7040. $this->view->assign('orderCcydh', $bundle['ccydh']);
  7041. $mergeRows = $bundle['merge_rows'];
  7042. $this->view->assign('processRows', $mergeRows);
  7043. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  7044. $this->view->assign('processCount', count($mergeRows));
  7045. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  7046. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  7047. $this->view->assign('pickedCompanyName', $pickedName);
  7048. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7049. if ($sysRqForView === '') {
  7050. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7051. }
  7052. $this->view->assign('sysRq', $sysRqForView);
  7053. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  7054. if ($deliveryDeadlineForView === '') {
  7055. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7056. }
  7057. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7058. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  7059. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups));
  7060. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups) ? 1 : 0);
  7061. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  7062. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  7063. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  7064. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  7065. return $this->view->fetch('procuremen/audit_issue');
  7066. }
  7067. /**
  7068. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7069. *
  7070. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7071. */
  7072. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7073. {
  7074. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7075. }
  7076. /**
  7077. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7078. *
  7079. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7080. */
  7081. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7082. {
  7083. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7084. return false;
  7085. }
  7086. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7087. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7088. return true;
  7089. }
  7090. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7091. }
  7092. /**
  7093. * 确认页 — 补加供应商弹窗
  7094. */
  7095. public function auditAppend()
  7096. {
  7097. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7098. $this->error(__('You have no permission'));
  7099. }
  7100. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7101. if (is_array($ids)) {
  7102. $ids = isset($ids[0]) ? $ids[0] : '';
  7103. }
  7104. $ids = trim((string)$ids);
  7105. if ($ids === '') {
  7106. $this->error(__('Invalid parameters'));
  7107. }
  7108. if ($this->request->isPost()) {
  7109. $this->error('请使用弹窗内「确认」提交');
  7110. }
  7111. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7112. if (($bundle['pos'] ?? []) === []) {
  7113. $this->error('该订单不在待确认供应商状态');
  7114. }
  7115. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7116. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7117. $this->error('已开标验证,不能再补加供应商');
  7118. }
  7119. $this->error('已经超过了招标截止日期,不可操作');
  7120. }
  7121. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7122. $existingNames = [];
  7123. foreach ($quoteGroups as $g) {
  7124. if (!is_array($g)) {
  7125. continue;
  7126. }
  7127. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7128. if ($n !== '') {
  7129. $existingNames[$n] = true;
  7130. }
  7131. }
  7132. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7133. $mergeRows = $bundle['merge_rows'] ?? [];
  7134. $this->view->assign('scydgyId', $ids);
  7135. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7136. $this->view->assign('po', $po);
  7137. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7138. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7139. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7140. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7141. if ($sysRqForView === '') {
  7142. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7143. }
  7144. $this->view->assign('sysRq', $sysRqForView);
  7145. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7146. if ($deliveryDeadlineForView === '') {
  7147. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7148. }
  7149. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7150. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7151. }
  7152. /**
  7153. * 确认页 — 补加供应商提交
  7154. */
  7155. public function auditAppendSubmit()
  7156. {
  7157. if (!$this->request->isPost()) {
  7158. $this->error(__('Invalid parameters'));
  7159. }
  7160. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7161. $this->error(__('You have no permission'));
  7162. }
  7163. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7164. if ($ids === '') {
  7165. $this->error(__('Invalid parameters'));
  7166. }
  7167. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7168. if (($bundle['pos'] ?? []) === []) {
  7169. $this->error('该订单不在待确认供应商状态');
  7170. }
  7171. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7172. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7173. $this->error('已开标验证,不能再补加供应商');
  7174. }
  7175. $this->error('已经超过了招标截止日期,不可操作');
  7176. }
  7177. $companiesJson = $this->request->post('companies_json', '[]');
  7178. $companies = json_decode((string)$companiesJson, true);
  7179. if (!is_array($companies)) {
  7180. $this->error('供应商数据无效');
  7181. }
  7182. $issueCompanies = $this->normalizePickCompanies($companies);
  7183. if ($issueCompanies === []) {
  7184. $this->error('请至少选择一家合作供应商');
  7185. }
  7186. $mergeRows = $bundle['merge_rows'] ?? [];
  7187. if (!is_array($mergeRows) || $mergeRows === []) {
  7188. $this->error('未找到工序行,无法补加');
  7189. }
  7190. $existingNames = [];
  7191. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7192. if (!is_array($g)) {
  7193. continue;
  7194. }
  7195. $n = trim((string)($g['company_name'] ?? ''));
  7196. if ($n !== '') {
  7197. $existingNames[$n] = true;
  7198. }
  7199. }
  7200. $toAdd = [];
  7201. foreach ($issueCompanies as $c) {
  7202. if (!is_array($c)) {
  7203. continue;
  7204. }
  7205. $n = trim((string)($c['name'] ?? ''));
  7206. if ($n === '' || isset($existingNames[$n])) {
  7207. continue;
  7208. }
  7209. $toAdd[] = $c;
  7210. }
  7211. if ($toAdd === []) {
  7212. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7213. }
  7214. $addedNames = [];
  7215. Db::startTrans();
  7216. try {
  7217. foreach ($toAdd as $c) {
  7218. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7219. $addedNames[] = trim((string)($c['name'] ?? ''));
  7220. }
  7221. Db::commit();
  7222. } catch (\Throwable $e) {
  7223. Db::rollback();
  7224. $this->error($e->getMessage());
  7225. }
  7226. $notifyErrors = [];
  7227. $notifyBundleBase = [
  7228. 'ccydh' => $bundle['ccydh'] ?? '',
  7229. 'pos' => $bundle['pos'] ?? [],
  7230. 'merge_rows' => $mergeRows,
  7231. ];
  7232. foreach ($toAdd as $c) {
  7233. if (!is_array($c)) {
  7234. continue;
  7235. }
  7236. $cname = trim((string)($c['name'] ?? ''));
  7237. if ($cname === '') {
  7238. continue;
  7239. }
  7240. try {
  7241. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7242. } catch (\Throwable $e) {
  7243. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7244. }
  7245. }
  7246. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7247. $seenLogSid = [];
  7248. foreach ($bundle['pos'] ?? [] as $poRow) {
  7249. if (!is_array($poRow)) {
  7250. continue;
  7251. }
  7252. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7253. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7254. continue;
  7255. }
  7256. $seenLogSid[$sid] = true;
  7257. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7258. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7259. }
  7260. if ($seenLogSid === []) {
  7261. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7262. if ($this->isValidScydgyRowId($logSid)) {
  7263. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7264. }
  7265. }
  7266. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7267. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7268. }
  7269. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7270. }
  7271. /**
  7272. * 开标双重验证 — 可选验证人列表
  7273. */
  7274. public function bidOpenUsers()
  7275. {
  7276. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7277. $this->error('无权限');
  7278. }
  7279. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7280. if ($scydgyId !== '') {
  7281. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7282. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7283. $this->success('已完成开标验证', null, [
  7284. 'verified' => 1,
  7285. 'users' => [],
  7286. ]);
  7287. }
  7288. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7289. }
  7290. $this->success('', null, [
  7291. 'verified' => 0,
  7292. 'users' => $this->listBidOpenVerifierCandidates(),
  7293. ]);
  7294. }
  7295. /**
  7296. * 开标双重验证 — 向指定管理员发送短信验证码
  7297. */
  7298. public function bidOpenSendCode()
  7299. {
  7300. if (!$this->request->isPost()) {
  7301. $this->error(__('Invalid parameters'));
  7302. }
  7303. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7304. $this->error('无权限');
  7305. }
  7306. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7307. $adminId = (int)$this->request->post('admin_id', 0);
  7308. if ($scydgyId === '' || $adminId <= 0) {
  7309. $this->error('参数无效');
  7310. }
  7311. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7312. if ($bundle['pos'] === []) {
  7313. $this->error('该订单不在待确认供应商状态');
  7314. }
  7315. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7316. $this->success('已完成开标验证,无需重复发送');
  7317. }
  7318. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7319. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7320. if ($ccydh === '') {
  7321. $this->error('订单号无效');
  7322. }
  7323. $admin = $this->loadBidOpenAdminUser($adminId);
  7324. if ($admin === null) {
  7325. $this->error('验证人无效或未绑定手机号');
  7326. }
  7327. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7328. $cd = max(30, min(120, $cd));
  7329. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7330. $this->error('发送过于频繁,请稍后再试');
  7331. }
  7332. $code = (string)random_int(100000, 999999);
  7333. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7334. $ttl = max(60, min(600, $ttl));
  7335. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7336. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7337. try {
  7338. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7339. } catch (\Throwable $e) {
  7340. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7341. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7342. $this->error($e->getMessage());
  7343. }
  7344. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7345. }
  7346. /**
  7347. * 开标双重验证 — 两人验证码校验并记录
  7348. */
  7349. public function bidOpenVerify()
  7350. {
  7351. if (!$this->request->isPost()) {
  7352. $this->error(__('Invalid parameters'));
  7353. }
  7354. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7355. $this->error('无权限');
  7356. }
  7357. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7358. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7359. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7360. $code1 = trim((string)$this->request->post('code1', ''));
  7361. $code2 = trim((string)$this->request->post('code2', ''));
  7362. if ($scydgyId === '') {
  7363. $this->error('参数无效');
  7364. }
  7365. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7366. $this->error('请选择两位验证人');
  7367. }
  7368. if ($verifier1Id === $verifier2Id) {
  7369. $this->error('两位验证人不能相同');
  7370. }
  7371. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7372. $this->error('请输入6位短信验证码');
  7373. }
  7374. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7375. if ($bundle['pos'] === []) {
  7376. $this->error('该订单不在待确认供应商状态');
  7377. }
  7378. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7379. if ($ccydh === '') {
  7380. $this->error('订单号无效');
  7381. }
  7382. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7383. $this->success('已完成开标验证');
  7384. }
  7385. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7386. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7387. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7388. if ($verifier1 === null || $verifier2 === null) {
  7389. $this->error('验证人无效或未绑定手机号');
  7390. }
  7391. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7392. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7393. }
  7394. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7395. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7396. }
  7397. try {
  7398. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7399. } catch (\Throwable $e) {
  7400. $this->error($e->getMessage());
  7401. }
  7402. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7403. }
  7404. /**
  7405. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7406. */
  7407. public function auditSubmit()
  7408. {
  7409. if (!$this->request->isPost()) {
  7410. $this->error(__('Invalid parameters'));
  7411. }
  7412. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7413. if ($scydgyId === '') {
  7414. $this->error('参数无效');
  7415. }
  7416. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7417. $pos = $bundle['pos'];
  7418. $mergeRows = $bundle['merge_rows'];
  7419. if ($pos === [] || $mergeRows === []) {
  7420. $this->error('该订单不在待确认供应商状态');
  7421. }
  7422. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7423. if ($quoteGroups === []) {
  7424. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7425. }
  7426. $companyName = trim((string)$this->request->post('selected_company', ''));
  7427. if ($companyName === '') {
  7428. $this->error('请选择一家供应商');
  7429. }
  7430. $matched = null;
  7431. foreach ($quoteGroups as $g) {
  7432. if (!is_array($g)) {
  7433. continue;
  7434. }
  7435. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7436. $matched = $g;
  7437. break;
  7438. }
  7439. }
  7440. if ($matched === null) {
  7441. $this->error('所选供应商不在本单报价列表中');
  7442. }
  7443. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7444. if ($sysRqDb === '') {
  7445. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  7446. } else {
  7447. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  7448. }
  7449. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7450. $this->error('请先完成开标双重验证后再确认供应商');
  7451. }
  7452. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7453. $procCnt = count($mergeRows);
  7454. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7455. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7456. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  7457. Db::startTrans();
  7458. try {
  7459. foreach ($pos as $poRow) {
  7460. if (!is_array($poRow)) {
  7461. continue;
  7462. }
  7463. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7464. if (!$this->isValidScydgyRowId($sid)) {
  7465. continue;
  7466. }
  7467. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7468. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7469. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7470. 'pick_company_name' => $companyName,
  7471. 'sys_rq' => $sysRqDb,
  7472. ]);
  7473. }
  7474. Db::commit();
  7475. } catch (\Throwable $e) {
  7476. Db::rollback();
  7477. $this->error($e->getMessage());
  7478. }
  7479. foreach ($pos as $poRow) {
  7480. if (!is_array($poRow)) {
  7481. continue;
  7482. }
  7483. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7484. if (!$this->isValidScydgyRowId($sid)) {
  7485. continue;
  7486. }
  7487. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7488. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7489. }
  7490. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7491. }
  7492. /**
  7493. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7494. */
  7495. public function auditResendSms()
  7496. {
  7497. if (!$this->request->isPost()) {
  7498. $this->error(__('Invalid parameters'));
  7499. }
  7500. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7501. if ($scydgyId === '') {
  7502. $this->error('参数无效');
  7503. }
  7504. $loaded = $this->loadAuditResendBundle($scydgyId);
  7505. $mergeRows = $loaded['merge_rows'];
  7506. $bundle = $loaded['bundle'];
  7507. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7508. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7509. if ($quoteGroups === []) {
  7510. $this->error('暂无可通知的供应商');
  7511. }
  7512. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7513. $companiesJson = (string)$this->request->post('companies_json', '');
  7514. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7515. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7516. }
  7517. /**
  7518. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7519. */
  7520. public function auditResendEmail()
  7521. {
  7522. if (!$this->request->isPost()) {
  7523. $this->error(__('Invalid parameters'));
  7524. }
  7525. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7526. if ($scydgyId === '') {
  7527. $this->error('参数无效');
  7528. }
  7529. $loaded = $this->loadAuditResendBundle($scydgyId);
  7530. $mergeRows = $loaded['merge_rows'];
  7531. $bundle = $loaded['bundle'];
  7532. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7533. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7534. if ($quoteGroups === []) {
  7535. $this->error('暂无可通知的供应商');
  7536. }
  7537. $companiesJson = (string)$this->request->post('companies_json', '');
  7538. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7539. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7540. if ($companiesJson === '' && $selectedCompany === '') {
  7541. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7542. }
  7543. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7544. }
  7545. /**
  7546. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7547. *
  7548. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7549. * @return array<int, true> 已处理的 scydgy_id 集合
  7550. */
  7551. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7552. {
  7553. $pos = $bundle['pos'] ?? [];
  7554. if (!is_array($pos) || $pos === []) {
  7555. return [];
  7556. }
  7557. $sids = [];
  7558. foreach ($pos as $poRow) {
  7559. if (!is_array($poRow)) {
  7560. continue;
  7561. }
  7562. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7563. if ($this->isValidScydgyRowId($sid)) {
  7564. $sids[$sid] = true;
  7565. }
  7566. }
  7567. if ($sids === []) {
  7568. return [];
  7569. }
  7570. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7571. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7572. $suffix = trim((string)$logSuffix, ',, ');
  7573. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7574. $logMsg .= ':从历史存证退回协助初选';
  7575. } else {
  7576. $logMsg .= ':退回协助初选';
  7577. }
  7578. Db::table('purchase_order')
  7579. ->where('scydgy_id', 'in', array_keys($sids))
  7580. ->update([
  7581. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7582. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7583. 'pick_company_name' => '',
  7584. 'pick_time' => null,
  7585. 'sys_rq' => null,
  7586. 'mod_rq' => null,
  7587. ]);
  7588. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7589. foreach (array_keys($sids) as $sid) {
  7590. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7591. }
  7592. return $sids;
  7593. }
  7594. /**
  7595. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7596. *
  7597. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7598. */
  7599. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7600. {
  7601. $scydgyId = trim($scydgyId);
  7602. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7603. if ($scydgyId === '') {
  7604. return $empty;
  7605. }
  7606. try {
  7607. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7608. } catch (\Throwable $e) {
  7609. $anchor = null;
  7610. }
  7611. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7612. return $empty;
  7613. }
  7614. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7615. if ($ccydh === '') {
  7616. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7617. }
  7618. try {
  7619. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7620. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7621. $pos = $query->order('scydgy_id', 'asc')->select();
  7622. } catch (\Throwable $e) {
  7623. $pos = [$anchor];
  7624. }
  7625. if (!is_array($pos) || $pos === []) {
  7626. $pos = [$anchor];
  7627. }
  7628. return [
  7629. 'ccydh' => $ccydh,
  7630. 'pos' => $pos,
  7631. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7632. ];
  7633. }
  7634. protected function purchaseOrderRowIsCompleted(array $po): bool
  7635. {
  7636. $st = $po['status'] ?? null;
  7637. if ($st === 1 || $st === '1') {
  7638. return true;
  7639. }
  7640. if (is_string($st) && trim($st) === '1') {
  7641. return true;
  7642. }
  7643. return is_numeric($st) && (int)$st === 1;
  7644. }
  7645. /**
  7646. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7647. */
  7648. public function auditAbandon()
  7649. {
  7650. if (!$this->request->isPost()) {
  7651. $this->error(__('Invalid parameters'));
  7652. }
  7653. $anchorIds = [];
  7654. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7655. if ($batchRaw !== '') {
  7656. $decoded = json_decode($batchRaw, true);
  7657. if (is_array($decoded)) {
  7658. foreach ($decoded as $id) {
  7659. $s = trim((string)$id);
  7660. if ($s !== '') {
  7661. $anchorIds[] = $s;
  7662. }
  7663. }
  7664. }
  7665. }
  7666. if ($anchorIds === []) {
  7667. $single = trim((string)$this->request->post('scydgy_id', ''));
  7668. if ($single !== '') {
  7669. $anchorIds[] = $single;
  7670. }
  7671. }
  7672. if ($anchorIds === []) {
  7673. $this->error('请至少选择一条订单');
  7674. }
  7675. $processedCcydh = [];
  7676. $doneOrders = 0;
  7677. $allSids = [];
  7678. Db::startTrans();
  7679. try {
  7680. foreach ($anchorIds as $anchorId) {
  7681. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7682. if (($bundle['pos'] ?? []) === []) {
  7683. continue;
  7684. }
  7685. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7686. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7687. if (isset($processedCcydh[$dedupeKey])) {
  7688. continue;
  7689. }
  7690. $processedCcydh[$dedupeKey] = true;
  7691. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7692. if ($sids === []) {
  7693. continue;
  7694. }
  7695. $doneOrders++;
  7696. foreach (array_keys($sids) as $sid) {
  7697. $allSids[(int)$sid] = true;
  7698. }
  7699. }
  7700. if ($doneOrders < 1) {
  7701. throw new \Exception('所选订单均不在待确认供应商状态');
  7702. }
  7703. Db::commit();
  7704. } catch (\Throwable $e) {
  7705. Db::rollback();
  7706. $this->error($e->getMessage());
  7707. }
  7708. $this->pickHiddenScydgySetCache = null;
  7709. $msg = $doneOrders > 1
  7710. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7711. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7712. $this->success($msg);
  7713. }
  7714. /**
  7715. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7716. */
  7717. public function archiveAbandon()
  7718. {
  7719. if (!$this->request->isPost()) {
  7720. $this->error(__('Invalid parameters'));
  7721. }
  7722. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7723. $this->error(__('You have no permission'));
  7724. }
  7725. $anchorIds = [];
  7726. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7727. if ($batchRaw !== '') {
  7728. $decoded = json_decode($batchRaw, true);
  7729. if (is_array($decoded)) {
  7730. foreach ($decoded as $id) {
  7731. $s = trim((string)$id);
  7732. if ($s !== '') {
  7733. $anchorIds[] = $s;
  7734. }
  7735. }
  7736. }
  7737. }
  7738. if ($anchorIds === []) {
  7739. $single = trim((string)$this->request->post('scydgy_id', ''));
  7740. if ($single !== '') {
  7741. $anchorIds[] = $single;
  7742. }
  7743. }
  7744. if ($anchorIds === []) {
  7745. $this->error('请至少选择一条订单');
  7746. }
  7747. $processedCcydh = [];
  7748. $doneOrders = 0;
  7749. Db::startTrans();
  7750. try {
  7751. foreach ($anchorIds as $anchorId) {
  7752. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7753. if (($bundle['pos'] ?? []) === []) {
  7754. continue;
  7755. }
  7756. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7757. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7758. if (isset($processedCcydh[$dedupeKey])) {
  7759. continue;
  7760. }
  7761. $processedCcydh[$dedupeKey] = true;
  7762. $sids = $this->abandonOrderBundleToPick(
  7763. $bundle,
  7764. 'archive_abandon',
  7765. ',从历史存证退回协助初选'
  7766. );
  7767. if ($sids === []) {
  7768. continue;
  7769. }
  7770. $doneOrders++;
  7771. }
  7772. if ($doneOrders < 1) {
  7773. throw new \Exception('所选订单均不是已完结状态');
  7774. }
  7775. Db::commit();
  7776. } catch (\Throwable $e) {
  7777. Db::rollback();
  7778. $this->error($e->getMessage());
  7779. }
  7780. $this->pickHiddenScydgySetCache = null;
  7781. $msg = $doneOrders > 1
  7782. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7783. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7784. $this->success($msg);
  7785. }
  7786. /**
  7787. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7788. */
  7789. public function purchaseApprovalReject()
  7790. {
  7791. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7792. $this->error(__('Invalid parameters'));
  7793. }
  7794. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7795. $this->error(__('You have no permission'));
  7796. }
  7797. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7798. $decoded = json_decode($batchRaw, true);
  7799. if (!is_array($decoded) || $decoded === []) {
  7800. $this->error('提交数据无效');
  7801. }
  7802. $done = 0;
  7803. Db::startTrans();
  7804. try {
  7805. foreach ($decoded as $item) {
  7806. if (!is_array($item)) {
  7807. continue;
  7808. }
  7809. $sid = (int)($item['scydgy_id'] ?? 0);
  7810. if (!$this->isValidScydgyRowId($sid)) {
  7811. continue;
  7812. }
  7813. $this->runPurchaseApprovalRejectForSid($sid);
  7814. $done++;
  7815. }
  7816. if ($done < 1) {
  7817. throw new \Exception('所选订单均不在待审批状态');
  7818. }
  7819. Db::commit();
  7820. } catch (\Throwable $e) {
  7821. Db::rollback();
  7822. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7823. }
  7824. $this->pickHiddenScydgySetCache = null;
  7825. $this->success('已驳回并退回「协助审批下发」');
  7826. }
  7827. /**
  7828. * @throws \Exception
  7829. */
  7830. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7831. {
  7832. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7833. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7834. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7835. $allIds = $this->purchaseOrderDetail($sid);
  7836. if ($allIds === []) {
  7837. throw new \Exception('未找到下发明细');
  7838. }
  7839. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7840. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7841. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7842. 'pick_company_name' => '',
  7843. ]);
  7844. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7845. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7846. $poId = 0;
  7847. try {
  7848. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7849. if (is_array($po)) {
  7850. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7851. }
  7852. } catch (\Throwable $e) {
  7853. }
  7854. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7855. }
  7856. /**
  7857. * 审核弹窗(旧入口,POST 已关闭)
  7858. */
  7859. public function review()
  7860. {
  7861. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7862. $this->error(__('You have no permission'));
  7863. }
  7864. if ($this->request->isPost()) {
  7865. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7866. }
  7867. $this->view->assign('pickMode', 0);
  7868. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  7869. }
  7870. /**
  7871. * 审核弹窗获取公司列表
  7872. */
  7873. public function reviewCompanies()
  7874. {
  7875. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  7876. $this->error(__('You have no permission'));
  7877. }
  7878. if (!$this->request->isAjax()) {
  7879. $this->error(__('Invalid parameters'));
  7880. }
  7881. $list = [];
  7882. try {
  7883. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7884. $rows = Db::table('customer')
  7885. ->where(function ($q) {
  7886. $q->where('status', 1)
  7887. ->whereOr('status', '1')
  7888. ->whereOr('status', '')
  7889. ->whereNull('status');
  7890. })
  7891. ->order('id', 'desc')
  7892. ->select();
  7893. } catch (\Throwable $e) {
  7894. $this->success('', '', []);
  7895. return;
  7896. }
  7897. if (!is_array($rows)) {
  7898. $this->success('', '', []);
  7899. return;
  7900. }
  7901. $detailColCandidates = [
  7902. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7903. 'company_detail', 'company_desc', 'address',
  7904. ];
  7905. foreach ($rows as $row) {
  7906. if (!is_array($row)) {
  7907. continue;
  7908. }
  7909. $norm = [];
  7910. foreach ($row as $k => $v) {
  7911. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7912. }
  7913. $row = $norm;
  7914. $st = $row['status'] ?? '';
  7915. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7916. continue;
  7917. }
  7918. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7919. if ($payload === null) {
  7920. continue;
  7921. }
  7922. $detail = '';
  7923. foreach ($detailColCandidates as $dk) {
  7924. if (!isset($row[$dk])) {
  7925. continue;
  7926. }
  7927. $dv = trim((string)$row[$dk]);
  7928. if ($dv !== '') {
  7929. $detail = $dv;
  7930. break;
  7931. }
  7932. }
  7933. $payload['detail'] = $detail;
  7934. $list[] = $this->maskSupplierContactFields($payload);
  7935. }
  7936. $this->success('', '', $list);
  7937. }
  7938. /**
  7939. * 采购确认-下发明细弹窗:
  7940. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7941. */
  7942. public function outward_detail()
  7943. {
  7944. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7945. if (is_array($ids)) {
  7946. $ids = isset($ids[0]) ? $ids[0] : '';
  7947. }
  7948. $ids = trim((string)$ids);
  7949. if ($ids === '') {
  7950. $this->error(__('Invalid parameters'));
  7951. }
  7952. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7953. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7954. $wffTab = 'all';
  7955. }
  7956. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7957. $purchaseOrderId = 0;
  7958. $po = null;
  7959. try {
  7960. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7961. if (is_array($po)) {
  7962. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7963. }
  7964. } catch (\Throwable $e) {
  7965. $purchaseOrderId = 0;
  7966. $po = null;
  7967. }
  7968. if (!$isPurchaseConfirm && is_array($po)) {
  7969. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7970. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7971. $isPurchaseConfirm = true;
  7972. }
  7973. }
  7974. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7975. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7976. $confirmProcessCount = 1;
  7977. $confirmPickGroups = [];
  7978. $processDisplayRows = [];
  7979. $allDetailsBySid = [];
  7980. $requiredSidList = [];
  7981. $sidList = [$ids];
  7982. if ($isPurchaseConfirm) {
  7983. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7984. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7985. if ($mergeRows !== []) {
  7986. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7987. }
  7988. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7989. if ($confirmBundle['pos'] !== []) {
  7990. $sidList = [];
  7991. foreach ($confirmBundle['pos'] as $poRow) {
  7992. if (!is_array($poRow)) {
  7993. continue;
  7994. }
  7995. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7996. if (!$this->isValidScydgyRowId($sid)) {
  7997. continue;
  7998. }
  7999. $sidList[] = (string)$sid;
  8000. $requiredSidList[] = $sid;
  8001. }
  8002. }
  8003. if ($sidList === []) {
  8004. $sidList = [$ids];
  8005. $requiredSidList = [(int)$ids];
  8006. }
  8007. $confirmProcessCount = max(1, count($requiredSidList));
  8008. if (is_array($po) && $purchaseOrderId <= 0) {
  8009. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8010. }
  8011. }
  8012. $rows = [];
  8013. try {
  8014. if (count($sidList) === 1) {
  8015. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  8016. } else {
  8017. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  8018. }
  8019. } catch (\Throwable $e) {
  8020. $rows = [];
  8021. }
  8022. if ($isPurchaseConfirm) {
  8023. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  8024. }
  8025. foreach ($rows as &$r) {
  8026. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  8027. $r['id'] = $r['ID'];
  8028. }
  8029. if (isset($r['createtime'])) {
  8030. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  8031. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  8032. } else {
  8033. $r['createtime_text'] = (string)$r['createtime'];
  8034. }
  8035. } else {
  8036. $r['createtime_text'] = '';
  8037. }
  8038. if (is_array($r)) {
  8039. $r = $this->maskSupplierContactFields($r);
  8040. }
  8041. }
  8042. unset($r);
  8043. $pickedCompanyName = '';
  8044. if ($isPurchaseConfirm) {
  8045. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  8046. if (!is_array($poRow)) {
  8047. continue;
  8048. }
  8049. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  8050. if ($pn !== '') {
  8051. $pickedCompanyName = $pn;
  8052. break;
  8053. }
  8054. }
  8055. }
  8056. $this->view->assign('rows', $rows ?: []);
  8057. $this->view->assign('rowCount', count($rows ?: []));
  8058. $this->view->assign('scydgyId', $ids);
  8059. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  8060. $this->view->assign('headTitle', $headTitle);
  8061. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  8062. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  8063. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  8064. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  8065. $this->view->assign('processDisplayRows', $processDisplayRows);
  8066. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8067. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8068. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8069. $this->view->assign('bidOpenVerified', ($isPurchaseConfirm && $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle)) ? 1 : 0);
  8070. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups));
  8071. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups) ? 1 : 0);
  8072. $sysRqDisplay = '—';
  8073. if ($isPurchaseConfirm) {
  8074. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8075. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8076. );
  8077. }
  8078. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8079. $this->view->assign('sysRq', $isPurchaseConfirm
  8080. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8081. : '');
  8082. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8083. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8084. : '');
  8085. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8086. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8087. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8088. if ($isPurchaseConfirm) {
  8089. return $this->view->fetch();
  8090. }
  8091. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8092. $this->view->engine->layout(false);
  8093. try {
  8094. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8095. $this->view->assign('dialogBody', $bodyHtml);
  8096. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8097. } finally {
  8098. if ($restoreLayout) {
  8099. $this->view->engine->layout($restoreLayout);
  8100. }
  8101. }
  8102. }
  8103. /**
  8104. * 月度导出记录表(不存在时自动创建)
  8105. */
  8106. protected function ensurePurchaseMonthExportLogTable(): void
  8107. {
  8108. try {
  8109. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8110. } catch (\Throwable $e) {
  8111. Db::execute(
  8112. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8113. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8114. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8115. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8116. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8117. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8118. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8119. `createtime` int(10) unsigned DEFAULT NULL,
  8120. PRIMARY KEY (`id`),
  8121. KEY `idx_ym` (`ym`),
  8122. KEY `idx_ct` (`createtime`)
  8123. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8124. );
  8125. }
  8126. }
  8127. /**
  8128. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8129. *
  8130. * @param array<int, mixed> $dbRows
  8131. * @return array<int, array<string, mixed>>
  8132. */
  8133. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8134. {
  8135. $keyword = trim((string)$this->request->get('search', ''));
  8136. if ($keyword === '') {
  8137. $keyword = trim((string)$this->request->request('search', ''));
  8138. }
  8139. $filter = $this->request->get('filter', '');
  8140. $op = $this->request->get('op', '');
  8141. if (is_string($filter) && $filter !== '') {
  8142. $filterArr = (array)json_decode($filter, true);
  8143. } else {
  8144. $filterArr = is_array($filter) ? $filter : [];
  8145. }
  8146. if (is_string($op) && $op !== '') {
  8147. $opArr = (array)json_decode($op, true);
  8148. } else {
  8149. $opArr = is_array($op) ? $op : [];
  8150. }
  8151. if ($keyword === '' && $filterArr === []) {
  8152. return array_values(array_filter($dbRows, 'is_array'));
  8153. }
  8154. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8155. $out = [];
  8156. foreach ($dbRows as $row) {
  8157. if (!is_array($row)) {
  8158. continue;
  8159. }
  8160. if ($keyword !== '') {
  8161. $hit = false;
  8162. foreach ($searchFields as $f) {
  8163. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8164. $hit = true;
  8165. break;
  8166. }
  8167. }
  8168. if (!$hit) {
  8169. continue;
  8170. }
  8171. }
  8172. $passFilter = true;
  8173. foreach ($filterArr as $field => $val) {
  8174. $field = (string)$field;
  8175. $val = trim((string)$val);
  8176. if ($field === '' || $val === '') {
  8177. continue;
  8178. }
  8179. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8180. continue;
  8181. }
  8182. $cell = (string)($row[$field] ?? '');
  8183. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8184. if ($mode === '=' || $mode === 'EQUAL') {
  8185. if (strcasecmp($cell, $val) !== 0) {
  8186. $passFilter = false;
  8187. break;
  8188. }
  8189. } elseif (mb_stripos($cell, $val) === false) {
  8190. $passFilter = false;
  8191. break;
  8192. }
  8193. }
  8194. if (!$passFilter) {
  8195. continue;
  8196. }
  8197. $out[] = $row;
  8198. }
  8199. return $out;
  8200. }
  8201. /**
  8202. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8203. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8204. */
  8205. public function export_month_outward()
  8206. {
  8207. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8208. $this->error(__('You have no permission'));
  8209. }
  8210. $bundle = $this->prepareMonthOutwardExportBundle();
  8211. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8212. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  8213. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  8214. $spreadsheet = new Spreadsheet();
  8215. $sheet = $spreadsheet->getActiveSheet();
  8216. $sheet->setTitle('外协加工明细');
  8217. $mon = (int)substr($ym, 5, 2);
  8218. $sheet->mergeCells('A1:H1');
  8219. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8220. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8221. $sheet->getStyle('A1')->getAlignment()
  8222. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8223. ->setVertical(Alignment::VERTICAL_CENTER);
  8224. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8225. $col = 'A';
  8226. foreach ($headers as $h) {
  8227. $sheet->setCellValue($col . '2', $h);
  8228. $col++;
  8229. }
  8230. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8231. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8232. $rowNum = 3;
  8233. $sumSubtotalCounts = 0;
  8234. $grandAmount = 0.0;
  8235. $globalSeq = 0;
  8236. if ($groups === []) {
  8237. $sheet->mergeCells('A3:H3');
  8238. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8239. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8240. $rowNum = 4;
  8241. } else {
  8242. foreach ($groups as $items) {
  8243. if ($items === []) {
  8244. continue;
  8245. }
  8246. $groupLineCount = count($items);
  8247. $subAmount = 0.0;
  8248. foreach ($items as $line) {
  8249. $globalSeq++;
  8250. $dr = $line['detail'];
  8251. $amt = $this->procuremenExportAmount($dr);
  8252. $subAmount += $amt;
  8253. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8254. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8255. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8256. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8257. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8258. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8259. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8260. $sheet->setCellValue('H' . $rowNum, $amt);
  8261. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8262. $rowNum++;
  8263. }
  8264. $sumSubtotalCounts += $groupLineCount;
  8265. $grandAmount += $subAmount;
  8266. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8267. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8268. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8269. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8270. ->setVertical(Alignment::VERTICAL_CENTER);
  8271. $rowNum++;
  8272. }
  8273. }
  8274. $sheet->setCellValue('A' . $rowNum, '总计');
  8275. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8276. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8277. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8278. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8279. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8280. $lastRow = $rowNum;
  8281. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8282. 'borders' => [
  8283. 'allBorders' => [
  8284. 'borderStyle' => Border::BORDER_THIN,
  8285. 'color' => ['rgb' => '000000'],
  8286. ],
  8287. ],
  8288. ]);
  8289. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8290. if ($lastRow >= 3) {
  8291. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8292. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8293. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8294. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8295. }
  8296. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8297. $sheet->getColumnDimension('A')->setWidth(7);
  8298. $sheet->getColumnDimension('B')->setWidth(16);
  8299. $sheet->getColumnDimension('C')->setWidth(52);
  8300. $sheet->getColumnDimension('D')->setWidth(32);
  8301. $sheet->getColumnDimension('E')->setWidth(12);
  8302. $sheet->getColumnDimension('F')->setWidth(44);
  8303. $sheet->getColumnDimension('G')->setWidth(26);
  8304. $sheet->getColumnDimension('H')->setWidth(13);
  8305. $sheet->getRowDimension(1)->setRowHeight(28);
  8306. $ymCompact = str_replace('-', '', $ym);
  8307. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8308. $filename = $fileBase . '.xlsx';
  8309. try {
  8310. $this->ensurePurchaseMonthExportLogTable();
  8311. list($adminId, $adminName) = $this->GetUseName();
  8312. Db::table('purchase_month_export_log')->insert([
  8313. 'ym' => $ym,
  8314. 'admin_id' => (int)$adminId,
  8315. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8316. 'row_count' => count($exportLines),
  8317. 'total_amount' => round($grandAmount, 2),
  8318. 'createtime' => time(),
  8319. ]);
  8320. } catch (\Throwable $e) {
  8321. Log::write('month export log: ' . $e->getMessage(), 'error');
  8322. }
  8323. if (ob_get_length()) {
  8324. ob_end_clean();
  8325. }
  8326. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8327. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8328. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8329. header('Cache-Control: max-age=0');
  8330. $writer = new Xlsx($spreadsheet);
  8331. $writer->save('php://output');
  8332. $spreadsheet->disconnectWorksheets();
  8333. unset($spreadsheet);
  8334. exit;
  8335. }
  8336. /**
  8337. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  8338. */
  8339. public function export_month_quote()
  8340. {
  8341. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  8342. $this->error(__('You have no permission'));
  8343. }
  8344. $bundle = $this->prepareMonthOutwardExportBundle();
  8345. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8346. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  8347. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  8348. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8349. $spreadsheet = new Spreadsheet();
  8350. $sheet = $spreadsheet->getActiveSheet();
  8351. $sheet->setTitle('供应商报价明细');
  8352. $mon = (int)substr($ym, 5, 2);
  8353. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  8354. $sheet->getColumnDimension('A')->setWidth(7);
  8355. $sheet->getColumnDimension('B')->setWidth(16);
  8356. $sheet->getColumnDimension('C')->setWidth(52);
  8357. $sheet->getColumnDimension('D')->setWidth(26);
  8358. $sheet->getColumnDimension('E')->setWidth(32);
  8359. $sheet->getColumnDimension('F')->setWidth(12);
  8360. $sheet->getColumnDimension('G')->setWidth(14);
  8361. $sheet->getColumnDimension('H')->setWidth(12);
  8362. if ($quoteLastRow < 1) {
  8363. $quoteLastRow = 3;
  8364. }
  8365. $ymCompact = str_replace('-', '', $ym);
  8366. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  8367. if (ob_get_length()) {
  8368. ob_end_clean();
  8369. }
  8370. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  8371. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8372. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8373. header('Cache-Control: max-age=0');
  8374. $writer = new Xlsx($spreadsheet);
  8375. $writer->save('php://output');
  8376. $spreadsheet->disconnectWorksheets();
  8377. unset($spreadsheet);
  8378. exit;
  8379. }
  8380. /**
  8381. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  8382. *
  8383. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  8384. */
  8385. protected function prepareMonthOutwardExportBundle(): array
  8386. {
  8387. $this->request->filter(['strip_tags', 'trim']);
  8388. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8389. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8390. $ym = date('Y-m');
  8391. }
  8392. $dbRows = [];
  8393. try {
  8394. $query = Db::table('purchase_order');
  8395. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8396. $dbRows = $query->select();
  8397. } catch (\Throwable $e) {
  8398. $dbRows = [];
  8399. }
  8400. if (!is_array($dbRows)) {
  8401. $dbRows = [];
  8402. }
  8403. $completeTsMap = [];
  8404. $sidList = [];
  8405. foreach ($dbRows as $dbRow) {
  8406. if (!is_array($dbRow)) {
  8407. continue;
  8408. }
  8409. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8410. if ($sid > 0) {
  8411. $sidList[$sid] = true;
  8412. }
  8413. }
  8414. if ($sidList !== []) {
  8415. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8416. }
  8417. $searchKw = trim((string)$this->request->get('search', ''));
  8418. if ($searchKw === '') {
  8419. $searchKw = trim((string)$this->request->request('search', ''));
  8420. }
  8421. $filterRaw = $this->request->get('filter', '');
  8422. $filterArrTmp = [];
  8423. if (is_string($filterRaw) && $filterRaw !== '') {
  8424. $filterArrTmp = (array)json_decode($filterRaw, true);
  8425. } elseif (is_array($filterRaw)) {
  8426. $filterArrTmp = $filterRaw;
  8427. }
  8428. $hasSearch = ($searchKw !== '');
  8429. if (!$hasSearch) {
  8430. foreach ($filterArrTmp as $fv) {
  8431. if (trim((string)$fv) !== '') {
  8432. $hasSearch = true;
  8433. break;
  8434. }
  8435. }
  8436. }
  8437. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8438. if (!is_array($dbRow)) {
  8439. return false;
  8440. }
  8441. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8442. if ($done['ts'] <= 0) {
  8443. return false;
  8444. }
  8445. if ($hasSearch) {
  8446. return true;
  8447. }
  8448. return date('Y-m', $done['ts']) === $ym;
  8449. }));
  8450. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8451. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8452. $mainBySid = [];
  8453. foreach ($pool as $rw) {
  8454. if (!is_array($rw)) {
  8455. continue;
  8456. }
  8457. $rid = (int)($rw['ID'] ?? 0);
  8458. if ($rid > 0) {
  8459. $mainBySid[$rid] = $rw;
  8460. }
  8461. }
  8462. if ($mainBySid === []) {
  8463. $detailRows = [];
  8464. } else {
  8465. try {
  8466. $detailRows = Db::table('purchase_order_detail')
  8467. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8468. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8469. ->order('status', 'desc')
  8470. ->order('CCYDH', 'asc')
  8471. ->order('company_name', 'asc')
  8472. ->order('id', 'asc')
  8473. ->select();
  8474. } catch (\Throwable $e) {
  8475. try {
  8476. $detailRows = Db::table('purchase_order_detail')
  8477. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8478. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8479. ->order('status', 'desc')
  8480. ->order('CCYDH', 'asc')
  8481. ->order('company_name', 'asc')
  8482. ->order('ID', 'asc')
  8483. ->select();
  8484. } catch (\Throwable $e2) {
  8485. $detailRows = [];
  8486. }
  8487. }
  8488. }
  8489. if (!is_array($detailRows)) {
  8490. $detailRows = [];
  8491. }
  8492. $exportLines = [];
  8493. $detailSidSeen = [];
  8494. foreach ($detailRows as $dr) {
  8495. if (!is_array($dr)) {
  8496. continue;
  8497. }
  8498. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8499. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8500. continue;
  8501. }
  8502. if (isset($detailSidSeen[$sid])) {
  8503. continue;
  8504. }
  8505. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8506. continue;
  8507. }
  8508. $detailSidSeen[$sid] = true;
  8509. $m = $mainBySid[$sid];
  8510. $exportLines[] = [
  8511. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8512. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8513. 'company_name' => (string)($dr['company_name'] ?? ''),
  8514. 'CDF' => (string)($m['CDF'] ?? ''),
  8515. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8516. 'gx' => $this->procuremenExportGxText($m),
  8517. 'detail' => $dr,
  8518. ];
  8519. }
  8520. foreach ($detailRows as $dr) {
  8521. if (!is_array($dr)) {
  8522. continue;
  8523. }
  8524. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8525. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8526. continue;
  8527. }
  8528. $detailSidSeen[$sid] = true;
  8529. $m = $mainBySid[$sid];
  8530. $exportLines[] = [
  8531. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8532. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8533. 'company_name' => (string)($dr['company_name'] ?? ''),
  8534. 'CDF' => (string)($m['CDF'] ?? ''),
  8535. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8536. 'gx' => $this->procuremenExportGxText($m),
  8537. 'detail' => $dr,
  8538. ];
  8539. }
  8540. foreach ($mainBySid as $sid => $m) {
  8541. if (isset($detailSidSeen[$sid])) {
  8542. continue;
  8543. }
  8544. $company = trim((string)($m['pick_company_name'] ?? ''));
  8545. $exportLines[] = [
  8546. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8547. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8548. 'company_name' => $company,
  8549. 'CDF' => (string)($m['CDF'] ?? ''),
  8550. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8551. 'gx' => $this->procuremenExportGxText($m),
  8552. 'detail' => [],
  8553. ];
  8554. }
  8555. $groups = [];
  8556. foreach ($exportLines as $line) {
  8557. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8558. if (!isset($groups[$k])) {
  8559. $groups[$k] = [];
  8560. }
  8561. $groups[$k][] = $line;
  8562. }
  8563. ksort($groups, SORT_STRING);
  8564. return [
  8565. 'ym' => $ym,
  8566. 'mainBySid' => $mainBySid,
  8567. 'detailRows' => $detailRows,
  8568. 'exportLines' => $exportLines,
  8569. 'groups' => $groups,
  8570. ];
  8571. }
  8572. /**
  8573. * 导出用:工序列文案
  8574. */
  8575. protected function procuremenExportGxText(array $r)
  8576. {
  8577. $a = trim((string)($r['CDXMC'] ?? ''));
  8578. $b = trim((string)($r['CGYMC'] ?? ''));
  8579. if ($a !== '' && $b !== '') {
  8580. return $a . ':' . $b;
  8581. }
  8582. return $a !== '' ? $a : $b;
  8583. }
  8584. /**
  8585. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8586. */
  8587. protected function procuremenExportAmount(array $r)
  8588. {
  8589. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8590. if (!array_key_exists($k, $r)) {
  8591. continue;
  8592. }
  8593. $v = $r[$k];
  8594. if ($v === null || $v === '') {
  8595. continue;
  8596. }
  8597. if (is_numeric($v)) {
  8598. return (float)$v;
  8599. }
  8600. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8601. if ($v !== '' && is_numeric($v)) {
  8602. return (float)$v;
  8603. }
  8604. }
  8605. return 0.0;
  8606. }
  8607. /**
  8608. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8609. *
  8610. * @param array<int, array<string, mixed>> $detailRows
  8611. * @param array<int, array<string, mixed>> $mainBySid
  8612. * @return array<int, array<string, mixed>>
  8613. */
  8614. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8615. {
  8616. $lines = [];
  8617. foreach ($detailRows as $dr) {
  8618. if (!is_array($dr)) {
  8619. continue;
  8620. }
  8621. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8622. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8623. continue;
  8624. }
  8625. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8626. continue;
  8627. }
  8628. $cn = trim((string)($dr['company_name'] ?? ''));
  8629. if ($cn === '') {
  8630. continue;
  8631. }
  8632. $m = $mainBySid[$sid];
  8633. $am = trim((string)($dr['amount'] ?? ''));
  8634. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8635. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8636. $amountText = $amountFilled
  8637. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8638. : '未填写';
  8639. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8640. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8641. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8642. $deliveryShow = $deliveryRaw;
  8643. }
  8644. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8645. ? $deliveryShow
  8646. : '未填写';
  8647. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8648. $lines[] = [
  8649. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8650. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8651. 'gx' => $this->procuremenExportGxText($m),
  8652. 'company_name' => $cn,
  8653. 'amount_text' => $amountText,
  8654. 'amount_num' => $amountFilled ? $amountNum : null,
  8655. 'delivery_text' => $deliveryText,
  8656. 'picked_text' => $picked ? '中标' : '未中标',
  8657. 'picked' => $picked,
  8658. ];
  8659. }
  8660. $winnerSupplierByOrder = [];
  8661. foreach ($lines as $line) {
  8662. $dh = trim((string)($line['CCYDH'] ?? ''));
  8663. $cn = trim((string)($line['company_name'] ?? ''));
  8664. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8665. $winnerSupplierByOrder[$dh][$cn] = true;
  8666. }
  8667. }
  8668. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8669. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8670. if ($c !== 0) {
  8671. return $c;
  8672. }
  8673. $dh = trim((string)($a['CCYDH'] ?? ''));
  8674. $aCn = trim((string)($a['company_name'] ?? ''));
  8675. $bCn = trim((string)($b['company_name'] ?? ''));
  8676. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8677. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8678. if ($aSupplierWin !== $bSupplierWin) {
  8679. return $aSupplierWin ? -1 : 1;
  8680. }
  8681. $c = strcmp($aCn, $bCn);
  8682. if ($c !== 0) {
  8683. return $c;
  8684. }
  8685. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8686. return !empty($a['picked']) ? -1 : 1;
  8687. }
  8688. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8689. if ($c !== 0) {
  8690. return $c;
  8691. }
  8692. return 0;
  8693. });
  8694. return $lines;
  8695. }
  8696. /**
  8697. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8698. *
  8699. * @param array<int, array<string, mixed>> $quoteLines
  8700. */
  8701. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8702. {
  8703. $mon = (int)substr($ym, 5, 2);
  8704. $titleRow = $startRow;
  8705. $headerRow = $startRow + 1;
  8706. $dataStartRow = $startRow + 2;
  8707. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8708. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8709. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8710. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8711. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8712. ->setVertical(Alignment::VERTICAL_CENTER);
  8713. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8714. $col = 'A';
  8715. foreach ($headers as $h) {
  8716. $sheet->setCellValue($col . $headerRow, $h);
  8717. $col++;
  8718. }
  8719. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8720. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8721. $rowNum = $dataStartRow;
  8722. if ($quoteLines === []) {
  8723. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8724. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8725. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8726. $rowNum = $dataStartRow + 1;
  8727. } else {
  8728. $i = 0;
  8729. foreach ($quoteLines as $line) {
  8730. $i++;
  8731. $sheet->setCellValue('A' . $rowNum, $i);
  8732. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8733. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8734. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8735. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8736. if ($line['amount_num'] !== null) {
  8737. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8738. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8739. } else {
  8740. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8741. }
  8742. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8743. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8744. if (!empty($line['picked'])) {
  8745. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8746. }
  8747. $rowNum++;
  8748. }
  8749. }
  8750. $lastRow = $rowNum - 1;
  8751. if ($lastRow >= $headerRow) {
  8752. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8753. 'borders' => [
  8754. 'allBorders' => [
  8755. 'borderStyle' => Border::BORDER_THIN,
  8756. 'color' => ['rgb' => '000000'],
  8757. ],
  8758. ],
  8759. ]);
  8760. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8761. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8762. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8763. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8764. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8765. if ($lastRow >= $dataStartRow) {
  8766. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8767. }
  8768. }
  8769. return $lastRow;
  8770. }
  8771. /**
  8772. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8773. */
  8774. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8775. {
  8776. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8777. return;
  8778. }
  8779. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8780. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8781. ->setVertical(Alignment::VERTICAL_CENTER);
  8782. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8783. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8784. ->setVertical(Alignment::VERTICAL_CENTER);
  8785. if ($lastCol > 'B') {
  8786. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8787. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8788. ->setVertical(Alignment::VERTICAL_CENTER);
  8789. }
  8790. }
  8791. /**
  8792. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8793. */
  8794. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8795. {
  8796. $s = trim($ccydh);
  8797. if ($s === '') {
  8798. return 'ORDER';
  8799. }
  8800. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8801. $s = trim($s, '._-');
  8802. if ($s === '') {
  8803. return 'ORDER';
  8804. }
  8805. if (function_exists('mb_substr')) {
  8806. return mb_substr($s, 0, 80, 'UTF-8');
  8807. }
  8808. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8809. }
  8810. /**
  8811. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8812. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8813. *
  8814. * @return array{objectKey: string, webPath: string}
  8815. */
  8816. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8817. {
  8818. $sid = (int)$scydgyId;
  8819. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8820. $y = date('Y');
  8821. $m = date('m');
  8822. $d = date('d');
  8823. $basename = $safeOrder . '_' . $sid . '.pdf';
  8824. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8825. return [
  8826. 'objectKey' => $objectKey,
  8827. 'webPath' => '/' . $objectKey,
  8828. ];
  8829. }
  8830. /**
  8831. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8832. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8833. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8834. *
  8835. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8836. */
  8837. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8838. {
  8839. if (!$this->isValidScydgyRowId($scydgyId)) {
  8840. return '';
  8841. }
  8842. $ids = trim((string)$scydgyId);
  8843. $prep = $this->prepareProcuremenDetailsView($ids);
  8844. if (!$prep['ok']) {
  8845. return '';
  8846. }
  8847. $ccydh = $prep['ccydh'];
  8848. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8849. $objectKey = $paths['objectKey'];
  8850. $webPath = $paths['webPath'];
  8851. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8852. $this->view->assign([
  8853. 'pdf_export' => 1,
  8854. 'pdfMetaLine' => $meta,
  8855. ]);
  8856. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8857. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8858. $this->view->engine->layout(false);
  8859. try {
  8860. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8861. } catch (\Throwable $e) {
  8862. if ($restoreLayout) {
  8863. $this->view->engine->layout($restoreLayout);
  8864. }
  8865. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8866. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8867. return '';
  8868. }
  8869. if ($restoreLayout) {
  8870. $this->view->engine->layout($restoreLayout);
  8871. }
  8872. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8873. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8874. if (!is_dir($tempDir)) {
  8875. @mkdir($tempDir, 0755, true);
  8876. }
  8877. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8878. try {
  8879. $mpdf = new \Mpdf\Mpdf([
  8880. 'mode' => 'utf-8',
  8881. 'format' => 'A4',
  8882. 'margin_left' => 12,
  8883. 'margin_right' => 12,
  8884. 'margin_top' => 14,
  8885. 'margin_bottom' => 14,
  8886. 'tempDir' => $tempDir,
  8887. 'autoScriptToLang' => true,
  8888. 'autoLangToFont' => true,
  8889. ]);
  8890. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8891. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8892. $mpdf->SetBasePath('http://127.0.0.1/');
  8893. $mpdf->WriteHTML($html);
  8894. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8895. } catch (\Throwable $e) {
  8896. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8897. if (is_file($tempPdf)) {
  8898. @unlink($tempPdf);
  8899. }
  8900. return '';
  8901. }
  8902. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8903. if ($ossUrl !== '') {
  8904. @unlink($tempPdf);
  8905. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8906. return $ossUrl;
  8907. }
  8908. $pi = pathinfo($objectKey);
  8909. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8910. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8911. if ($baseFile === '') {
  8912. @unlink($tempPdf);
  8913. return '';
  8914. }
  8915. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8916. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8917. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8918. @unlink($tempPdf);
  8919. return '';
  8920. }
  8921. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8922. if (!@copy($tempPdf, $fullPath)) {
  8923. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8924. @unlink($tempPdf);
  8925. return '';
  8926. }
  8927. @unlink($tempPdf);
  8928. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8929. return $webPath;
  8930. }
  8931. /**
  8932. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8933. */
  8934. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8935. {
  8936. if ($scydgyId <= 0 || $webPath === '') {
  8937. return;
  8938. }
  8939. try {
  8940. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8941. } catch (\Throwable $e) {
  8942. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8943. }
  8944. }
  8945. /**
  8946. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8947. *
  8948. * @param array<string, string> $vars
  8949. * @return array<string, string>
  8950. */
  8951. protected function normalizeSmsTemplateVars(array $vars): array
  8952. {
  8953. $out = [];
  8954. foreach ($vars as $k => $v) {
  8955. $out[(string)$k] = trim((string)$v);
  8956. }
  8957. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8958. $out['contact_name'] = $out['company_name'];
  8959. }
  8960. return $out;
  8961. }
  8962. /**
  8963. * 按手机号或公司名称查 customer 表联系人姓名
  8964. */
  8965. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8966. {
  8967. $phone = trim($phone);
  8968. $companyName = trim($companyName);
  8969. try {
  8970. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8971. $row = Db::table('customer')
  8972. ->where(function ($q) use ($phone) {
  8973. $q->where('phone', $phone)->whereOr('account', $phone);
  8974. })
  8975. ->order('id', 'asc')
  8976. ->find();
  8977. if (is_array($row)) {
  8978. $nm = trim((string)($row['username'] ?? ''));
  8979. if ($nm !== '') {
  8980. return $nm;
  8981. }
  8982. }
  8983. }
  8984. if ($companyName !== '') {
  8985. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8986. if (is_array($row)) {
  8987. return trim((string)($row['username'] ?? ''));
  8988. }
  8989. }
  8990. } catch (\Throwable $e) {
  8991. }
  8992. return '';
  8993. }
  8994. /**
  8995. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8996. */
  8997. protected function plainTextToHtmlEmailBody(string $text): string
  8998. {
  8999. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  9000. $parts = explode("\n", $text);
  9001. $out = [];
  9002. foreach ($parts as $line) {
  9003. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  9004. $out[] = $line;
  9005. } else {
  9006. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  9007. }
  9008. }
  9009. return implode("<br>\n", $out);
  9010. }
  9011. /**
  9012. * 短信场景:去掉链接类变量,避免误填 URL
  9013. *
  9014. * @param array<string, string> $vars
  9015. * @return array<string, string>
  9016. */
  9017. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  9018. {
  9019. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  9020. return $vars;
  9021. }
  9022. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  9023. $vars[$k] = '';
  9024. }
  9025. return $vars;
  9026. }
  9027. /**
  9028. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  9029. *
  9030. * @param array<string, string> $vars
  9031. */
  9032. protected function renderNotifyTemplate(string $scene, array $vars): string
  9033. {
  9034. $vars = $this->normalizeSmsTemplateVars($vars);
  9035. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  9036. $row = $this->loadNotifyTemplateRow($scene);
  9037. if ($row === null) {
  9038. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9039. }
  9040. $tpl = trim((string)($row['content'] ?? ''));
  9041. if ($tpl === '') {
  9042. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9043. }
  9044. foreach ($vars as $k => $v) {
  9045. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  9046. }
  9047. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  9048. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  9049. return $tpl;
  9050. }
  9051. protected function resolveProcuremenEmailSubject(string $scene): string
  9052. {
  9053. $map = [
  9054. 'review_email' => '您有新的协助加工订单',
  9055. ];
  9056. $subject = trim((string)($map[$scene] ?? ''));
  9057. if ($subject === '') {
  9058. $this->error('未配置邮件主题:' . $scene);
  9059. }
  9060. return $subject;
  9061. }
  9062. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  9063. {
  9064. $map = [
  9065. 'review_email' => '协助下发-邮箱',
  9066. 'review_sms' => '协助下发-短信',
  9067. 'confirm_ok' => '采购确认-通过',
  9068. 'confirm_fail' => '采购确认-未通过',
  9069. 'bid_open' => '开标双重验证',
  9070. ];
  9071. $label = $map[$scene] ?? $scene;
  9072. if ($titleRequired) {
  9073. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  9074. }
  9075. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  9076. }
  9077. /**
  9078. * 是否开启协助通知演练(不发真实短信/邮件)
  9079. */
  9080. protected function isProcuremenNotifyDryRun(): bool
  9081. {
  9082. return (bool)Config::get('procuremen_notify_dry_run');
  9083. }
  9084. /**
  9085. * @param array<string, mixed> $payload
  9086. */
  9087. protected function recordNotifyDryRunPreview(array $payload): void
  9088. {
  9089. $this->notifyDryRunPreview[] = $payload;
  9090. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9091. }
  9092. /**
  9093. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  9094. * @throws \Exception
  9095. */
  9096. protected function smsbao($phone, $content)
  9097. {
  9098. if ($this->isProcuremenNotifyDryRun()) {
  9099. $this->recordNotifyDryRunPreview([
  9100. 'scene' => 'sms_only',
  9101. 'phone' => $phone,
  9102. 'sms_content' => $content,
  9103. ]);
  9104. return;
  9105. }
  9106. $statusStr = [
  9107. '0' => '短信发送成功',
  9108. '-1' => '参数不全',
  9109. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  9110. '30' => '密码错误',
  9111. '40' => '账号不存在',
  9112. '41' => '余额不足',
  9113. '42' => '帐户已过期',
  9114. '43' => 'IP地址限制',
  9115. '50' => '内容含有敏感词',
  9116. ];
  9117. $smsapi = 'http://api.smsbao.com/';
  9118. $user = 'zhuwei123';
  9119. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  9120. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  9121. $result = @file_get_contents($sendurl);
  9122. if ($result === false) {
  9123. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9124. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9125. }
  9126. $result = trim((string)$result);
  9127. if ($result !== '0') {
  9128. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9129. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9130. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9131. }
  9132. }
  9133. }