Procuremen.php 377 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenSupplierScore;
  9. use app\common\library\ProcuremenTime;
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use think\Config;
  12. use think\Cache;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use think\Db;
  19. use think\Log;
  20. class Procuremen extends Backend
  21. {
  22. /**
  23. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  24. */
  25. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  26. /**
  27. * Procuremen模型对象
  28. * @var \app\admin\model\Procuremen
  29. */
  30. protected $model = null;
  31. /**
  32. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  33. */
  34. protected $notifyDryRunPreview = [];
  35. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  36. protected $procuremenRedisCache = null;
  37. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  38. protected $pickHiddenScydgySetCache = null;
  39. /** 邮件发送日志表结构已就绪缓存键 */
  40. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  41. /**
  42. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  43. * @var array
  44. */
  45. protected $noNeedRight = [
  46. 'pickreview', 'review', 'reviewcompanies',
  47. ];
  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, b.czlyq, 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. $this->ensurePurchaseOrderCzlyqColumn();
  784. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  785. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  786. try {
  787. $query = Db::table('purchase_order')->field($fields);
  788. $this->applyPurchaseOrderNotDeletedWhere($query);
  789. if ($stage === 'audit') {
  790. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  791. } elseif ($stage === 'confirm') {
  792. $this->applyPurchaseOrderConfirmStageWhere($query);
  793. } else {
  794. return [];
  795. }
  796. $query->order('pick_time', 'desc')->order('id', 'desc');
  797. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  798. $monthStart = $ym . '-01 00:00:00';
  799. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  800. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  801. }
  802. $rows = $query->select();
  803. } catch (\Throwable $e) {
  804. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  805. $rows = [];
  806. }
  807. return is_array($rows) ? $rows : [];
  808. }
  809. /**
  810. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  811. */
  812. protected function resolveProcuremenListStage(): string
  813. {
  814. $tab = trim((string)$this->request->request('wff_tab', ''));
  815. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  816. return $tab;
  817. }
  818. $action = strtolower((string)$this->request->action());
  819. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  820. return $action;
  821. }
  822. return 'pick';
  823. }
  824. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  825. {
  826. $rootTrue = rtrim((string)$this->request->root(true), '/');
  827. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  828. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  829. $indexPhpRoot = $rootTrue . '/index.php';
  830. }
  831. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  832. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  833. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  834. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  835. $this->view->assign('defaultYm', $defaultYm);
  836. $this->view->assign('sidebarYearMonths', $sidebar);
  837. $this->view->assign('procuremenStage', $stage);
  838. $this->view->assign('procuremenPageTitle', $pageTitle);
  839. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  840. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  841. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  842. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  843. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  844. }
  845. /**
  846. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  847. *
  848. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  849. */
  850. protected function buildProcuremenFilterOptions(string $stage): array
  851. {
  852. $buckets = [
  853. 'czlyq' => [],
  854. 'CCLBMMC' => [],
  855. 'cywyxm' => [],
  856. 'CGYMC' => [],
  857. ];
  858. $maxPerField = 300;
  859. try {
  860. if ($stage === 'pick') {
  861. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  862. return $buckets;
  863. }
  864. if (in_array($stage, ['audit', 'confirm'], true)) {
  865. $this->ensurePurchaseOrderCzlyqColumn();
  866. foreach (array_keys($buckets) as $field) {
  867. try {
  868. $query = Db::table('purchase_order')->field($field);
  869. $this->applyPurchaseOrderNotDeletedWhere($query);
  870. if ($stage === 'audit') {
  871. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  872. } else {
  873. $this->applyPurchaseOrderConfirmStageWhere($query);
  874. }
  875. $query->where($field, '<>', '')->whereNotNull($field);
  876. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  877. if (!is_array($vals)) {
  878. continue;
  879. }
  880. foreach ($vals as $v) {
  881. $v = trim((string)$v);
  882. if ($v !== '') {
  883. $buckets[$field][$v] = $v;
  884. }
  885. }
  886. } catch (\Throwable $e) {
  887. // 单字段失败不影响其它
  888. }
  889. }
  890. }
  891. } catch (\Throwable $e) {
  892. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  893. }
  894. foreach ($buckets as &$set) {
  895. if ($set !== []) {
  896. ksort($set, SORT_STRING);
  897. }
  898. }
  899. unset($set);
  900. return $buckets;
  901. }
  902. /**
  903. * filter JSON 是否含有效条件
  904. *
  905. * @param array<string, mixed> $filterArr
  906. */
  907. protected function procuremenFilterArrHasValue(array $filterArr): bool
  908. {
  909. foreach ($filterArr as $v) {
  910. if (is_array($v)) {
  911. if (array_filter($v, function ($x) {
  912. return $x !== '' && $x !== null;
  913. })) {
  914. return true;
  915. }
  916. } elseif ($v !== '' && $v !== null) {
  917. return true;
  918. }
  919. }
  920. return false;
  921. }
  922. /**
  923. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  924. *
  925. * @param array<string, mixed> $filterArr
  926. * @param array<string, mixed> $opArr
  927. */
  928. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  929. {
  930. if ($search !== '') {
  931. return false;
  932. }
  933. foreach ($filterArr as $fk => $fv) {
  934. if (is_array($fv)) {
  935. continue;
  936. }
  937. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  938. continue;
  939. }
  940. if ($fv === null) {
  941. continue;
  942. }
  943. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  944. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  945. if ($sym === '' || $sym === '=') {
  946. continue;
  947. }
  948. return false;
  949. }
  950. return true;
  951. }
  952. /**
  953. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  954. *
  955. * @param array<int, mixed> $rows
  956. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  957. */
  958. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  959. {
  960. $buckets = [
  961. 'czlyq' => [],
  962. 'CCLBMMC' => [],
  963. 'cywyxm' => [],
  964. 'CGYMC' => [],
  965. ];
  966. foreach ($rows as $r) {
  967. if (!is_array($r)) {
  968. continue;
  969. }
  970. foreach ($buckets as $field => &$set) {
  971. if (count($set) >= $maxPerField) {
  972. continue;
  973. }
  974. $v = trim((string)($r[$field] ?? ''));
  975. if ($v !== '') {
  976. $set[$v] = $v;
  977. }
  978. }
  979. unset($set);
  980. $full = true;
  981. foreach ($buckets as $set) {
  982. if (count($set) < $maxPerField) {
  983. $full = false;
  984. break;
  985. }
  986. }
  987. if ($full) {
  988. break;
  989. }
  990. }
  991. foreach ($buckets as &$set) {
  992. if ($set !== []) {
  993. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  994. $normalized = [];
  995. foreach ($set as $k => $v) {
  996. $s = trim((string)(is_scalar($v) ? $v : $k));
  997. if ($s === '') {
  998. continue;
  999. }
  1000. $normalized[$s] = $s;
  1001. }
  1002. ksort($normalized, SORT_STRING);
  1003. $set = $normalized;
  1004. }
  1005. }
  1006. unset($set);
  1007. return $buckets;
  1008. }
  1009. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1010. public function pick()
  1011. {
  1012. $this->request->filter(['strip_tags', 'trim']);
  1013. if (!$this->request->isAjax()) {
  1014. $this->assignProcuremenListPage('pick', '协助下发');
  1015. return $this->view->fetch('procuremen/index');
  1016. }
  1017. return $this->index();
  1018. }
  1019. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1020. public function audit()
  1021. {
  1022. $this->request->filter(['strip_tags', 'trim']);
  1023. if (!$this->request->isAjax()) {
  1024. $this->assignProcuremenListPage('audit', '确认供应商');
  1025. return $this->view->fetch('procuremen/index');
  1026. }
  1027. return $this->index();
  1028. }
  1029. /** 采购确认(定标) */
  1030. public function confirm()
  1031. {
  1032. $this->request->filter(['strip_tags', 'trim']);
  1033. if (!$this->request->isAjax()) {
  1034. $this->assignProcuremenListPage('confirm', '采购确认');
  1035. return $this->view->fetch('procuremen/index');
  1036. }
  1037. return $this->index();
  1038. }
  1039. /**
  1040. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1041. */
  1042. public function index()
  1043. {
  1044. $this->request->filter(['strip_tags', 'trim']);
  1045. if (!$this->request->isAjax()) {
  1046. $this->assignProcuremenListPage('pick', '协助下发');
  1047. return $this->view->fetch('procuremen/index');
  1048. }
  1049. if ($this->request->request('keyField')) {
  1050. return $this->selectpage();
  1051. }
  1052. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1053. $limit = max(10, min(500, (int)$limit));
  1054. $ym = $this->request->request('ym', '');
  1055. $ym = is_string($ym) ? trim($ym) : '';
  1056. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1057. $wffTab = $this->resolveProcuremenListStage();
  1058. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1059. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1060. ? $this->resolveProcuremenDefaultYm($wffTab)
  1061. : date('Y-m');
  1062. }
  1063. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1064. $ym = date('Y-m');
  1065. }
  1066. $monthStart = $ym . '-01 00:00:00';
  1067. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1068. $search = trim((string)$this->request->get('search', ''));
  1069. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1070. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1071. if (!is_array($filterArr)) {
  1072. $filterArr = [];
  1073. }
  1074. if (!is_array($opArr)) {
  1075. $opArr = [];
  1076. }
  1077. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1078. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1079. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1080. try {
  1081. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1082. if ($wffTab === 'audit') {
  1083. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1084. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1085. );
  1086. } elseif ($wffTab === 'confirm') {
  1087. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1088. if ($dbRows === []) {
  1089. try {
  1090. $dbRows = Db::table('purchase_order')
  1091. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1092. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1093. ->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%\')')
  1094. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1095. ->order('pick_time', 'desc')->order('id', 'desc')
  1096. ->select();
  1097. } catch (\Throwable $e) {
  1098. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1099. $dbRows = [];
  1100. }
  1101. }
  1102. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1103. if ($pool === []) {
  1104. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1105. }
  1106. } else {
  1107. $pool = $this->procuremenEnsureRedisPool();
  1108. if (!is_array($pool)) {
  1109. $pool = [];
  1110. }
  1111. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  1112. $hideSet = $this->loadPickHiddenScydgySet();
  1113. if ($pool !== [] && $hideSet !== []) {
  1114. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1115. if (!is_array($r)) {
  1116. return false;
  1117. }
  1118. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1119. return $id <= 0 || !isset($hideSet[$id]);
  1120. }));
  1121. }
  1122. $manualPool = $this->loadPickManualOrderRows();
  1123. if ($manualPool !== []) {
  1124. $pool = array_merge($pool, $manualPool);
  1125. }
  1126. if ($pool === []) {
  1127. return json([
  1128. 'total' => 0,
  1129. 'rows' => [],
  1130. ]);
  1131. }
  1132. }
  1133. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1134. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1135. $monthStart = $ym . '-01 00:00:00';
  1136. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1137. }
  1138. $filtered = $this->filterProcuremenIndexPool(
  1139. $pool,
  1140. $monthStart,
  1141. $monthEnd,
  1142. $applyMonthRange,
  1143. $search,
  1144. $filterArr,
  1145. $opArr,
  1146. $listTimePrimary
  1147. );
  1148. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1149. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1150. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1151. }
  1152. $sortField = 'ID';
  1153. if (is_string($sort) && $sort !== '') {
  1154. $parts = explode(',', $sort);
  1155. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1156. if ($sortField === '') {
  1157. $sortField = 'ID';
  1158. }
  1159. }
  1160. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1161. $nFiltered = count($filtered);
  1162. if ($nFiltered > 1) {
  1163. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1164. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1165. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1166. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1167. if ($ta === $tb) {
  1168. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1169. }
  1170. if ($ta === '') {
  1171. return 1;
  1172. }
  1173. if ($tb === '') {
  1174. return -1;
  1175. }
  1176. return strcmp($ta, $tb) * $ord;
  1177. });
  1178. } elseif ($sortField === 'ID') {
  1179. $sortKeys = [];
  1180. foreach ($filtered as $i => $row) {
  1181. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1182. }
  1183. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1184. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1185. } elseif ($sortField === 'CCYDH') {
  1186. usort($filtered, function ($a, $b) use ($ord) {
  1187. $sa = trim((string)($a['CCYDH'] ?? ''));
  1188. $sb = trim((string)($b['CCYDH'] ?? ''));
  1189. if ($sa === $sb) {
  1190. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1191. }
  1192. if ($sa === '') {
  1193. return 1;
  1194. }
  1195. if ($sb === '') {
  1196. return -1;
  1197. }
  1198. return strcmp($sa, $sb) * $ord;
  1199. });
  1200. } else {
  1201. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1202. $va = $a[$sortField] ?? null;
  1203. $vb = $b[$sortField] ?? null;
  1204. $sa = (string)$va;
  1205. $sb = (string)$vb;
  1206. if ($sa === $sb) {
  1207. return 0;
  1208. }
  1209. return strcmp($sa, $sb) * $ord;
  1210. });
  1211. }
  1212. }
  1213. $offset = max(0, (int)$offset);
  1214. $limit = max(1, (int)$limit);
  1215. $rows = array_slice($filtered, $offset, $limit);
  1216. foreach ($rows as &$rw) {
  1217. if (!is_array($rw)) {
  1218. continue;
  1219. }
  1220. $rid = (int)($rw['ID'] ?? 0);
  1221. $rw['_iss_out'] = ($wffTab !== 'pick');
  1222. }
  1223. unset($rw);
  1224. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1225. $idList = [];
  1226. foreach ($rows as $rw) {
  1227. if (!is_array($rw)) {
  1228. continue;
  1229. }
  1230. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1231. foreach ($rw['_order_merge_rows'] as $mr) {
  1232. $mid = (int)($mr['ID'] ?? 0);
  1233. if ($this->isValidScydgyRowId($mid)) {
  1234. $idList[$mid] = true;
  1235. }
  1236. }
  1237. }
  1238. $id = (int)($rw['ID'] ?? 0);
  1239. if ($this->isValidScydgyRowId($id)) {
  1240. $idList[$id] = true;
  1241. }
  1242. }
  1243. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1244. foreach ($rows as &$rw) {
  1245. if (!is_array($rw)) {
  1246. continue;
  1247. }
  1248. $mergeIds = [];
  1249. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1250. foreach ($rw['_order_merge_rows'] as $mr) {
  1251. $mid = (int)($mr['ID'] ?? 0);
  1252. if ($this->isValidScydgyRowId($mid)) {
  1253. $mergeIds[$mid] = true;
  1254. }
  1255. }
  1256. }
  1257. $rid = (int)($rw['ID'] ?? 0);
  1258. if ($this->isValidScydgyRowId($rid)) {
  1259. $mergeIds[$rid] = true;
  1260. }
  1261. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1262. $rw['po_detail_count'] = $s['cnt'];
  1263. $rw['po_amount_fill_cnt'] = $s['amt'];
  1264. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1265. }
  1266. unset($rw);
  1267. }
  1268. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1269. $idList = [];
  1270. foreach ($rows as $rw) {
  1271. if (!is_array($rw)) {
  1272. continue;
  1273. }
  1274. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1275. foreach ($rw['_order_merge_rows'] as $mr) {
  1276. $mid = (int)($mr['ID'] ?? 0);
  1277. if ($this->isValidScydgyRowId($mid)) {
  1278. $idList[$mid] = true;
  1279. }
  1280. }
  1281. }
  1282. $id = (int)($rw['ID'] ?? 0);
  1283. if ($this->isValidScydgyRowId($id)) {
  1284. $idList[$id] = true;
  1285. }
  1286. }
  1287. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1288. $bidOpenSet = [];
  1289. if ($wffTab === 'audit') {
  1290. $ccydhList = [];
  1291. foreach ($rows as $rw0) {
  1292. if (!is_array($rw0)) {
  1293. continue;
  1294. }
  1295. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1296. if ($c0 !== '') {
  1297. $ccydhList[] = $c0;
  1298. }
  1299. }
  1300. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1301. }
  1302. foreach ($rows as &$rw) {
  1303. if (!is_array($rw)) {
  1304. continue;
  1305. }
  1306. $mergeIds = [];
  1307. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1308. foreach ($rw['_order_merge_rows'] as $mr) {
  1309. $mid = (int)($mr['ID'] ?? 0);
  1310. if ($this->isValidScydgyRowId($mid)) {
  1311. $mergeIds[$mid] = true;
  1312. }
  1313. }
  1314. }
  1315. $rid = (int)($rw['ID'] ?? 0);
  1316. if ($this->isValidScydgyRowId($rid)) {
  1317. $mergeIds[$rid] = true;
  1318. }
  1319. $buckets = [];
  1320. foreach (array_keys($mergeIds) as $mid) {
  1321. if (isset($quoteBucket[$mid])) {
  1322. $buckets[] = $quoteBucket[$mid];
  1323. }
  1324. }
  1325. $supplierText = $buckets !== []
  1326. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1327. : '';
  1328. if ($wffTab === 'confirm') {
  1329. $rw['picked_supplier_name'] = $supplierText;
  1330. } else {
  1331. $rw['notify_supplier_text'] = $supplierText;
  1332. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1333. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1334. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1335. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1336. }
  1337. }
  1338. unset($rw);
  1339. }
  1340. if ($wffTab === 'all' && count($rows) > 0) {
  1341. $this->mergePurchaseOrder($rows);
  1342. }
  1343. if ($wffTab === 'pick' && count($rows) > 0) {
  1344. $this->mergePurchaseOrder($rows);
  1345. }
  1346. foreach ($rows as &$rwClean) {
  1347. if (is_array($rwClean)) {
  1348. unset($rwClean['_order_merge_rows']);
  1349. if (array_key_exists('NGZL', $rwClean)) {
  1350. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1351. }
  1352. }
  1353. }
  1354. unset($rwClean);
  1355. return json([
  1356. 'total' => count($filtered),
  1357. 'rows' => $rows,
  1358. 'activeYm' => $ym,
  1359. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1360. 'filterOptions' => (
  1361. (int)$offset === 0
  1362. && !$hasActiveSearch
  1363. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1364. )
  1365. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1366. : new \stdClass(),
  1367. ]);
  1368. } catch (\Throwable $e) {
  1369. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1370. return json([
  1371. 'total' => 0,
  1372. 'rows' => [],
  1373. ]);
  1374. }
  1375. }
  1376. /**
  1377. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1378. *
  1379. * @return array<int, true>
  1380. */
  1381. protected function loadPickHiddenScydgySet(): array
  1382. {
  1383. if ($this->pickHiddenScydgySetCache !== null) {
  1384. return $this->pickHiddenScydgySetCache;
  1385. }
  1386. $hideSet = [];
  1387. try {
  1388. $poIds = Db::table('purchase_order')
  1389. ->where(function ($q) {
  1390. $q->whereIn('wflow_status', array_merge(
  1391. ProcuremenStatus::wflowPendingConfirmValues(),
  1392. ProcuremenStatus::wflowPendingApprovalValues()
  1393. ))
  1394. ->whereOr(function ($q1) {
  1395. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1396. })
  1397. ->whereOr(function ($q2) {
  1398. $q2->whereNotNull('pick_time')
  1399. ->where('pick_time', '<>', '')
  1400. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1401. })
  1402. ->whereOr(function ($q3) {
  1403. $q3->whereNotNull('mod_rq')
  1404. ->where('mod_rq', '<>', '')
  1405. ->where('mod_rq', 'not like', '0000-00-00%');
  1406. });
  1407. })
  1408. ->column('scydgy_id');
  1409. if (is_array($poIds)) {
  1410. foreach ($poIds as $pid) {
  1411. $k = (int)$pid;
  1412. if ($k !== 0) {
  1413. $hideSet[$k] = true;
  1414. }
  1415. }
  1416. }
  1417. } catch (\Throwable $e) {
  1418. }
  1419. try {
  1420. $detIdsQuery = Db::table('purchase_order_detail');
  1421. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1422. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1423. if (is_array($detIds)) {
  1424. foreach ($detIds as $pid) {
  1425. $k = (int)$pid;
  1426. if ($this->isValidScydgyRowId($k)) {
  1427. $hideSet[$k] = true;
  1428. }
  1429. }
  1430. }
  1431. } catch (\Throwable $e) {
  1432. }
  1433. $this->pickHiddenScydgySetCache = $hideSet;
  1434. return $hideSet;
  1435. }
  1436. /**
  1437. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1438. *
  1439. * @return array<int, array<string, mixed>>
  1440. */
  1441. protected function loadPickManualOrderRows(): array
  1442. {
  1443. try {
  1444. $dbRows = Db::table('purchase_order')
  1445. ->where('scydgy_id', '<', 0)
  1446. ->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%\')')
  1447. ->order('scydgy_id', 'asc')
  1448. ->select();
  1449. } catch (\Throwable $e) {
  1450. try {
  1451. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1452. } catch (\Throwable $e2) {
  1453. return [];
  1454. }
  1455. }
  1456. if (!is_array($dbRows) || $dbRows === []) {
  1457. return [];
  1458. }
  1459. $detailSidSet = [];
  1460. try {
  1461. $negIds = [];
  1462. foreach ($dbRows as $dbRow) {
  1463. if (!is_array($dbRow)) {
  1464. continue;
  1465. }
  1466. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1467. if ($sid < 0) {
  1468. $negIds[$sid] = true;
  1469. }
  1470. }
  1471. if ($negIds !== []) {
  1472. $detQuery = Db::table('purchase_order_detail')
  1473. ->where('scydgy_id', 'in', array_keys($negIds));
  1474. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1475. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1476. if (is_array($detRows)) {
  1477. foreach ($detRows as $did) {
  1478. $detailSidSet[(int)$did] = true;
  1479. }
  1480. }
  1481. }
  1482. } catch (\Throwable $e) {
  1483. }
  1484. $pool = [];
  1485. foreach ($dbRows as $dbRow) {
  1486. if (!is_array($dbRow)) {
  1487. continue;
  1488. }
  1489. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1490. if ($sid >= 0) {
  1491. continue;
  1492. }
  1493. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1494. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1495. continue;
  1496. }
  1497. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1498. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1499. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1500. continue;
  1501. }
  1502. if (isset($detailSidSet[$sid])) {
  1503. continue;
  1504. }
  1505. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1506. $r['_is_manual'] = 1;
  1507. $pool[] = $r;
  1508. }
  1509. return $pool;
  1510. }
  1511. /**
  1512. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1513. */
  1514. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1515. {
  1516. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1517. foreach ($keys as $k) {
  1518. $t = trim((string)($row[$k] ?? ''));
  1519. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1520. return $t;
  1521. }
  1522. }
  1523. return '';
  1524. }
  1525. /**
  1526. * 分配手工新增工序行 ID(负数递减)
  1527. */
  1528. protected function allocateManualScydgyId(): int
  1529. {
  1530. try {
  1531. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1532. $min = (int)$min;
  1533. return $min < 0 ? $min - 1 : -1;
  1534. } catch (\Throwable $e) {
  1535. return -1;
  1536. }
  1537. }
  1538. /**
  1539. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1540. */
  1541. protected function allocateManualOrderCcydh(): string
  1542. {
  1543. $prefix = 'YW' . date('Ymd');
  1544. $maxSeq = 0;
  1545. try {
  1546. $rows = Db::table('purchase_order')
  1547. ->where('CCYDH', 'like', $prefix . '%')
  1548. ->column('CCYDH');
  1549. if (is_array($rows)) {
  1550. foreach ($rows as $ccydh) {
  1551. $ccydh = trim((string)$ccydh);
  1552. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1553. $maxSeq = max($maxSeq, (int)$m[1]);
  1554. }
  1555. }
  1556. }
  1557. } catch (\Throwable $e) {
  1558. }
  1559. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1560. }
  1561. /**
  1562. * purchase_order.mod_rq 是否有有效软删除时间
  1563. */
  1564. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1565. {
  1566. $t = trim((string)$modRq);
  1567. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1568. }
  1569. /**
  1570. * 列表行 → purchase_order 写入字段
  1571. *
  1572. * @return array<string, mixed>
  1573. */
  1574. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1575. {
  1576. return [
  1577. 'scydgy_id' => $scydgyId,
  1578. 'CCYDH' => $row['CCYDH'] ?? null,
  1579. 'CYJMC' => $row['CYJMC'] ?? null,
  1580. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1581. 'CDXMC' => $row['CDXMC'] ?? null,
  1582. 'CGYBH' => $row['CGYBH'] ?? null,
  1583. 'CGYMC' => $row['CGYMC'] ?? null,
  1584. 'CDW' => $row['CDW'] ?? null,
  1585. 'czlyq' => $row['czlyq'] ?? null,
  1586. 'NGZL' => $row['NGZL'] ?? null,
  1587. 'CDF' => $row['CDF'] ?? null,
  1588. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1589. 'MBZ' => $row['MBZ'] ?? null,
  1590. 'bwjg' => $row['bwjg'] ?? null,
  1591. 'iStatus' => $row['iStatus'] ?? null,
  1592. 'dStamp' => $row['dStamp'] ?? null,
  1593. 'dputrecord' => $row['dputrecord'] ?? null,
  1594. 'cywyxm' => $row['cywyxm'] ?? null,
  1595. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1596. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1597. ];
  1598. }
  1599. /**
  1600. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1601. *
  1602. * @return array{po:?array<string,mixed>, hidden:bool}
  1603. */
  1604. protected function resolvePickRowPoContext(int $sid): array
  1605. {
  1606. $po = null;
  1607. try {
  1608. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1609. if (is_array($found)) {
  1610. $po = $found;
  1611. }
  1612. } catch (\Throwable $e) {
  1613. }
  1614. $hideSet = $this->loadPickHiddenScydgySet();
  1615. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1616. }
  1617. /**
  1618. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1619. */
  1620. protected function assertPickRowCanDelete(int $sid, array $row): void
  1621. {
  1622. $ctx = $this->resolvePickRowPoContext($sid);
  1623. $po = $ctx['po'];
  1624. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1625. return;
  1626. }
  1627. if (is_array($po)) {
  1628. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1629. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1630. }
  1631. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1632. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1633. }
  1634. }
  1635. if ($ctx['hidden']) {
  1636. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1637. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1638. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1639. }
  1640. }
  1641. /**
  1642. * 初选直接完结前校验
  1643. */
  1644. protected function assertPickRowCanComplete(int $sid, array $row): void
  1645. {
  1646. $ctx = $this->resolvePickRowPoContext($sid);
  1647. $po = $ctx['po'];
  1648. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1649. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1650. }
  1651. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1652. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1653. }
  1654. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1655. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1656. }
  1657. }
  1658. /**
  1659. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1660. */
  1661. protected function softDeleteProcuremenPickRow(array $row): void
  1662. {
  1663. $sid = $this->extractScydgyRowId($row);
  1664. if (!$this->isValidScydgyRowId($sid)) {
  1665. throw new \InvalidArgumentException('无效的行主键');
  1666. }
  1667. $this->assertPickRowCanDelete($sid, $row);
  1668. $po = $this->resolvePickRowPoContext($sid)['po'];
  1669. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1670. return;
  1671. }
  1672. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1673. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1674. }
  1675. $now = date('Y-m-d H:i:s');
  1676. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1677. if (is_array($exists)) {
  1678. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1679. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1680. } else {
  1681. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1682. $data['mod_rq'] = $now;
  1683. $data['createtime'] = $now;
  1684. Db::table('purchase_order')->insert($data);
  1685. $poIdLog = (int)Db::getLastInsID();
  1686. }
  1687. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1688. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1689. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1690. if ($gymcLog !== '') {
  1691. $logTail .= ' / ' . $gymcLog;
  1692. }
  1693. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1694. }
  1695. /**
  1696. * 手工新增协助工序(写入 purchase_order)
  1697. *
  1698. * @param array<string, mixed> $params
  1699. * @return int scydgy_id
  1700. */
  1701. protected function saveManualPickOrder(array $params): int
  1702. {
  1703. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1704. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1705. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1706. if ($ccydh === '') {
  1707. $ccydh = $this->allocateManualOrderCcydh();
  1708. }
  1709. $now = date('Y-m-d H:i:s');
  1710. $sid = $this->allocateManualScydgyId();
  1711. $data = [
  1712. 'scydgy_id' => $sid,
  1713. 'CCYDH' => $ccydh,
  1714. 'CYJMC' => $cyjmc,
  1715. 'CGYMC' => $cgymc,
  1716. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1717. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1718. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1719. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1720. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1721. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1722. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1723. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1724. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1725. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1726. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1727. 'createtime' => $now,
  1728. 'dStamp' => $now,
  1729. 'dputrecord' => $now,
  1730. ];
  1731. Db::table('purchase_order')->insert($data);
  1732. $poId = (int)Db::getLastInsID();
  1733. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1734. return $sid;
  1735. }
  1736. protected function formatProcuremenRowLabel(array $row): string
  1737. {
  1738. $dh = trim((string)($row['CCYDH'] ?? ''));
  1739. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1740. if ($dh !== '' && $gymc !== '') {
  1741. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1742. }
  1743. if ($dh !== '') {
  1744. return '订单「' . $dh . '」';
  1745. }
  1746. if ($gymc !== '') {
  1747. return '工序「' . $gymc . '」';
  1748. }
  1749. $id = $this->extractScydgyRowId($row);
  1750. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1751. }
  1752. /**
  1753. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1754. */
  1755. protected function extractScydgyRowId(array $row): int
  1756. {
  1757. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  1758. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  1759. return (int)$row['scydgy_id'];
  1760. }
  1761. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  1762. return (int)$row['SCYDGY_ID'];
  1763. }
  1764. return (int)($row['ID'] ?? $row['id'] ?? 0);
  1765. }
  1766. protected function isValidScydgyRowId(int $id): bool
  1767. {
  1768. return ProcuremenGuard::isValidScydgyId($id);
  1769. }
  1770. protected function isManualScydgyRowId(int $id): bool
  1771. {
  1772. return $id < 0;
  1773. }
  1774. /**
  1775. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1776. *
  1777. * @param int[] $scydgyIds
  1778. * @return array<int, string[]>
  1779. */
  1780. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1781. {
  1782. $out = [];
  1783. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1784. if ($scydgyIds === []) {
  1785. return $out;
  1786. }
  1787. try {
  1788. $rows = Db::table('purchase_order_detail')
  1789. ->where('scydgy_id', 'in', $scydgyIds)
  1790. ->field('scydgy_id,company_name')
  1791. ->order('company_name', 'asc')
  1792. ->select();
  1793. } catch (\Throwable $e) {
  1794. $rows = [];
  1795. }
  1796. if (!is_array($rows)) {
  1797. return $out;
  1798. }
  1799. foreach ($rows as $r) {
  1800. if (!is_array($r)) {
  1801. continue;
  1802. }
  1803. $sid = (int)($r['scydgy_id'] ?? 0);
  1804. $cn = trim((string)($r['company_name'] ?? ''));
  1805. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1806. continue;
  1807. }
  1808. if (!isset($out[$sid])) {
  1809. $out[$sid] = [];
  1810. }
  1811. if (!in_array($cn, $out[$sid], true)) {
  1812. $out[$sid][] = $cn;
  1813. }
  1814. }
  1815. return $out;
  1816. }
  1817. /**
  1818. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1819. *
  1820. * @param string[] $names
  1821. */
  1822. protected function formatNotifySupplierDisplay(array $names): string
  1823. {
  1824. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1825. return trim((string)$n);
  1826. }, $names))));
  1827. if ($names === []) {
  1828. return '';
  1829. }
  1830. sort($names, SORT_STRING);
  1831. return implode("\n", $names);
  1832. }
  1833. /**
  1834. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1835. *
  1836. * @param int[] $scydgyIds
  1837. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1838. */
  1839. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1840. {
  1841. $out = [];
  1842. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1843. if ($scydgyIds === []) {
  1844. return $out;
  1845. }
  1846. try {
  1847. $rows = Db::table('purchase_order_detail')
  1848. ->where('scydgy_id', 'in', $scydgyIds)
  1849. ->field('scydgy_id,company_name,amount')
  1850. ->select();
  1851. } catch (\Throwable $e) {
  1852. $rows = [];
  1853. }
  1854. if (!is_array($rows)) {
  1855. return $out;
  1856. }
  1857. foreach ($rows as $r) {
  1858. if (!is_array($r)) {
  1859. continue;
  1860. }
  1861. $sid = (int)($r['scydgy_id'] ?? 0);
  1862. $cn = trim((string)($r['company_name'] ?? ''));
  1863. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1864. continue;
  1865. }
  1866. if (!isset($out[$sid])) {
  1867. $out[$sid] = ['all' => [], 'quoted' => []];
  1868. }
  1869. $out[$sid]['all'][$cn] = true;
  1870. $am = trim((string)($r['amount'] ?? ''));
  1871. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1872. $out[$sid]['quoted'][$cn] = true;
  1873. }
  1874. }
  1875. return $out;
  1876. }
  1877. /**
  1878. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1879. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1880. */
  1881. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1882. {
  1883. $merged = ['all' => [], 'quoted' => []];
  1884. foreach ($buckets as $b) {
  1885. if (!is_array($b)) {
  1886. continue;
  1887. }
  1888. foreach ($b['all'] ?? [] as $cn => $_) {
  1889. $merged['all'][$cn] = true;
  1890. }
  1891. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1892. $merged['quoted'][$cn] = true;
  1893. }
  1894. }
  1895. return $merged;
  1896. }
  1897. /**
  1898. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1899. */
  1900. protected function formatQuotedSupplierLines(array $bucket): string
  1901. {
  1902. $all = array_keys($bucket['all'] ?? []);
  1903. if ($all === []) {
  1904. return '';
  1905. }
  1906. sort($all, SORT_STRING);
  1907. $lines = [];
  1908. foreach ($all as $cn) {
  1909. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1910. $lines[] = $cn . '(' . $status . ')';
  1911. }
  1912. return implode("\n", $lines);
  1913. }
  1914. /**
  1915. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1916. */
  1917. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1918. {
  1919. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1920. $this->view->engine->layout(false);
  1921. try {
  1922. $bodyHtml = $this->view->fetch($view);
  1923. $this->view->assign('dialogBody', $bodyHtml);
  1924. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1925. return $this->view->fetch('procuremen/dialog_lite_shell');
  1926. } finally {
  1927. if ($restoreLayout) {
  1928. $this->view->engine->layout($restoreLayout);
  1929. }
  1930. }
  1931. }
  1932. /**
  1933. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1934. */
  1935. protected function resolveBundleSysRq(array $bundle): string
  1936. {
  1937. foreach ($bundle['pos'] ?? [] as $po) {
  1938. if (!is_array($po)) {
  1939. continue;
  1940. }
  1941. $sr = trim((string)($po['sys_rq'] ?? ''));
  1942. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1943. return $sr;
  1944. }
  1945. }
  1946. return '';
  1947. }
  1948. /**
  1949. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1950. */
  1951. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1952. {
  1953. $raw = trim((string)$sysRq);
  1954. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1955. return true;
  1956. }
  1957. $ts = strtotime(str_replace('T', ' ', $raw));
  1958. if ($ts === false || $ts <= 0) {
  1959. return true;
  1960. }
  1961. return time() >= $ts;
  1962. }
  1963. /**
  1964. * 开标前校验:必须已过报价截止时间
  1965. *
  1966. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1967. */
  1968. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1969. {
  1970. $sysRq = $this->resolveBundleSysRq($bundle);
  1971. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1972. $this->error('未到招标截止日期');
  1973. }
  1974. }
  1975. /**
  1976. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1977. *
  1978. * @param array<string, mixed> $d
  1979. * @param string $deliveryYmd
  1980. */
  1981. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1982. {
  1983. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1984. return max(0, (int)$d['lead_days']);
  1985. }
  1986. if ($deliveryYmd === '') {
  1987. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1988. }
  1989. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1990. return null;
  1991. }
  1992. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1993. $t2 = strtotime($m[1] . ' 00:00:00');
  1994. if ($t1 === false || $t2 === false) {
  1995. return null;
  1996. }
  1997. return max(0, (int)round(($t2 - $t1) / 86400));
  1998. }
  1999. /**
  2000. * @param int|null $days
  2001. */
  2002. protected function formatProcuremenLeadDaysText($days): string
  2003. {
  2004. if ($days === null || $days === '') {
  2005. return '未填写';
  2006. }
  2007. if (!is_numeric($days)) {
  2008. return '未填写';
  2009. }
  2010. return ((int)$days) . '天';
  2011. }
  2012. /**
  2013. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2014. *
  2015. * @param array<string, mixed> $line
  2016. */
  2017. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2018. {
  2019. $amountFilled = !empty($line['amount_filled']);
  2020. $deliveryFilled = !empty($line['delivery_filled']);
  2021. $leadFilled = !empty($line['lead_days_filled']);
  2022. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2023. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2024. $line['amount_show'] = '';
  2025. if (array_key_exists('amount_text', $line)) {
  2026. $line['amount_text'] = $line['unit_price_text'];
  2027. }
  2028. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2029. $line['delivery_show'] = $deliveryText;
  2030. if (array_key_exists('delivery_text', $line)) {
  2031. $line['delivery_text'] = $deliveryText;
  2032. }
  2033. $line['delivery_ymd'] = '';
  2034. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2035. $line['lead_days_show'] = $leadText;
  2036. $line['lead_days_text'] = $leadText;
  2037. $line['lead_days'] = '';
  2038. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2039. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2040. $line['subtotal_num'] = null;
  2041. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2042. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2043. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2044. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2045. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2046. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2047. $line['amount_filled'] = false;
  2048. $line['delivery_filled'] = false;
  2049. $line['lead_days_filled'] = false;
  2050. $line['is_quoted'] = false;
  2051. if (array_key_exists('quote_label', $line)) {
  2052. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2053. }
  2054. }
  2055. protected function ensurePurchaseOrderBidOpenTable(): void
  2056. {
  2057. try {
  2058. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2059. } catch (\Throwable $e) {
  2060. Db::execute(
  2061. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2062. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2063. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2064. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2065. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2066. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2067. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2068. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2069. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2070. `createtime` datetime DEFAULT NULL,
  2071. PRIMARY KEY (`id`),
  2072. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2073. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2074. );
  2075. }
  2076. }
  2077. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2078. {
  2079. $ccydh = trim($ccydh);
  2080. if ($ccydh === '') {
  2081. return false;
  2082. }
  2083. $this->ensurePurchaseOrderBidOpenTable();
  2084. try {
  2085. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2086. return is_array($row);
  2087. } catch (\Throwable $e) {
  2088. return false;
  2089. }
  2090. }
  2091. /**
  2092. * 批量查询订单是否已开标验证
  2093. *
  2094. * @param array<int, string> $ccydhs
  2095. * @return array<string, bool> ccydh => true
  2096. */
  2097. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2098. {
  2099. $set = [];
  2100. $list = [];
  2101. foreach ($ccydhs as $c) {
  2102. $c = trim((string)$c);
  2103. if ($c !== '') {
  2104. $list[$c] = true;
  2105. }
  2106. }
  2107. if ($list === []) {
  2108. return $set;
  2109. }
  2110. $this->ensurePurchaseOrderBidOpenTable();
  2111. try {
  2112. $rows = Db::table('purchase_order_bid_open')
  2113. ->where('ccydh', 'in', array_keys($list))
  2114. ->field('ccydh')
  2115. ->select();
  2116. foreach ($rows as $row) {
  2117. if (!is_array($row)) {
  2118. continue;
  2119. }
  2120. $c = trim((string)($row['ccydh'] ?? ''));
  2121. if ($c !== '') {
  2122. $set[$c] = true;
  2123. }
  2124. }
  2125. } catch (\Throwable $e) {
  2126. return [];
  2127. }
  2128. return $set;
  2129. }
  2130. /**
  2131. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2132. *
  2133. * @param array<string, mixed> $group
  2134. */
  2135. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2136. {
  2137. if ($quoteVisible) {
  2138. $group['remark_quote_pending'] = 0;
  2139. return;
  2140. }
  2141. $group['remark'] = '';
  2142. $group['remark_quote_pending'] = 0;
  2143. }
  2144. /**
  2145. * @param array{ccydh?:string} $bundle
  2146. */
  2147. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2148. {
  2149. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2150. }
  2151. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2152. {
  2153. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  2154. }
  2155. protected function loadBidOpenAdminUser(int $adminId): ?array
  2156. {
  2157. if ($adminId <= 0) {
  2158. return null;
  2159. }
  2160. try {
  2161. $row = Db::name('admin')->where('id', $adminId)->find();
  2162. } catch (\Throwable $e) {
  2163. return null;
  2164. }
  2165. if (!is_array($row)) {
  2166. return null;
  2167. }
  2168. $status = strtolower(trim((string)($row['status'] ?? '')));
  2169. if ($status !== '' && $status !== 'normal') {
  2170. return null;
  2171. }
  2172. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2173. return null;
  2174. }
  2175. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2176. if (!preg_match('/^1\d{10}$/', $phone)) {
  2177. return null;
  2178. }
  2179. $name = trim((string)($row['nickname'] ?? ''));
  2180. if ($name === '') {
  2181. $name = trim((string)($row['username'] ?? ''));
  2182. }
  2183. return [
  2184. 'id' => (int)$row['id'],
  2185. 'username' => trim((string)($row['username'] ?? '')),
  2186. 'nickname' => $name,
  2187. 'mobile' => $phone,
  2188. ];
  2189. }
  2190. /**
  2191. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2192. */
  2193. protected function bidOpenVerifierAuthGroupRootId(): int
  2194. {
  2195. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2196. return $id > 0 ? $id : 10;
  2197. }
  2198. /**
  2199. * @return int[]
  2200. */
  2201. protected function loadBidOpenVerifierAuthGroupIds(): array
  2202. {
  2203. static $memo = [];
  2204. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2205. if (isset($memo[$rootId])) {
  2206. return $memo[$rootId];
  2207. }
  2208. try {
  2209. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2210. } catch (\Throwable $e) {
  2211. $memo[$rootId] = [$rootId];
  2212. return $memo[$rootId];
  2213. }
  2214. if (!is_array($groups) || $groups === []) {
  2215. $memo[$rootId] = [$rootId];
  2216. return $memo[$rootId];
  2217. }
  2218. $groupList = [];
  2219. foreach ($groups as $g) {
  2220. if (is_array($g)) {
  2221. $groupList[] = $g;
  2222. }
  2223. }
  2224. if ($groupList === []) {
  2225. $memo[$rootId] = [$rootId];
  2226. return $memo[$rootId];
  2227. }
  2228. $tree = \fast\Tree::instance();
  2229. $tree->init($groupList);
  2230. $ids = $tree->getChildrenIds($rootId, true);
  2231. if (!is_array($ids) || $ids === []) {
  2232. $memo[$rootId] = [$rootId];
  2233. return $memo[$rootId];
  2234. }
  2235. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2236. return $memo[$rootId];
  2237. }
  2238. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2239. {
  2240. if ($adminId <= 0) {
  2241. return false;
  2242. }
  2243. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2244. if ($groupIds === []) {
  2245. return false;
  2246. }
  2247. try {
  2248. return (bool)Db::name('auth_group_access')
  2249. ->where('uid', $adminId)
  2250. ->where('group_id', 'in', $groupIds)
  2251. ->count();
  2252. } catch (\Throwable $e) {
  2253. return false;
  2254. }
  2255. }
  2256. /**
  2257. * @return array<int, array<string, mixed>>
  2258. */
  2259. protected function listBidOpenVerifierCandidates(): array
  2260. {
  2261. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2262. if ($groupIds === []) {
  2263. return [];
  2264. }
  2265. try {
  2266. $adminIds = Db::name('auth_group_access')
  2267. ->where('group_id', 'in', $groupIds)
  2268. ->column('uid');
  2269. } catch (\Throwable $e) {
  2270. $adminIds = [];
  2271. }
  2272. $adminIds = is_array($adminIds)
  2273. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2274. : [];
  2275. if ($adminIds === []) {
  2276. return [];
  2277. }
  2278. try {
  2279. $rows = Db::name('admin')
  2280. ->where('status', 'normal')
  2281. ->where('id', 'in', $adminIds)
  2282. ->where('mobile', '<>', '')
  2283. ->order('id', 'asc')
  2284. ->select();
  2285. } catch (\Throwable $e) {
  2286. return [];
  2287. }
  2288. if (!is_array($rows)) {
  2289. return [];
  2290. }
  2291. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2292. $out = [];
  2293. foreach ($rows as $row) {
  2294. if (!is_array($row)) {
  2295. continue;
  2296. }
  2297. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2298. if ($one === null) {
  2299. continue;
  2300. }
  2301. $out[] = [
  2302. 'id' => $one['id'],
  2303. 'username' => $one['username'],
  2304. 'nickname' => $one['nickname'],
  2305. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2306. 'mobile' => mask_phone($one['mobile']),
  2307. ];
  2308. }
  2309. return $out;
  2310. }
  2311. /**
  2312. * @param int[] $adminIds
  2313. * @return array<int, string>
  2314. */
  2315. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2316. {
  2317. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2318. if ($adminIds === []) {
  2319. return [];
  2320. }
  2321. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2322. try {
  2323. $rows = Db::name('auth_group_access')
  2324. ->alias('aga')
  2325. ->join('auth_group ag', 'aga.group_id = ag.id')
  2326. ->where('aga.uid', 'in', $adminIds)
  2327. ->where('aga.group_id', 'in', $groupIds)
  2328. ->field('aga.uid,ag.name')
  2329. ->order('aga.uid', 'asc')
  2330. ->order('aga.group_id', 'asc')
  2331. ->select();
  2332. } catch (\Throwable $e) {
  2333. return [];
  2334. }
  2335. if (!is_array($rows)) {
  2336. return [];
  2337. }
  2338. $out = [];
  2339. foreach ($rows as $row) {
  2340. if (!is_array($row)) {
  2341. continue;
  2342. }
  2343. $uid = (int)($row['uid'] ?? 0);
  2344. $name = trim((string)($row['name'] ?? ''));
  2345. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2346. continue;
  2347. }
  2348. $out[$uid] = $name;
  2349. }
  2350. return $out;
  2351. }
  2352. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2353. {
  2354. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2355. }
  2356. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2357. {
  2358. return 'procuremen_bidopen_wait_' . $adminId;
  2359. }
  2360. protected function renderBidOpenVerifySms(string $code): string
  2361. {
  2362. $tpl = '';
  2363. try {
  2364. $row = $this->loadNotifyTemplateRow('bid_open');
  2365. if (is_array($row)) {
  2366. $tpl = trim((string)($row['content'] ?? ''));
  2367. }
  2368. } catch (\Throwable $e) {
  2369. $tpl = '';
  2370. }
  2371. if ($tpl === '') {
  2372. $tpl = '【可集达】您的短信验证码是{code}';
  2373. }
  2374. return str_replace('{code}', $code, $tpl);
  2375. }
  2376. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2377. {
  2378. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2379. }
  2380. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2381. {
  2382. $code = trim($code);
  2383. if (!preg_match('/^\d{6}$/', $code)) {
  2384. return false;
  2385. }
  2386. $mock = Config::get('mproc.mock_sms_code');
  2387. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2388. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2389. return true;
  2390. }
  2391. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2392. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2393. return false;
  2394. }
  2395. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2396. return true;
  2397. }
  2398. /**
  2399. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2400. */
  2401. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2402. {
  2403. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2404. if ($ccydh === '') {
  2405. throw new \InvalidArgumentException('订单号无效');
  2406. }
  2407. $this->ensurePurchaseOrderBidOpenTable();
  2408. list($operatorId, $operatorName) = $this->GetUseName();
  2409. $now = date('Y-m-d H:i:s');
  2410. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2411. $payload = [
  2412. 'ccydh' => $ccydh,
  2413. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2414. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2415. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2416. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2417. 'operator_id' => (int)$operatorId,
  2418. 'operator_name' => trim((string)$operatorName),
  2419. 'createtime' => $now,
  2420. ];
  2421. if (is_array($exists)) {
  2422. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2423. } else {
  2424. Db::table('purchase_order_bid_open')->insert($payload);
  2425. }
  2426. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2427. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2428. $orderPart = '(订单' . $ccydh . ')';
  2429. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2430. $seenSid = [];
  2431. foreach ($bundle['pos'] ?? [] as $poRow) {
  2432. if (!is_array($poRow)) {
  2433. continue;
  2434. }
  2435. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2436. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2437. continue;
  2438. }
  2439. $seenSid[$sid] = true;
  2440. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2441. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2442. }
  2443. if ($seenSid === []) {
  2444. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2445. if ($this->isValidScydgyRowId($anchor)) {
  2446. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2447. }
  2448. }
  2449. // 开标通过后计算并写入供应商服务评分
  2450. try {
  2451. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  2452. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  2453. } catch (\Throwable $e) {
  2454. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  2455. }
  2456. }
  2457. /**
  2458. * 报价行展示字段默认值(模板安全访问)
  2459. *
  2460. * @param array<string, mixed> $line
  2461. * @return array<string, mixed>
  2462. */
  2463. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2464. {
  2465. if (!array_key_exists('amount_quote_pending', $line)) {
  2466. $line['amount_quote_pending'] = 0;
  2467. }
  2468. if (!array_key_exists('delivery_quote_pending', $line)) {
  2469. $line['delivery_quote_pending'] = 0;
  2470. }
  2471. if (!array_key_exists('quote_before_deadline', $line)) {
  2472. $line['quote_before_deadline'] = 0;
  2473. }
  2474. if (!array_key_exists('amount_filled', $line)) {
  2475. $line['amount_filled'] = 0;
  2476. }
  2477. if (!array_key_exists('delivery_filled', $line)) {
  2478. $line['delivery_filled'] = 0;
  2479. }
  2480. if (!array_key_exists('lead_days_filled', $line)) {
  2481. $line['lead_days_filled'] = 0;
  2482. }
  2483. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2484. $line['lead_days_quote_pending'] = 0;
  2485. }
  2486. if (!array_key_exists('lead_days_show', $line)) {
  2487. $line['lead_days_show'] = '未填写';
  2488. }
  2489. if (!array_key_exists('lead_days_text', $line)) {
  2490. $line['lead_days_text'] = $line['lead_days_show'];
  2491. }
  2492. return $line;
  2493. }
  2494. /**
  2495. * 审核弹窗:按供应商汇总报价明细
  2496. *
  2497. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2498. * @return array<int, array<string, mixed>>
  2499. */
  2500. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2501. {
  2502. $sids = [];
  2503. foreach ($bundle['pos'] ?? [] as $po) {
  2504. if (!is_array($po)) {
  2505. continue;
  2506. }
  2507. $sid = (int)($po['scydgy_id'] ?? 0);
  2508. if ($this->isValidScydgyRowId($sid)) {
  2509. $sids[$sid] = true;
  2510. }
  2511. }
  2512. if ($sids === []) {
  2513. return [];
  2514. }
  2515. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2516. $gymcMap = [];
  2517. $qtyBySid = [];
  2518. $orderedSids = [];
  2519. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2520. if (!is_array($mr)) {
  2521. continue;
  2522. }
  2523. $gid = $this->extractScydgyRowId($mr);
  2524. if ($this->isValidScydgyRowId($gid)) {
  2525. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2526. $orderedSids[] = $gid;
  2527. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2528. if ($qty === '') {
  2529. $qty = trim((string)($mr['NGZL'] ?? ''));
  2530. }
  2531. $qtyBySid[$gid] = $qty;
  2532. }
  2533. }
  2534. foreach ($bundle['pos'] ?? [] as $po) {
  2535. if (!is_array($po)) {
  2536. continue;
  2537. }
  2538. $gid = (int)($po['scydgy_id'] ?? 0);
  2539. if ($this->isValidScydgyRowId($gid)) {
  2540. $nm = trim((string)($po['CGYMC'] ?? ''));
  2541. if ($nm !== '') {
  2542. $gymcMap[$gid] = $nm;
  2543. }
  2544. if (!in_array($gid, $orderedSids, true)) {
  2545. $orderedSids[] = $gid;
  2546. }
  2547. }
  2548. }
  2549. try {
  2550. $detailsQuery = Db::table('purchase_order_detail')
  2551. ->where('scydgy_id', 'in', array_keys($sids));
  2552. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2553. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2554. } catch (\Throwable $e) {
  2555. try {
  2556. $detailsQuery = Db::table('purchase_order_detail')
  2557. ->where('scydgy_id', 'in', array_keys($sids));
  2558. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2559. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2560. } catch (\Throwable $e2) {
  2561. $details = [];
  2562. }
  2563. }
  2564. if (!is_array($details)) {
  2565. $details = [];
  2566. }
  2567. $byCompany = [];
  2568. foreach ($details as $d) {
  2569. if (!is_array($d)) {
  2570. continue;
  2571. }
  2572. $cn = trim((string)($d['company_name'] ?? ''));
  2573. if ($cn === '') {
  2574. continue;
  2575. }
  2576. if (!isset($byCompany[$cn])) {
  2577. $ph = trim((string)($d['phone'] ?? ''));
  2578. $username = trim((string)($d['username'] ?? ''));
  2579. if ($username === '') {
  2580. $username = $this->resolveCustomerContactName($ph, $cn);
  2581. }
  2582. $byCompany[$cn] = [
  2583. 'name' => $cn,
  2584. 'email' => trim((string)($d['email'] ?? '')),
  2585. 'phone' => $ph,
  2586. 'username' => $username,
  2587. 'remark' => '',
  2588. 'has_quote' => false,
  2589. 'lines_map' => [],
  2590. ];
  2591. }
  2592. if ($byCompany[$cn]['remark'] === '') {
  2593. $rm = '';
  2594. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2595. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2596. $rm = trim((string)$d[$rk]);
  2597. break;
  2598. }
  2599. }
  2600. if ($rm !== '') {
  2601. $byCompany[$cn]['remark'] = $rm;
  2602. }
  2603. }
  2604. $sid = (int)($d['scydgy_id'] ?? 0);
  2605. $am = trim((string)($d['amount'] ?? ''));
  2606. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2607. if ($gymc === '') {
  2608. $gymc = '工序';
  2609. }
  2610. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2611. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2612. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2613. $deliveryShow = $deliveryRaw;
  2614. }
  2615. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2616. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2617. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2618. $subtotal = null;
  2619. if ($amountNum !== null) {
  2620. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2621. }
  2622. $unitPriceText = $amountFilled
  2623. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2624. : '未填写';
  2625. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2626. $leadFilled = ($leadDays !== null);
  2627. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2628. $lineRow = [
  2629. 'cgymc' => $gymc,
  2630. 'amount' => $am,
  2631. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2632. 'amount_filled' => $amountFilled,
  2633. 'unit_price_text' => $unitPriceText,
  2634. 'delivery' => $deliveryRaw,
  2635. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2636. 'delivery_filled' => $deliveryFilled,
  2637. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2638. 'lead_days' => $leadFilled ? $leadDays : '',
  2639. 'lead_days_filled'=> $leadFilled,
  2640. 'lead_days_show' => $leadText,
  2641. 'lead_days_text' => $leadText,
  2642. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2643. 'subtotal_num' => $subtotal,
  2644. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2645. 'is_quoted' => $amountFilled,
  2646. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2647. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2648. ];
  2649. if (!$quoteVisible) {
  2650. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2651. }
  2652. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2653. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2654. }
  2655. foreach ($byCompany as $cn => $g) {
  2656. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2657. $lines = [];
  2658. $usedSids = [];
  2659. foreach ($orderedSids as $sid) {
  2660. if (!isset($linesMap[$sid])) {
  2661. continue;
  2662. }
  2663. $lines[] = $linesMap[$sid];
  2664. $usedSids[$sid] = true;
  2665. }
  2666. foreach ($linesMap as $sid => $ln) {
  2667. if (isset($usedSids[$sid])) {
  2668. continue;
  2669. }
  2670. $lines[] = $ln;
  2671. }
  2672. $total = count($lines);
  2673. $quoted = 0;
  2674. $groupTotal = 0.0;
  2675. $groupHasTotal = false;
  2676. if ($quoteVisible) {
  2677. foreach ($lines as $ln) {
  2678. $am = trim((string)($ln['amount'] ?? ''));
  2679. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2680. $quoted++;
  2681. }
  2682. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2683. $groupTotal += (float)$ln['subtotal_num'];
  2684. $groupHasTotal = true;
  2685. }
  2686. }
  2687. }
  2688. unset($byCompany[$cn]['lines_map']);
  2689. $byCompany[$cn]['lines'] = $lines;
  2690. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2691. $byCompany[$cn]['line_count'] = $total;
  2692. $byCompany[$cn]['has_total'] = $total > 0;
  2693. $byCompany[$cn]['has_remark'] = $total > 0;
  2694. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2695. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2696. // 工序行 + 备注行 + 总计行
  2697. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2698. }
  2699. $groups = array_values($byCompany);
  2700. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2701. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  2702. }
  2703. /**
  2704. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2705. *
  2706. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2707. * @return array<int, array<string, mixed>>
  2708. */
  2709. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2710. {
  2711. $sids = [];
  2712. $poIdMap = [];
  2713. foreach ($bundle['pos'] ?? [] as $po) {
  2714. if (!is_array($po)) {
  2715. continue;
  2716. }
  2717. $sid = (int)($po['scydgy_id'] ?? 0);
  2718. if ($this->isValidScydgyRowId($sid)) {
  2719. $sids[$sid] = true;
  2720. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2721. }
  2722. }
  2723. if ($sids === []) {
  2724. return [];
  2725. }
  2726. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2727. $gymcMap = [];
  2728. $qtyBySid = [];
  2729. $orderedSids = [];
  2730. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2731. if (!is_array($mr)) {
  2732. continue;
  2733. }
  2734. $gid = $this->extractScydgyRowId($mr);
  2735. if ($this->isValidScydgyRowId($gid)) {
  2736. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2737. $orderedSids[] = $gid;
  2738. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2739. if ($qty === '') {
  2740. $qty = trim((string)($mr['NGZL'] ?? ''));
  2741. }
  2742. $qtyBySid[$gid] = $qty;
  2743. }
  2744. }
  2745. foreach ($bundle['pos'] ?? [] as $po) {
  2746. if (!is_array($po)) {
  2747. continue;
  2748. }
  2749. $gid = (int)($po['scydgy_id'] ?? 0);
  2750. if ($this->isValidScydgyRowId($gid)) {
  2751. $nm = trim((string)($po['CGYMC'] ?? ''));
  2752. if ($nm !== '') {
  2753. $gymcMap[$gid] = $nm;
  2754. }
  2755. }
  2756. }
  2757. try {
  2758. $details = Db::table('purchase_order_detail')
  2759. ->where('scydgy_id', 'in', array_keys($sids))
  2760. ->order('company_name', 'asc')
  2761. ->order('id', 'asc')
  2762. ->select();
  2763. } catch (\Throwable $e) {
  2764. try {
  2765. $details = Db::table('purchase_order_detail')
  2766. ->where('scydgy_id', 'in', array_keys($sids))
  2767. ->order('company_name', 'asc')
  2768. ->order('ID', 'asc')
  2769. ->select();
  2770. } catch (\Throwable $e2) {
  2771. $details = [];
  2772. }
  2773. }
  2774. if (!is_array($details)) {
  2775. $details = [];
  2776. }
  2777. $byCompany = [];
  2778. foreach ($details as $d) {
  2779. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2780. continue;
  2781. }
  2782. $cn = trim((string)($d['company_name'] ?? ''));
  2783. if ($cn === '') {
  2784. continue;
  2785. }
  2786. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2787. $sid = (int)($d['scydgy_id'] ?? 0);
  2788. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2789. continue;
  2790. }
  2791. if (!isset($byCompany[$cn])) {
  2792. $ph = trim((string)($d['phone'] ?? ''));
  2793. $username = trim((string)($d['username'] ?? ''));
  2794. if ($username === '') {
  2795. $username = $this->resolveCustomerContactName($ph, $cn);
  2796. }
  2797. $byCompany[$cn] = [
  2798. 'name' => $cn,
  2799. 'email' => trim((string)($d['email'] ?? '')),
  2800. 'phone' => $ph,
  2801. 'username' => $username,
  2802. 'remark' => '',
  2803. 'pick_lines' => [],
  2804. 'detail_picks' => [],
  2805. ];
  2806. }
  2807. if ($byCompany[$cn]['remark'] === '') {
  2808. $rm = '';
  2809. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2810. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2811. $rm = trim((string)$d[$rk]);
  2812. break;
  2813. }
  2814. }
  2815. if ($rm !== '') {
  2816. $byCompany[$cn]['remark'] = $rm;
  2817. }
  2818. }
  2819. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2820. if ($gymc === '') {
  2821. $gymc = '工序';
  2822. }
  2823. $am = trim((string)($d['amount'] ?? ''));
  2824. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2825. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2826. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2827. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2828. $deliveryShow = $deliveryRaw;
  2829. }
  2830. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2831. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2832. $subtotal = null;
  2833. if ($amountNum !== null) {
  2834. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2835. }
  2836. $unitPriceText = $amountFilled
  2837. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2838. : '未填写';
  2839. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2840. $leadFilled = ($leadDays !== null);
  2841. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2842. $pickLine = [
  2843. 'cgymc' => $gymc,
  2844. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  2845. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2846. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2847. 'amount_filled' => $amountFilled,
  2848. 'delivery_filled' => $deliveryFilled,
  2849. 'unit_price_text' => $unitPriceText,
  2850. 'lead_days' => $leadFilled ? $leadDays : '',
  2851. 'lead_days_filled'=> $leadFilled,
  2852. 'lead_days_show' => $leadText,
  2853. 'lead_days_text' => $leadText,
  2854. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2855. 'subtotal_num' => $subtotal,
  2856. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2857. 'is_quoted' => $amountFilled,
  2858. ];
  2859. if (!$quoteVisible) {
  2860. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2861. }
  2862. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2863. $byCompany[$cn]['detail_picks'][$sid] = [
  2864. 'scydgy_id' => $sid,
  2865. 'detail_id' => $detailId,
  2866. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2867. 'cgymc' => $gymc,
  2868. ];
  2869. }
  2870. $out = [];
  2871. foreach ($byCompany as $g) {
  2872. $pickLinesMap = $g['pick_lines'] ?? [];
  2873. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2874. continue;
  2875. }
  2876. $pickLines = [];
  2877. $usedLineSids = [];
  2878. foreach ($orderedSids as $sid) {
  2879. if (!isset($pickLinesMap[$sid])) {
  2880. continue;
  2881. }
  2882. $pickLines[] = $pickLinesMap[$sid];
  2883. $usedLineSids[$sid] = true;
  2884. }
  2885. foreach ($pickLinesMap as $sid => $ln) {
  2886. if (isset($usedLineSids[$sid])) {
  2887. continue;
  2888. }
  2889. $pickLines[] = $ln;
  2890. }
  2891. $groupTotal = 0.0;
  2892. $groupHasTotal = false;
  2893. if ($quoteVisible) {
  2894. foreach ($pickLines as $ln) {
  2895. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2896. $groupTotal += (float)$ln['subtotal_num'];
  2897. $groupHasTotal = true;
  2898. }
  2899. }
  2900. }
  2901. $lineCount = count($pickLines);
  2902. $g['pick_lines'] = $pickLines;
  2903. $g['line_count'] = $lineCount;
  2904. $g['has_total'] = $lineCount > 0;
  2905. $g['has_remark'] = $lineCount > 0;
  2906. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2907. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2908. // 工序行 + 备注行 + 总计行
  2909. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2910. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2911. $detailPicks = [];
  2912. $usedPickSids = [];
  2913. foreach ($orderedSids as $sid) {
  2914. if (!isset($detailPicksMap[$sid])) {
  2915. continue;
  2916. }
  2917. $detailPicks[] = $detailPicksMap[$sid];
  2918. $usedPickSids[$sid] = true;
  2919. }
  2920. foreach ($detailPicksMap as $sid => $dp) {
  2921. if (isset($usedPickSids[$sid])) {
  2922. continue;
  2923. }
  2924. $detailPicks[] = $dp;
  2925. }
  2926. $g['detail_picks'] = $detailPicks;
  2927. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2928. unset($g['detail_picks']);
  2929. $out[] = $g;
  2930. }
  2931. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2932. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  2933. }
  2934. /**
  2935. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2936. * @return array<int, int[]> scydgy_id => detail_id[]
  2937. */
  2938. protected function mapDetailIdsByScydgyId(array $details): array
  2939. {
  2940. $out = [];
  2941. foreach ($details as $d) {
  2942. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2943. continue;
  2944. }
  2945. $sid = (int)($d['scydgy_id'] ?? 0);
  2946. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2947. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2948. continue;
  2949. }
  2950. if (!isset($out[$sid])) {
  2951. $out[$sid] = [];
  2952. }
  2953. $out[$sid][] = $pk;
  2954. }
  2955. foreach ($out as $sid => $ids) {
  2956. $out[$sid] = array_values(array_unique($ids));
  2957. }
  2958. return $out;
  2959. }
  2960. /**
  2961. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2962. *
  2963. * @param array<string, mixed> $dbRow
  2964. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2965. */
  2966. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2967. {
  2968. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2969. $r = [
  2970. 'ID' => $sid,
  2971. 'scydgy_id' => $sid,
  2972. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2973. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2974. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2975. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2976. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2977. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2978. 'CDW' => $dbRow['CDW'] ?? '',
  2979. 'czlyq' => $dbRow['czlyq'] ?? '',
  2980. 'NGZL' => $dbRow['NGZL'] ?? '',
  2981. 'CDF' => $dbRow['CDF'] ?? '',
  2982. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2983. 'MBZ' => $dbRow['MBZ'] ?? '',
  2984. 'bwjg' => $dbRow['bwjg'] ?? '',
  2985. 'iStatus' => $dbRow['iStatus'] ?? '',
  2986. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2987. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2988. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2989. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2990. 'dStamp' => $dbRow['dStamp'] ?? '',
  2991. 'pick_time' => $dbRow['pick_time'] ?? '',
  2992. ];
  2993. if ($sid > 0 && isset($dStampMap[$sid])) {
  2994. $t = trim((string)$dStampMap[$sid]);
  2995. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2996. $r['dStamp'] = $dStampMap[$sid];
  2997. }
  2998. }
  2999. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3000. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3001. $ct = $dbRow['createtime'];
  3002. if (is_numeric($ct) && (int)$ct > 946684800) {
  3003. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3004. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3005. $r['dStamp'] = trim($ct);
  3006. }
  3007. }
  3008. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3009. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3010. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3011. $fallback = trim((string)($r['dStamp'] ?? ''));
  3012. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3013. $r['dputrecord'] = $fallback;
  3014. }
  3015. }
  3016. if (array_key_exists('id', $dbRow)) {
  3017. $r['purchase_order_id'] = (int)$dbRow['id'];
  3018. }
  3019. if ($sid < 0) {
  3020. $r['_is_manual'] = 1;
  3021. }
  3022. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3023. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3024. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3025. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3026. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3027. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3028. $r['pick_time'] = $pickFallback;
  3029. break;
  3030. }
  3031. }
  3032. }
  3033. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3034. if ($pickNm !== '') {
  3035. $r['pick_company_name'] = $pickNm;
  3036. $r['picked_supplier_name'] = $pickNm;
  3037. }
  3038. return $r;
  3039. }
  3040. /**
  3041. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3042. *
  3043. * @return array<int, array<string, mixed>>
  3044. */
  3045. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3046. {
  3047. $pool = [];
  3048. if (!is_array($dbRows) || $dbRows === []) {
  3049. return $pool;
  3050. }
  3051. $dStampMap = [];
  3052. $sidList = [];
  3053. foreach ($dbRows as $tmpRow) {
  3054. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3055. $sid = (int)$tmpRow['scydgy_id'];
  3056. if ($sid > 0) {
  3057. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3058. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3059. $sidList[$sid] = true;
  3060. }
  3061. }
  3062. }
  3063. }
  3064. if ($sidList !== []) {
  3065. try {
  3066. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3067. } catch (\Throwable $e) {
  3068. $dStampMap = [];
  3069. }
  3070. }
  3071. foreach ($dbRows as $dbRow) {
  3072. if (!is_array($dbRow)) {
  3073. continue;
  3074. }
  3075. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3076. }
  3077. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3078. $needCcydh = [];
  3079. foreach ($pool as $row) {
  3080. if (!is_array($row)) {
  3081. continue;
  3082. }
  3083. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3084. continue;
  3085. }
  3086. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3087. if ($ccydh !== '') {
  3088. $needCcydh[$ccydh] = true;
  3089. }
  3090. }
  3091. if ($needCcydh !== []) {
  3092. $czMap = [];
  3093. try {
  3094. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3095. } catch (\Throwable $e) {
  3096. $czMap = [];
  3097. }
  3098. if (is_array($czMap) && $czMap !== []) {
  3099. foreach ($pool as &$row) {
  3100. if (!is_array($row)) {
  3101. continue;
  3102. }
  3103. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3104. continue;
  3105. }
  3106. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3107. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3108. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3109. }
  3110. }
  3111. unset($row);
  3112. }
  3113. }
  3114. return $pool;
  3115. }
  3116. /**
  3117. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3118. *
  3119. * @param int[] $scydgyIds
  3120. * @return array<int, array<string, mixed>>
  3121. */
  3122. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3123. {
  3124. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3125. if ($scydgyIds === []) {
  3126. return [];
  3127. }
  3128. try {
  3129. $list = Db::table('purchase_order_detail')
  3130. ->where('scydgy_id', 'in', $scydgyIds)
  3131. ->field('scydgy_id,company_name,amount,delivery')
  3132. ->select();
  3133. } catch (\Throwable $e) {
  3134. $list = [];
  3135. }
  3136. return is_array($list) ? $list : [];
  3137. }
  3138. /**
  3139. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3140. *
  3141. * @param int[] $scydgyIds
  3142. * @param array<int, array<string, mixed>> $allRows
  3143. * @return array{cnt:int, amt:int, deliv:int}
  3144. */
  3145. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3146. {
  3147. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3148. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3149. if ($scydgyIds === [] || $allRows === []) {
  3150. return $out;
  3151. }
  3152. $idSet = array_flip($scydgyIds);
  3153. $all = [];
  3154. $withAmt = [];
  3155. $withDeliv = [];
  3156. foreach ($allRows as $r) {
  3157. if (!is_array($r)) {
  3158. continue;
  3159. }
  3160. $sid = (int)($r['scydgy_id'] ?? 0);
  3161. if (!isset($idSet[$sid])) {
  3162. continue;
  3163. }
  3164. $cn = trim((string)($r['company_name'] ?? ''));
  3165. if ($cn === '') {
  3166. continue;
  3167. }
  3168. $all[$cn] = true;
  3169. $am = $r['amount'] ?? null;
  3170. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3171. $withAmt[$cn] = true;
  3172. }
  3173. $dv = $r['delivery'] ?? null;
  3174. if ($dv !== null && trim((string)$dv) !== '') {
  3175. $withDeliv[$cn] = true;
  3176. }
  3177. }
  3178. return [
  3179. 'cnt' => count($all),
  3180. 'amt' => count($withAmt),
  3181. 'deliv' => count($withDeliv),
  3182. ];
  3183. }
  3184. /**
  3185. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  3186. *
  3187. * @param int[] $scydgyIds
  3188. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  3189. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  3190. */
  3191. protected function OrderDetailSummary(array $scydgyIds)
  3192. {
  3193. $out = [];
  3194. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3195. if ($scydgyIds === []) {
  3196. return $out;
  3197. }
  3198. $list = [];
  3199. try {
  3200. $list = Db::table('purchase_order_detail')
  3201. ->where('scydgy_id', 'in', $scydgyIds)
  3202. ->field('id,scydgy_id,amount,delivery')
  3203. ->select();
  3204. } catch (\Throwable $e) {
  3205. $list = [];
  3206. }
  3207. if (!is_array($list)) {
  3208. return $out;
  3209. }
  3210. foreach ($list as $r) {
  3211. if (!is_array($r)) {
  3212. continue;
  3213. }
  3214. $ids = (int)($r['scydgy_id'] ?? 0);
  3215. if (!$this->isValidScydgyRowId($ids)) {
  3216. continue;
  3217. }
  3218. if (!isset($out[$ids])) {
  3219. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3220. }
  3221. $out[$ids]['cnt']++;
  3222. $am = $r['amount'] ?? null;
  3223. if ($am !== null && $am !== '') {
  3224. if (!(is_string($am) && trim($am) === '')) {
  3225. $out[$ids]['amt']++;
  3226. }
  3227. }
  3228. $dv = $r['delivery'] ?? null;
  3229. if ($dv !== null && trim((string)$dv) !== '') {
  3230. $out[$ids]['deliv']++;
  3231. }
  3232. }
  3233. return $out;
  3234. }
  3235. /**
  3236. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3237. *
  3238. * @return array
  3239. */
  3240. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3241. {
  3242. $strContains = function ($haystack, $needle) {
  3243. if ($needle === '') {
  3244. return false;
  3245. }
  3246. $haystack = (string)$haystack;
  3247. if (function_exists('mb_stripos')) {
  3248. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3249. }
  3250. return stripos($haystack, $needle) !== false;
  3251. };
  3252. $stripAlias = function ($f) {
  3253. return preg_replace('/^[ab]\./i', '', (string)$f);
  3254. };
  3255. $searchColNames = [];
  3256. foreach (explode(',', $this->searchFields) as $colRaw) {
  3257. $c = $stripAlias(trim($colRaw));
  3258. if ($c !== '') {
  3259. $searchColNames[] = $c;
  3260. }
  3261. }
  3262. // 等值条件先行(表头下拉),减少后续日期解析量
  3263. $eqFilters = [];
  3264. $otherFilters = [];
  3265. foreach ($filterArr as $fk => $fv) {
  3266. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3267. continue;
  3268. }
  3269. if (is_array($fv)) {
  3270. continue;
  3271. }
  3272. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3273. continue;
  3274. }
  3275. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3276. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3277. $field = $stripAlias($fk);
  3278. if ($sym === '=' || $sym === '') {
  3279. $eqFilters[$field] = trim((string)$fv);
  3280. } else {
  3281. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  3282. }
  3283. }
  3284. $ymTarget = '';
  3285. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  3286. $ymTarget = $ymM[1];
  3287. }
  3288. $filtered = [];
  3289. foreach ($pool as $r) {
  3290. if (!is_array($r)) {
  3291. continue;
  3292. }
  3293. foreach ($eqFilters as $field => $fv) {
  3294. if (trim((string)($r[$field] ?? '')) !== $fv) {
  3295. continue 2;
  3296. }
  3297. }
  3298. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3299. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3300. if (!$isManual) {
  3301. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3302. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3303. continue;
  3304. }
  3305. if ($applyMonthRange) {
  3306. $mo = (int)$m[2];
  3307. if ($mo < 1 || $mo > 12) {
  3308. continue;
  3309. }
  3310. if ($ymTarget !== '') {
  3311. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3312. if ($ymRow !== $ymTarget) {
  3313. continue;
  3314. }
  3315. } else {
  3316. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3317. $rowMonthStart = $ymRow . '-01 00:00:00';
  3318. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3319. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3320. continue;
  3321. }
  3322. }
  3323. }
  3324. } elseif ($applyMonthRange) {
  3325. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3326. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3327. $ds = $listTime;
  3328. }
  3329. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3330. continue;
  3331. }
  3332. $mo = (int)$m[2];
  3333. if ($mo < 1 || $mo > 12) {
  3334. continue;
  3335. }
  3336. if ($ymTarget !== '') {
  3337. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3338. if ($ymRow !== $ymTarget) {
  3339. continue;
  3340. }
  3341. } else {
  3342. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3343. $rowMonthStart = $ymRow . '-01 00:00:00';
  3344. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3345. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3346. continue;
  3347. }
  3348. }
  3349. }
  3350. if ($search !== '') {
  3351. $hitSearch = false;
  3352. foreach ($searchColNames as $c) {
  3353. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3354. if ($cell !== '' && $strContains($cell, $search)) {
  3355. $hitSearch = true;
  3356. break;
  3357. }
  3358. }
  3359. if (!$hitSearch) {
  3360. continue;
  3361. }
  3362. }
  3363. foreach ($otherFilters as $item) {
  3364. $fv = $item['fv'];
  3365. $sym = $item['sym'];
  3366. $field = $item['field'];
  3367. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3368. $cellStr = trim((string)$cell);
  3369. switch ($sym) {
  3370. case '<>':
  3371. if ((string)$cell === (string)$fv) {
  3372. continue 3;
  3373. }
  3374. break;
  3375. case 'LIKE':
  3376. case 'NOT LIKE':
  3377. $needle = trim((string)$fv);
  3378. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3379. if ($sym === 'LIKE' && !$hit) {
  3380. continue 3;
  3381. }
  3382. if ($sym === 'NOT LIKE' && $hit) {
  3383. continue 3;
  3384. }
  3385. break;
  3386. case 'BETWEEN':
  3387. case 'RANGE':
  3388. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  3389. if (count($parts) < 2) {
  3390. $parts = is_string($fv) ? explode(',', $fv) : [];
  3391. }
  3392. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  3393. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  3394. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  3395. continue 3;
  3396. }
  3397. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  3398. continue 3;
  3399. }
  3400. break;
  3401. case '>':
  3402. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  3403. continue 3;
  3404. }
  3405. break;
  3406. case '>=':
  3407. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  3408. continue 3;
  3409. }
  3410. break;
  3411. case '<':
  3412. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  3413. continue 3;
  3414. }
  3415. break;
  3416. case '<=':
  3417. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  3418. continue 3;
  3419. }
  3420. break;
  3421. default:
  3422. if ((string)$cell !== (string)$fv) {
  3423. continue 3;
  3424. }
  3425. break;
  3426. }
  3427. }
  3428. $filtered[] = $r;
  3429. }
  3430. return $filtered;
  3431. }
  3432. /**
  3433. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3434. */
  3435. public function snapshotToProcure()
  3436. {
  3437. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3438. $this->error(__('Invalid parameters'));
  3439. }
  3440. $row = json_decode($this->request->post('row_json', ''), true);
  3441. if (!is_array($row)) {
  3442. $this->error(__('Invalid parameters'));
  3443. }
  3444. try {
  3445. $ids = $this->extractScydgyRowId($row);
  3446. if (!$this->isValidScydgyRowId($ids)) {
  3447. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3448. }
  3449. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3450. $data = [
  3451. 'scydgy_id' => $ids,
  3452. 'CCYDH' => $row['CCYDH'] ?? null,
  3453. 'CYJMC' => $row['CYJMC'] ?? null,
  3454. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3455. 'CDXMC' => $row['CDXMC'] ?? null,
  3456. 'CGYBH' => $row['CGYBH'] ?? null,
  3457. 'CGYMC' => $row['CGYMC'] ?? null,
  3458. 'CDW' => $row['CDW'] ?? null,
  3459. 'czlyq' => $row['czlyq'] ?? null,
  3460. 'NGZL' => $row['NGZL'] ?? null,
  3461. 'CDF' => $row['CDF'] ?? null,
  3462. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3463. 'MBZ' => $row['MBZ'] ?? null,
  3464. 'bwjg' => $row['bwjg'] ?? null,
  3465. 'iStatus' => $row['iStatus'] ?? null,
  3466. 'dStamp' => $row['dStamp'] ?? null,
  3467. 'dputrecord' => $row['dputrecord'] ?? null,
  3468. 'cywyxm' => $row['cywyxm'] ?? null,
  3469. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3470. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3471. ];
  3472. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3473. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3474. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3475. $this->success('操作成功');
  3476. return;
  3477. }
  3478. if ($exists) {
  3479. $upd = $data;
  3480. unset($upd['scydgy_id'], $upd['status']);
  3481. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3482. } else {
  3483. // 新增:不写 status(空/走库默认);仅写创建时间
  3484. $data['createtime'] = date('Y-m-d H:i:s');
  3485. Db::table('purchase_order')->insert($data);
  3486. }
  3487. } catch (\Throwable $e) {
  3488. $this->error($e->getMessage());
  3489. }
  3490. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3491. $this->success('操作成功');
  3492. }
  3493. /**
  3494. * 未发列表
  3495. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3496. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3497. */
  3498. public function completeDirectly()
  3499. {
  3500. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3501. $this->error(__('参数错误'));
  3502. }
  3503. if (!$this->procuremenCanComplete()) {
  3504. $this->error(__('You have no permission'));
  3505. }
  3506. $row = json_decode($this->request->post('row_json', ''), true);
  3507. if (!is_array($row)) {
  3508. $this->error(__('Invalid parameters'));
  3509. }
  3510. $finishRaw = $this->request->post('finish', '1');
  3511. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3512. $poIdLog = null;
  3513. try {
  3514. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3515. $ids = $this->extractScydgyRowId($row);
  3516. if (!$this->isValidScydgyRowId($ids)) {
  3517. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3518. }
  3519. if ($asComplete) {
  3520. $this->assertPickRowCanComplete($ids, $row);
  3521. }
  3522. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3523. $data = [
  3524. 'scydgy_id' => $ids,
  3525. 'CCYDH' => $row['CCYDH'] ?? null,
  3526. 'CYJMC' => $row['CYJMC'] ?? null,
  3527. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3528. 'CDXMC' => $row['CDXMC'] ?? null,
  3529. 'CGYBH' => $row['CGYBH'] ?? null,
  3530. 'CGYMC' => $row['CGYMC'] ?? null,
  3531. 'CDW' => $row['CDW'] ?? null,
  3532. 'czlyq' => $row['czlyq'] ?? null,
  3533. 'NGZL' => $row['NGZL'] ?? null,
  3534. 'CDF' => $row['CDF'] ?? null,
  3535. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3536. 'MBZ' => $row['MBZ'] ?? null,
  3537. 'bwjg' => $row['bwjg'] ?? null,
  3538. 'iStatus' => $row['iStatus'] ?? null,
  3539. 'dStamp' => $row['dStamp'] ?? null,
  3540. 'dputrecord' => $row['dputrecord'] ?? null,
  3541. 'cywyxm' => $row['cywyxm'] ?? null,
  3542. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3543. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3544. ];
  3545. if ($asComplete) {
  3546. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3547. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3548. }
  3549. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3550. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3551. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3552. $this->success('操作成功');
  3553. return;
  3554. }
  3555. if ($exists) {
  3556. $upd = $data;
  3557. unset($upd['scydgy_id']);
  3558. if (!$asComplete) {
  3559. unset($upd['status']);
  3560. }
  3561. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3562. } else {
  3563. // 新增:不写 status;完结时 $data 已含 status=1
  3564. $data['createtime'] = date('Y-m-d H:i:s');
  3565. Db::table('purchase_order')->insert($data);
  3566. }
  3567. } catch (\Throwable $e) {
  3568. $this->error($e->getMessage());
  3569. }
  3570. try {
  3571. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3572. if (is_array($rpo)) {
  3573. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3574. $poIdLog = $tid > 0 ? $tid : null;
  3575. }
  3576. } catch (\Throwable $e) {
  3577. $poIdLog = null;
  3578. }
  3579. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3580. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3581. if ($asComplete) {
  3582. $this->addOrderLog(
  3583. $ids,
  3584. 'mark_complete',
  3585. '点击「完结」,已标记为已完结',
  3586. $poIdLog
  3587. );
  3588. try {
  3589. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3590. if ($pdfPublicPath === '') {
  3591. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3592. }
  3593. } catch (\Throwable $e) {
  3594. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3595. }
  3596. } else {
  3597. $this->addOrderLog(
  3598. $ids,
  3599. 'save_qty_price',
  3600. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3601. $poIdLog
  3602. );
  3603. }
  3604. $this->pickHiddenScydgySetCache = null;
  3605. $this->success("操作成功");
  3606. }
  3607. /**
  3608. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3609. *
  3610. * @param array<int, array> $rows 引用传递当前页行
  3611. */
  3612. protected function mergePurchaseOrder(array &$rows)
  3613. {
  3614. if ($rows === []) {
  3615. return;
  3616. }
  3617. $ids = [];
  3618. foreach ($rows as $rw) {
  3619. if (!is_array($rw)) {
  3620. continue;
  3621. }
  3622. $id = (int)($rw['ID'] ?? 0);
  3623. if ($id > 0) {
  3624. $ids[$id] = true;
  3625. }
  3626. }
  3627. $idList = array_keys($ids);
  3628. if ($idList === []) {
  3629. return;
  3630. }
  3631. try {
  3632. $list = Db::table('purchase_order')
  3633. ->where('scydgy_id', 'in', $idList)
  3634. ->field('scydgy_id,This_quantity,ceilingPrice')
  3635. ->select();
  3636. } catch (\Throwable $e) {
  3637. return;
  3638. }
  3639. if (!is_array($list)) {
  3640. return;
  3641. }
  3642. $byId = [];
  3643. foreach ($list as $dbRow) {
  3644. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3645. continue;
  3646. }
  3647. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3648. }
  3649. foreach ($rows as &$rw) {
  3650. if (!is_array($rw)) {
  3651. continue;
  3652. }
  3653. $sid = (int)($rw['ID'] ?? 0);
  3654. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3655. continue;
  3656. }
  3657. $db = $byId[$sid];
  3658. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3659. if (array_key_exists('This_quantity', $db)) {
  3660. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3661. }
  3662. if (array_key_exists('ceilingPrice', $db)) {
  3663. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3664. } elseif (array_key_exists('ceiling_price', $db)) {
  3665. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3666. }
  3667. }
  3668. unset($rw);
  3669. }
  3670. /**
  3671. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3672. */
  3673. public function purchaseConfirmPick()
  3674. {
  3675. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3676. $this->error(__('Invalid parameters'));
  3677. }
  3678. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3679. $this->error(__('You have no permission'));
  3680. }
  3681. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3682. if ($batchRaw !== '') {
  3683. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3684. return;
  3685. }
  3686. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3687. $sid = (int)$scydgyId;
  3688. if (!$this->isValidScydgyRowId($sid)) {
  3689. $this->error('参数无效');
  3690. }
  3691. $parseIdList = function ($raw) {
  3692. if (is_array($raw)) {
  3693. $arr = $raw;
  3694. } else {
  3695. $decoded = json_decode((string)$raw, true);
  3696. $arr = is_array($decoded) ? $decoded : [];
  3697. }
  3698. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3699. };
  3700. $selectedRaw = $this->request->post('selected_ids', null);
  3701. if ($selectedRaw === null || $selectedRaw === '') {
  3702. $legacy = (int)$this->request->post('selected_id', 0);
  3703. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3704. } else {
  3705. $selectedIds = $parseIdList($selectedRaw);
  3706. }
  3707. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3708. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3709. try {
  3710. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3711. } catch (\InvalidArgumentException $e) {
  3712. $this->error($e->getMessage());
  3713. } catch (\Throwable $e) {
  3714. $this->error($e->getMessage());
  3715. }
  3716. $this->pickHiddenScydgySetCache = null;
  3717. $this->success('操作成功', '', $result);
  3718. }
  3719. /**
  3720. * 整单采购确认(多道工序一次提交)
  3721. */
  3722. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3723. {
  3724. $decoded = json_decode($batchRaw, true);
  3725. if (!is_array($decoded) || $decoded === []) {
  3726. $this->error('提交数据无效');
  3727. }
  3728. $picks = [];
  3729. foreach ($decoded as $item) {
  3730. if (!is_array($item)) {
  3731. continue;
  3732. }
  3733. $sid = (int)($item['scydgy_id'] ?? 0);
  3734. if (!$this->isValidScydgyRowId($sid)) {
  3735. continue;
  3736. }
  3737. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3738. if (!is_array($sel)) {
  3739. $sel = [(int)$sel];
  3740. }
  3741. $unsel = $item['unselected_ids'] ?? [];
  3742. if (!is_array($unsel)) {
  3743. $unsel = json_decode((string)$unsel, true);
  3744. $unsel = is_array($unsel) ? $unsel : [];
  3745. }
  3746. $picks[] = [
  3747. 'scydgy_id' => $sid,
  3748. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3749. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3750. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3751. ];
  3752. }
  3753. if ($picks === []) {
  3754. $this->error('提交数据无效');
  3755. }
  3756. Db::startTrans();
  3757. $results = [];
  3758. try {
  3759. foreach ($picks as $pick) {
  3760. $results[] = $this->runPurchaseConfirmPick(
  3761. (int)$pick['scydgy_id'],
  3762. $pick['selected_ids'],
  3763. $pick['unselected_ids'],
  3764. (int)$pick['purchase_order_id'],
  3765. false,
  3766. false
  3767. );
  3768. }
  3769. Db::commit();
  3770. } catch (\Throwable $e) {
  3771. Db::rollback();
  3772. $msg = $e->getMessage();
  3773. $this->error($msg !== '' ? $msg : '提交失败');
  3774. }
  3775. try {
  3776. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3777. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3778. } catch (\Throwable $e) {
  3779. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3780. }
  3781. $this->pickHiddenScydgySetCache = null;
  3782. $this->success('操作成功', '', ['batch' => $results]);
  3783. }
  3784. /**
  3785. * @return array<string, mixed>
  3786. */
  3787. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3788. {
  3789. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3790. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3791. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3792. $scydgyId = (string)$sid;
  3793. if ($selectedIds === []) {
  3794. throw new \InvalidArgumentException('请至少勾选一条明细');
  3795. }
  3796. $inter = array_intersect($selectedIds, $unselectedIds);
  3797. if ($inter !== []) {
  3798. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3799. }
  3800. $allIds = $this->purchaseOrderDetail($sid);
  3801. if ($allIds === []) {
  3802. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3803. }
  3804. foreach ($selectedIds as $id) {
  3805. if (!in_array($id, $allIds, true)) {
  3806. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3807. }
  3808. }
  3809. foreach ($unselectedIds as $id) {
  3810. if (!in_array($id, $allIds, true)) {
  3811. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3812. }
  3813. }
  3814. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3815. sort($union, SORT_NUMERIC);
  3816. $expect = $allIds;
  3817. sort($expect, SORT_NUMERIC);
  3818. if ($union !== $expect) {
  3819. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3820. }
  3821. if ($manageTransaction) {
  3822. Db::startTrans();
  3823. }
  3824. try {
  3825. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3826. $aff = 0;
  3827. try {
  3828. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3829. } catch (\Throwable $e) {
  3830. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3831. }
  3832. if ($aff < 1) {
  3833. throw new \Exception('更新选中状态失败');
  3834. }
  3835. $poPayload = [
  3836. 'status' => ProcuremenStatus::PO_COMPLETED,
  3837. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3838. ];
  3839. if ($purchaseOrderId > 0) {
  3840. $poAff = (int)Db::table('purchase_order')
  3841. ->where('id', $purchaseOrderId)
  3842. ->where('scydgy_id', $sid)
  3843. ->update($poPayload);
  3844. if ($poAff < 1) {
  3845. throw new \Exception('主表订单不存在或与工序行不匹配');
  3846. }
  3847. } else {
  3848. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3849. if ($poAff < 1) {
  3850. throw new \Exception('未找到');
  3851. }
  3852. }
  3853. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3854. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3855. if ($manageTransaction) {
  3856. Db::commit();
  3857. }
  3858. } catch (\Throwable $e) {
  3859. if ($manageTransaction) {
  3860. Db::rollback();
  3861. }
  3862. throw $e;
  3863. }
  3864. $poIdFinal = $purchaseOrderId;
  3865. if ($poIdFinal <= 0) {
  3866. try {
  3867. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3868. if (is_array($rpo)) {
  3869. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3870. }
  3871. } catch (\Throwable $e) {
  3872. $poIdFinal = 0;
  3873. }
  3874. }
  3875. $pickNames = [];
  3876. foreach ($selectedIds as $pid) {
  3877. $dr = $this->purchaseOrderDetai($sid, $pid);
  3878. $nm = trim((string)($dr['company_name'] ?? ''));
  3879. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3880. }
  3881. $this->addOrderLog(
  3882. $sid,
  3883. 'purchase_confirm',
  3884. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3885. $poIdFinal > 0 ? $poIdFinal : null
  3886. );
  3887. if ($sendNotifications) {
  3888. try {
  3889. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3890. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3891. 'scydgy_id' => $sid,
  3892. 'selected_ids' => $selectedIds,
  3893. 'unselected_ids' => $unselectedIds,
  3894. 'purchase_order_id' => $purchaseOrderId,
  3895. ]]);
  3896. } catch (\Throwable $e) {
  3897. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3898. }
  3899. }
  3900. Log::write(sprintf(
  3901. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3902. $scydgyId,
  3903. $purchaseOrderId,
  3904. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3905. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3906. ), 'notice');
  3907. $pdfPublicPath = '';
  3908. try {
  3909. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3910. } catch (\Throwable $e) {
  3911. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3912. }
  3913. return [
  3914. 'scydgy_id' => $scydgyId,
  3915. 'purchase_order_id' => $purchaseOrderId,
  3916. 'selected_ids' => $selectedIds,
  3917. 'unselected_ids' => $unselectedIds,
  3918. 'purchase_confirm_pdf' => $pdfPublicPath,
  3919. ];
  3920. }
  3921. /**
  3922. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3923. *
  3924. * @param int[]|string[] $scydgyIds
  3925. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3926. */
  3927. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3928. {
  3929. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3930. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3931. if ($scydgyIds === []) {
  3932. return $empty;
  3933. }
  3934. $pos = [];
  3935. try {
  3936. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3937. } catch (\Throwable $e) {
  3938. $rows = [];
  3939. }
  3940. if (is_array($rows)) {
  3941. foreach ($rows as $po) {
  3942. if (is_array($po)) {
  3943. $pos[] = $po;
  3944. }
  3945. }
  3946. }
  3947. if ($pos === []) {
  3948. return $empty;
  3949. }
  3950. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3951. return [
  3952. 'ccydh' => $ccydh,
  3953. 'pos' => $pos,
  3954. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3955. ];
  3956. }
  3957. /**
  3958. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3959. *
  3960. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3961. * @param array<int, array<string, mixed>> $picks
  3962. */
  3963. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3964. {
  3965. if ($picks === []) {
  3966. return;
  3967. }
  3968. $fallbackDetailId = 0;
  3969. $winners = [];
  3970. $losers = [];
  3971. foreach ($picks as $pick) {
  3972. if (!is_array($pick)) {
  3973. continue;
  3974. }
  3975. $sid = (int)($pick['scydgy_id'] ?? 0);
  3976. if (!$this->isValidScydgyRowId($sid)) {
  3977. continue;
  3978. }
  3979. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3980. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3981. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3982. $fallbackDetailId = (int)$selectedIds[0];
  3983. }
  3984. foreach ($selectedIds as $pid) {
  3985. $dr = $this->purchaseOrderDetai($sid, $pid);
  3986. if (!is_array($dr)) {
  3987. continue;
  3988. }
  3989. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3990. }
  3991. foreach ($unselectedIds as $pid) {
  3992. $dr = $this->purchaseOrderDetai($sid, $pid);
  3993. if (!is_array($dr)) {
  3994. continue;
  3995. }
  3996. $key = $this->notifySupplierDedupeKey($dr);
  3997. if (!isset($winners[$key])) {
  3998. $losers[$key] = $dr;
  3999. }
  4000. }
  4001. }
  4002. if ($winners === [] && $losers === []) {
  4003. return;
  4004. }
  4005. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4006. $sendSmsSafe = function ($phone, $content) {
  4007. $phone = trim((string)$phone);
  4008. if ($phone === '') {
  4009. return;
  4010. }
  4011. try {
  4012. $this->smsbao($phone, $content);
  4013. } catch (\Throwable $e) {
  4014. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4015. }
  4016. };
  4017. foreach ($winners as $dr) {
  4018. $cname = trim((string)($dr['company_name'] ?? ''));
  4019. $ph = trim((string)($dr['phone'] ?? ''));
  4020. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4021. 'company_name' => $cname,
  4022. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4023. 'phone' => $ph,
  4024. ]));
  4025. $sendSmsSafe($ph, $sms);
  4026. }
  4027. foreach ($losers as $dr) {
  4028. $cname = trim((string)($dr['company_name'] ?? ''));
  4029. $ph = trim((string)($dr['phone'] ?? ''));
  4030. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4031. 'company_name' => $cname,
  4032. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4033. 'phone' => $ph,
  4034. ]));
  4035. $sendSmsSafe($ph, $sms);
  4036. }
  4037. }
  4038. /**
  4039. * 短信去重键:优先手机号,否则公司名
  4040. */
  4041. protected function notifySupplierDedupeKey(array $detailRow): string
  4042. {
  4043. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4044. if ($ph !== '') {
  4045. return 'p:' . $ph;
  4046. }
  4047. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4048. return 'c:' . $cn;
  4049. }
  4050. /**
  4051. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4052. *
  4053. * @param int[] $detailIds
  4054. */
  4055. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4056. {
  4057. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4058. if ($detailIds === []) {
  4059. return;
  4060. }
  4061. $payload = ['status_name' => $statusName];
  4062. try {
  4063. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4064. } catch (\Throwable $e) {
  4065. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4066. }
  4067. }
  4068. /**
  4069. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4070. */
  4071. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4072. {
  4073. try {
  4074. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4075. } catch (\Throwable $e) {
  4076. return;
  4077. }
  4078. if (!is_array($rows)) {
  4079. return;
  4080. }
  4081. foreach ($rows as $dr) {
  4082. if (!is_array($dr)) {
  4083. continue;
  4084. }
  4085. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4086. if ($id <= 0) {
  4087. continue;
  4088. }
  4089. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4090. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4091. try {
  4092. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4093. } catch (\Throwable $e) {
  4094. }
  4095. }
  4096. }
  4097. /**
  4098. * @param array<string, mixed> $detailRow
  4099. */
  4100. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4101. {
  4102. $am = $detailRow['amount'] ?? null;
  4103. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4104. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4105. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4106. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4107. }
  4108. /**
  4109. * @return int[]
  4110. */
  4111. protected function purchaseOrderDetail(int $scydgyId): array
  4112. {
  4113. if (!$this->isValidScydgyRowId($scydgyId)) {
  4114. return [];
  4115. }
  4116. try {
  4117. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4118. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  4119. $list = $listQuery->select();
  4120. } catch (\Throwable $e) {
  4121. return [];
  4122. }
  4123. if (!is_array($list)) {
  4124. return [];
  4125. }
  4126. $ids = [];
  4127. foreach ($list as $r) {
  4128. if (!is_array($r)) {
  4129. continue;
  4130. }
  4131. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  4132. if ($pk > 0) {
  4133. $ids[] = $pk;
  4134. }
  4135. }
  4136. return array_values(array_unique($ids));
  4137. }
  4138. /**
  4139. * 获取当前登录用户信息 [id, 展示名]
  4140. */
  4141. protected function GetUseName(): array
  4142. {
  4143. $id = 0;
  4144. $name = '';
  4145. try {
  4146. if ($this->auth && $this->auth->isLogin()) {
  4147. $u = $this->auth->getUserInfo();
  4148. if (is_array($u)) {
  4149. $id = (int)($u['id'] ?? 0);
  4150. $name = trim((string)($u['nickname'] ?? ''));
  4151. if ($name === '') {
  4152. $name = trim((string)($u['username'] ?? ''));
  4153. }
  4154. }
  4155. }
  4156. } catch (\Throwable $e) {
  4157. }
  4158. if ($name === '') {
  4159. $name = '未知用户';
  4160. }
  4161. return [$id, $name];
  4162. }
  4163. /**
  4164. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  4165. */
  4166. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  4167. {
  4168. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  4169. }
  4170. /**
  4171. * 按主键取一条
  4172. */
  4173. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  4174. {
  4175. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  4176. return [];
  4177. }
  4178. try {
  4179. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  4180. if (is_array($one)) {
  4181. return $one;
  4182. }
  4183. } catch (\Throwable $e) {
  4184. }
  4185. try {
  4186. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  4187. if (is_array($one)) {
  4188. return $one;
  4189. }
  4190. } catch (\Throwable $e) {
  4191. }
  4192. return [];
  4193. }
  4194. /**
  4195. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  4196. */
  4197. protected function formatProcuremenDetailTime($v): string
  4198. {
  4199. if ($v === null || $v === '') {
  4200. return '';
  4201. }
  4202. if (is_numeric($v) && (int)$v > 946684800) {
  4203. return date('Y-m-d H:i:s', (int)$v);
  4204. }
  4205. return ProcuremenTime::formatDisplayDateTime($v);
  4206. }
  4207. /**
  4208. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  4209. */
  4210. protected function formatDeliveryYmd($v): string
  4211. {
  4212. if ($v === null || $v === '') {
  4213. return '';
  4214. }
  4215. $s = trim((string)$v);
  4216. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  4217. return '';
  4218. }
  4219. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4220. return $m[1];
  4221. }
  4222. $ts = strtotime($s);
  4223. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4224. }
  4225. /**
  4226. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4227. */
  4228. protected function detailRowSupplierOperated(array $r): bool
  4229. {
  4230. $am = $r['amount'] ?? null;
  4231. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4232. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4233. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4234. return $okAmt || $okDel;
  4235. }
  4236. /**
  4237. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4238. */
  4239. protected function resolveDetailSupplierOperTime(array $r): string
  4240. {
  4241. if (!$this->detailRowSupplierOperated($r)) {
  4242. return '';
  4243. }
  4244. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4245. if ($t !== '') {
  4246. return $t;
  4247. }
  4248. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4249. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4250. continue;
  4251. }
  4252. $t = $this->formatProcuremenDetailTime($r[$col]);
  4253. if ($t !== '') {
  4254. return $t;
  4255. }
  4256. }
  4257. return '';
  4258. }
  4259. /**
  4260. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4261. */
  4262. protected function detailRowSupplierAccepted(array $r): bool
  4263. {
  4264. $am = $r['amount'] ?? null;
  4265. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4266. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4267. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4268. return $okAmt && $okDel;
  4269. }
  4270. /**
  4271. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4272. */
  4273. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4274. {
  4275. if ($detailCount > 0) {
  4276. return true;
  4277. }
  4278. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4279. return true;
  4280. }
  4281. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4282. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4283. return true;
  4284. }
  4285. return false;
  4286. }
  4287. /**
  4288. * 下发时间:优先 pick_time,其次首条下发明细时间
  4289. */
  4290. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4291. {
  4292. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4293. if ($issueTime !== '') {
  4294. return $issueTime;
  4295. }
  4296. foreach ($details as $dr) {
  4297. if (!is_array($dr)) {
  4298. continue;
  4299. }
  4300. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4301. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4302. $issueTime = $t;
  4303. }
  4304. }
  4305. if ($issueTime !== '') {
  4306. return $issueTime;
  4307. }
  4308. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4309. }
  4310. /**
  4311. * 直接点「完结」时间:优先操作记录 mark_complete
  4312. */
  4313. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4314. {
  4315. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4316. }
  4317. /**
  4318. * 操作记录时间(取指定 action 最近一条)
  4319. *
  4320. * @param string|array<int, string> $actions
  4321. */
  4322. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4323. {
  4324. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4325. }
  4326. /**
  4327. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4328. *
  4329. * @param array $main purchase_order 一行
  4330. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4331. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4332. */
  4333. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4334. {
  4335. $issueCnt = count($details);
  4336. $acceptCnt = 0;
  4337. $pickedName = '';
  4338. $pickedTime = '';
  4339. foreach ($details as $dr) {
  4340. if (!is_array($dr)) {
  4341. continue;
  4342. }
  4343. if ($this->detailRowSupplierAccepted($dr)) {
  4344. $acceptCnt++;
  4345. }
  4346. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4347. if ($pickedName === '') {
  4348. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4349. }
  4350. if ($pickedTime === '') {
  4351. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4352. if ($pickedTime === '') {
  4353. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4354. }
  4355. }
  4356. }
  4357. }
  4358. $hasMain = $main !== [];
  4359. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4360. if ($poTime === '') {
  4361. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4362. }
  4363. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4364. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4365. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4366. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4367. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4368. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4369. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4370. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4371. $supplierTime = '';
  4372. if ($acceptCnt > 0) {
  4373. foreach ($details as $dr) {
  4374. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4375. continue;
  4376. }
  4377. $t = $this->resolveDetailSupplierOperTime($dr);
  4378. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4379. $supplierTime = $t;
  4380. }
  4381. }
  4382. }
  4383. $directComplete = ($mainCompleted && !$issued);
  4384. $doneTime = '';
  4385. if ($mainCompleted) {
  4386. if ($directComplete) {
  4387. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4388. }
  4389. if ($doneTime === '') {
  4390. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4391. }
  4392. if ($doneTime === '') {
  4393. foreach ($details as $dr) {
  4394. if (!is_array($dr)) {
  4395. continue;
  4396. }
  4397. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4398. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4399. $doneTime = $t;
  4400. }
  4401. }
  4402. }
  4403. if ($doneTime === '') {
  4404. $doneTime = $poTime;
  4405. }
  4406. if ($confirmApproveTime !== '') {
  4407. $doneTime = $confirmApproveTime;
  4408. }
  4409. }
  4410. if ($directComplete) {
  4411. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4412. $step1Done = $hasMain;
  4413. $step2Done = false;
  4414. $step3Done = false;
  4415. $step4Done = false;
  4416. $step5Done = false;
  4417. $step6Done = true;
  4418. } else {
  4419. $step1Done = $issued;
  4420. $step2Done = $issued;
  4421. $step3Done = $acceptCnt > 0;
  4422. $step4Done = $wflowPendingApproval;
  4423. if (!$step4Done) {
  4424. foreach ($details as $dr) {
  4425. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4426. $step4Done = true;
  4427. break;
  4428. }
  4429. }
  4430. }
  4431. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4432. $step6Done = $mainCompleted;
  4433. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4434. if ($mainCompleted && $issued) {
  4435. $step3Done = true;
  4436. $step4Done = true;
  4437. $step5Done = true;
  4438. if ($supplierTime === '') {
  4439. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4440. if ($fillT !== '') {
  4441. $supplierTime = $fillT;
  4442. }
  4443. }
  4444. if ($pickedTime === '') {
  4445. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4446. if ($fillT !== '') {
  4447. $pickedTime = $fillT;
  4448. }
  4449. }
  4450. if ($auditSelectTime === '') {
  4451. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4452. if ($fillT !== '') {
  4453. $auditSelectTime = $fillT;
  4454. }
  4455. }
  4456. if ($confirmApproveTime === '') {
  4457. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4458. if ($fillT !== '') {
  4459. $confirmApproveTime = $fillT;
  4460. }
  4461. }
  4462. }
  4463. }
  4464. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4465. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4466. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4467. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4468. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4469. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4470. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4471. $deadlineLines = [];
  4472. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4473. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4474. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4475. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4476. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  4477. }
  4478. }
  4479. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  4480. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  4481. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  4482. if ($deliveryDisp === '') {
  4483. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  4484. }
  4485. if ($deliveryDisp !== '') {
  4486. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  4487. }
  4488. }
  4489. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  4490. $deadlineText = implode("\n", $deadlineLines);
  4491. $prefixOperTime = static function (string $t): string {
  4492. $t = trim($t);
  4493. if ($t === '' || $t === '—') {
  4494. return $t;
  4495. }
  4496. if (strpos($t, '操作时间') === 0) {
  4497. return $t;
  4498. }
  4499. return '操作时间:' . $t;
  4500. };
  4501. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  4502. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  4503. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '';
  4504. $step6Time = $step6Done ? $doneTime : '';
  4505. $steps = [
  4506. [
  4507. 'title' => '未发',
  4508. 'subtitle' => '',
  4509. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  4510. 'done' => $step1Done,
  4511. ],
  4512. [
  4513. 'title' => '下发',
  4514. 'subtitle' => $deadlineText,
  4515. 'time' => $prefixOperTime($step2Time),
  4516. 'done' => $step2Done,
  4517. ],
  4518. [
  4519. 'title' => '供应商接单',
  4520. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4521. 'time' => '',
  4522. 'done' => $step3Done,
  4523. ],
  4524. [
  4525. 'title' => '待确认',
  4526. 'subtitle' => $step4Done
  4527. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4528. : ($issued ? '待选供应商' : ''),
  4529. 'time' => $prefixOperTime($step4Time),
  4530. 'done' => $step4Done,
  4531. ],
  4532. [
  4533. 'title' => '待审批',
  4534. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4535. 'time' => $prefixOperTime($step5Time),
  4536. 'done' => $step5Done,
  4537. ],
  4538. [
  4539. 'title' => '已完结',
  4540. 'subtitle' => '',
  4541. 'time' => $prefixOperTime($step6Time),
  4542. 'done' => $step6Done,
  4543. ],
  4544. ];
  4545. $currentIdx = count($steps) - 1;
  4546. if (!$directComplete) {
  4547. foreach ($steps as $i => $s) {
  4548. if (!$s['done']) {
  4549. $currentIdx = $i;
  4550. break;
  4551. }
  4552. }
  4553. }
  4554. $nSteps = count($steps);
  4555. foreach ($steps as $idx => &$s) {
  4556. $s['current'] = ($idx === $currentIdx);
  4557. if ($idx === 0) {
  4558. $s['pdf_left_bg'] = '';
  4559. } else {
  4560. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4561. }
  4562. if ($idx >= $nSteps - 1) {
  4563. $s['pdf_right_bg'] = '';
  4564. } else {
  4565. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4566. }
  4567. }
  4568. unset($s);
  4569. $labelMap = [
  4570. 'CCYDH' => '订单号',
  4571. 'CYJMC' => '印件名称',
  4572. 'CCLBMMC' => '承揽部门',
  4573. 'CGYMC' => '工序名称',
  4574. 'CDW' => '单位',
  4575. 'czlyq' => '类型',
  4576. 'NGZL' => '工作量',
  4577. 'CDF' => '单价',
  4578. 'cGzzxMc' => '工作中心',
  4579. 'MBZ' => '备注',
  4580. 'This_quantity' => '本次数量',
  4581. 'ceilingPrice' => '最高限价',
  4582. ];
  4583. $orderSummary = [];
  4584. foreach ($labelMap as $key => $lab) {
  4585. if (!array_key_exists($key, $main)) {
  4586. continue;
  4587. }
  4588. $val = $main[$key];
  4589. if ($val === null) {
  4590. $val = '';
  4591. } elseif (!is_scalar($val)) {
  4592. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4593. } else {
  4594. $val = (string)$val;
  4595. }
  4596. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4597. }
  4598. $orderSummaryGrid = [];
  4599. $n = count($orderSummary);
  4600. for ($i = 0; $i < $n; $i += 2) {
  4601. $left = $orderSummary[$i];
  4602. $hasRight = ($i + 1) < $n;
  4603. $orderSummaryGrid[] = [
  4604. 'l1' => $left['label'],
  4605. 'v1' => $left['value'],
  4606. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4607. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4608. ];
  4609. }
  4610. return [
  4611. 'steps' => $steps,
  4612. 'orderSummary' => $orderSummary,
  4613. 'orderSummaryGrid' => $orderSummaryGrid,
  4614. 'detailRows' => $details,
  4615. ];
  4616. }
  4617. /**
  4618. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4619. *
  4620. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4621. */
  4622. protected function prepareProcuremenDetailsView(string $ids): array
  4623. {
  4624. $main = [];
  4625. try {
  4626. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4627. $main = is_array($one) ? $one : [];
  4628. } catch (\Throwable $e) {
  4629. $main = [];
  4630. }
  4631. $details = [];
  4632. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4633. if ($mergeRows === []) {
  4634. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4635. if ($mergeRows === [] && $main !== []) {
  4636. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4637. }
  4638. }
  4639. $detailSidList = [];
  4640. $anchorSid = (int)$ids;
  4641. if ($anchorSid !== 0) {
  4642. $detailSidList[$anchorSid] = true;
  4643. }
  4644. foreach ($mergeRows as $mr) {
  4645. if (!is_array($mr)) {
  4646. continue;
  4647. }
  4648. $sid = $this->extractScydgyRowId($mr);
  4649. if ($sid !== 0) {
  4650. $detailSidList[$sid] = true;
  4651. }
  4652. }
  4653. try {
  4654. if ($detailSidList !== []) {
  4655. $details = Db::table('purchase_order_detail')
  4656. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4657. ->order('id', 'asc')
  4658. ->select();
  4659. }
  4660. } catch (\Throwable $e) {
  4661. $details = [];
  4662. }
  4663. if (!is_array($details)) {
  4664. $details = [];
  4665. }
  4666. foreach ($details as &$r) {
  4667. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4668. $r['id'] = $r['ID'];
  4669. }
  4670. if (isset($r['createtime'])) {
  4671. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4672. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4673. } else {
  4674. $r['createtime_text'] = (string)$r['createtime'];
  4675. }
  4676. } else {
  4677. $r['createtime_text'] = '';
  4678. }
  4679. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4680. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4681. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4682. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4683. if (is_array($r)) {
  4684. $r = $this->maskSupplierContactFields($r);
  4685. }
  4686. }
  4687. unset($r);
  4688. $activeDetails = [];
  4689. foreach ($details as $r) {
  4690. if (is_array($r) && empty($r['is_void'])) {
  4691. $activeDetails[] = $r;
  4692. }
  4693. }
  4694. $operLogs = [];
  4695. try {
  4696. $operSidList = array_keys($detailSidList);
  4697. if ($operSidList === [] && (int)$ids !== 0) {
  4698. $operSidList = [(int)$ids];
  4699. }
  4700. if ($operSidList !== []) {
  4701. $operLogs = Db::table('purchase_order_oper_log')
  4702. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  4703. ->order('id', 'asc')
  4704. ->select();
  4705. }
  4706. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  4707. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  4708. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  4709. if ($poId > 0) {
  4710. $operLogs = Db::table('purchase_order_oper_log')
  4711. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  4712. ->order('id', 'asc')
  4713. ->select();
  4714. }
  4715. }
  4716. } catch (\Throwable $e) {
  4717. $operLogs = [];
  4718. }
  4719. if (!is_array($operLogs)) {
  4720. $operLogs = [];
  4721. }
  4722. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4723. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4724. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4725. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4726. if ($ccydh === '') {
  4727. foreach ($details as $r) {
  4728. if (!is_array($r)) {
  4729. continue;
  4730. }
  4731. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4732. if ($ccydh !== '') {
  4733. break;
  4734. }
  4735. }
  4736. }
  4737. $this->view->assign('ccydh', $ccydh);
  4738. $this->view->assign('steps', $bundle['steps']);
  4739. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4740. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4741. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4742. $this->view->assign('processCount', count($mergeRows));
  4743. $this->view->assign('detailRows', $details);
  4744. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4745. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4746. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4747. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4748. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4749. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4750. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4751. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4752. $this->view->assign('operLogs', $operLogs);
  4753. $sg = $quoteView['supplier_groups'] ?? [];
  4754. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : []));
  4755. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : []) ? 1 : 0);
  4756. return [
  4757. 'ok' => $main !== [] || $details !== [],
  4758. 'ccydh' => $ccydh,
  4759. ];
  4760. }
  4761. /**
  4762. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4763. */
  4764. public function details()
  4765. {
  4766. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4767. if (is_array($ids)) {
  4768. $ids = isset($ids[0]) ? $ids[0] : '';
  4769. }
  4770. $ids = trim((string)$ids);
  4771. if ($ids === '') {
  4772. $this->error(__('Invalid parameters'));
  4773. }
  4774. $this->assertManualOrderDetailsViewable((int)$ids);
  4775. $this->prepareProcuremenDetailsView($ids);
  4776. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4777. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4778. $this->view->engine->layout(false);
  4779. try {
  4780. return $this->view->fetch('procuremen/details_dialog_shell');
  4781. } finally {
  4782. if ($restoreLayout) {
  4783. $this->view->engine->layout($restoreLayout);
  4784. }
  4785. }
  4786. }
  4787. /**
  4788. * 解析合并审核工序行(订单号须一致,且均未协助)
  4789. *
  4790. * @return array<int, array<string, mixed>>
  4791. */
  4792. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4793. {
  4794. $primary = json_decode($rowJson, true);
  4795. if (!is_array($primary)) {
  4796. $this->error(__('Invalid parameters'));
  4797. }
  4798. $merge = json_decode($mergeRowsJson, true);
  4799. if (!is_array($merge) || $merge === []) {
  4800. $merge = [$primary];
  4801. }
  4802. $seen = [];
  4803. $out = [];
  4804. foreach ($merge as $r) {
  4805. if (!is_array($r)) {
  4806. continue;
  4807. }
  4808. $id = $this->extractScydgyRowId($r);
  4809. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4810. continue;
  4811. }
  4812. $seen[$id] = true;
  4813. $out[] = $r;
  4814. }
  4815. if ($out === []) {
  4816. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4817. }
  4818. $ccydh = null;
  4819. foreach ($out as $r) {
  4820. $dh = trim((string)($r['CCYDH'] ?? ''));
  4821. if ($ccydh === null) {
  4822. $ccydh = $dh;
  4823. } elseif ($dh !== $ccydh) {
  4824. $this->error('合并审核要求所选行的订单号一致');
  4825. }
  4826. }
  4827. $ids = [];
  4828. foreach ($out as $r) {
  4829. $id = $this->extractScydgyRowId($r);
  4830. if ($this->isValidScydgyRowId($id)) {
  4831. $ids[$id] = true;
  4832. }
  4833. }
  4834. $poBySid = [];
  4835. $detCntBySid = [];
  4836. if ($ids !== []) {
  4837. $idList = array_keys($ids);
  4838. try {
  4839. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4840. if (is_array($poList)) {
  4841. foreach ($poList as $po) {
  4842. if (!is_array($po)) {
  4843. continue;
  4844. }
  4845. $sid = (int)($po['scydgy_id'] ?? 0);
  4846. if ($this->isValidScydgyRowId($sid)) {
  4847. $poBySid[$sid] = $po;
  4848. }
  4849. }
  4850. }
  4851. } catch (\Throwable $e) {
  4852. }
  4853. try {
  4854. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4855. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4856. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4857. if (is_array($detRows)) {
  4858. foreach ($detRows as $dr) {
  4859. if (!is_array($dr)) {
  4860. continue;
  4861. }
  4862. $sid = (int)($dr['scydgy_id'] ?? 0);
  4863. if ($this->isValidScydgyRowId($sid)) {
  4864. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4865. }
  4866. }
  4867. }
  4868. } catch (\Throwable $e) {
  4869. }
  4870. }
  4871. foreach ($out as $r) {
  4872. $id = $this->extractScydgyRowId($r);
  4873. if (!$this->isValidScydgyRowId($id)) {
  4874. continue;
  4875. }
  4876. $po = $poBySid[$id] ?? null;
  4877. if (!is_array($po)) {
  4878. continue;
  4879. }
  4880. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4881. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4882. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4883. }
  4884. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4885. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4886. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4887. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4888. }
  4889. }
  4890. return $out;
  4891. }
  4892. /**
  4893. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4894. */
  4895. protected function maskSupplierContactFields(array $item): array
  4896. {
  4897. if (array_key_exists('email', $item)) {
  4898. $item['email'] = mask_email((string)$item['email']);
  4899. }
  4900. if (array_key_exists('phone', $item)) {
  4901. $item['phone'] = mask_phone((string)$item['phone']);
  4902. }
  4903. return $item;
  4904. }
  4905. /**
  4906. * @param array<int, array<string, mixed>> $list
  4907. * @return array<int, array<string, mixed>>
  4908. */
  4909. protected function maskSupplierContactList(array $list): array
  4910. {
  4911. $out = [];
  4912. foreach ($list as $item) {
  4913. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4914. }
  4915. return $out;
  4916. }
  4917. /**
  4918. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4919. *
  4920. * @return array<string, string>|null
  4921. */
  4922. protected function buildCustomerContactPayloadFromRow($row): ?array
  4923. {
  4924. if (!is_array($row)) {
  4925. return null;
  4926. }
  4927. $norm = [];
  4928. foreach ($row as $k => $v) {
  4929. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4930. }
  4931. $row = $norm;
  4932. $st = $row['status'] ?? '';
  4933. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4934. return null;
  4935. }
  4936. $companyName = '';
  4937. foreach (['company_name', 'name'] as $nk) {
  4938. if (!empty($row[$nk])) {
  4939. $companyName = trim((string)$row[$nk]);
  4940. break;
  4941. }
  4942. }
  4943. if ($companyName === '') {
  4944. return null;
  4945. }
  4946. $username = '';
  4947. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4948. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4949. $username = trim((string)$row[$uk]);
  4950. break;
  4951. }
  4952. }
  4953. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4954. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4955. if ($phone === '' && isset($row['account'])) {
  4956. $phone = trim((string)$row['account']);
  4957. }
  4958. if ($phone === '' && isset($row['mobile'])) {
  4959. $phone = trim((string)$row['mobile']);
  4960. }
  4961. if ($email === '' && $phone === '') {
  4962. return null;
  4963. }
  4964. $category = '';
  4965. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4966. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4967. $category = trim((string)$row[$ck]);
  4968. break;
  4969. }
  4970. }
  4971. return [
  4972. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4973. 'name' => $companyName,
  4974. 'company_name' => $companyName,
  4975. 'username' => $username,
  4976. 'email' => $email,
  4977. 'phone' => $phone,
  4978. 'category' => $category,
  4979. 'company_type' => $category,
  4980. ];
  4981. }
  4982. /**
  4983. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4984. */
  4985. protected function resolveCustomerContactById(string $id): ?array
  4986. {
  4987. $id = trim($id);
  4988. if ($id === '' || !ctype_digit($id)) {
  4989. return null;
  4990. }
  4991. try {
  4992. $row = Db::table('customer')->where('id', (int)$id)->find();
  4993. } catch (\Throwable $e) {
  4994. return null;
  4995. }
  4996. return $this->buildCustomerContactPayloadFromRow($row);
  4997. }
  4998. /**
  4999. * 按供应商名称解析联系信息(兼容旧提交数据)
  5000. */
  5001. protected function resolveCustomerContactByCompanyName(string $name): ?array
  5002. {
  5003. $name = trim($name);
  5004. if ($name === '') {
  5005. return null;
  5006. }
  5007. try {
  5008. $row = Db::table('customer')
  5009. ->where(function ($q) use ($name) {
  5010. $q->where('company_name', $name)->whereOr('name', $name);
  5011. })
  5012. ->order('id', 'desc')
  5013. ->find();
  5014. } catch (\Throwable $e) {
  5015. return null;
  5016. }
  5017. return $this->buildCustomerContactPayloadFromRow($row);
  5018. }
  5019. /**
  5020. * 规范化下发/确认时勾选的供应商
  5021. *
  5022. * @param array<int, mixed> $companies
  5023. * @return array<int, array<string, string>>
  5024. */
  5025. protected function normalizePickCompanies(array $companies): array
  5026. {
  5027. $out = [];
  5028. foreach ($companies as $c) {
  5029. if (!is_array($c)) {
  5030. continue;
  5031. }
  5032. $resolved = null;
  5033. $cid = trim((string)($c['id'] ?? ''));
  5034. if ($cid !== '') {
  5035. $resolved = $this->resolveCustomerContactById($cid);
  5036. }
  5037. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  5038. if ($resolved === null && $name !== '') {
  5039. $resolved = $this->resolveCustomerContactByCompanyName($name);
  5040. }
  5041. if ($resolved === null) {
  5042. continue;
  5043. }
  5044. $out[] = $resolved;
  5045. }
  5046. return $out;
  5047. }
  5048. /**
  5049. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  5050. *
  5051. * @param array<int, array<string, mixed>> $pool
  5052. * @return array<int, array<string, mixed>>
  5053. */
  5054. protected function collapseProcuremenPoolByOrder(array $pool): array
  5055. {
  5056. if ($pool === []) {
  5057. return [];
  5058. }
  5059. $groups = [];
  5060. foreach ($pool as $row) {
  5061. if (!is_array($row)) {
  5062. continue;
  5063. }
  5064. $dh = trim((string)($row['CCYDH'] ?? ''));
  5065. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  5066. if (!isset($groups[$key])) {
  5067. $groups[$key] = [];
  5068. }
  5069. $groups[$key][] = $row;
  5070. }
  5071. $out = [];
  5072. foreach ($groups as $ccydh => $rows) {
  5073. if ($rows === []) {
  5074. continue;
  5075. }
  5076. usort($rows, function ($a, $b) {
  5077. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  5078. });
  5079. $head = $rows[0];
  5080. $gymcList = [];
  5081. foreach ($rows as $r) {
  5082. $g = trim((string)($r['CGYMC'] ?? ''));
  5083. if ($g !== '' && !in_array($g, $gymcList, true)) {
  5084. $gymcList[] = $g;
  5085. }
  5086. }
  5087. $merged = $head;
  5088. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  5089. $merged['process_count'] = count($rows);
  5090. $merged['_order_merge_rows'] = $rows;
  5091. if (count($rows) > 1) {
  5092. $merged['CGYMC'] = implode('、', $gymcList);
  5093. }
  5094. $mergedPickTime = '';
  5095. foreach ($rows as $r) {
  5096. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  5097. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  5098. $mergedPickTime = $t;
  5099. }
  5100. }
  5101. if ($mergedPickTime !== '') {
  5102. $merged['pick_time'] = $mergedPickTime;
  5103. }
  5104. $out[] = $merged;
  5105. }
  5106. usort($out, function ($a, $b) {
  5107. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  5108. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  5109. if ($ta === $tb) {
  5110. $ida = (int)($a['purchase_order_id'] ?? 0);
  5111. $idb = (int)($b['purchase_order_id'] ?? 0);
  5112. if ($ida !== $idb) {
  5113. return $idb <=> $ida;
  5114. }
  5115. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  5116. }
  5117. if ($ta === '') {
  5118. return 1;
  5119. }
  5120. if ($tb === '') {
  5121. return -1;
  5122. }
  5123. return strcmp($tb, $ta);
  5124. });
  5125. return $out;
  5126. }
  5127. /**
  5128. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  5129. *
  5130. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5131. */
  5132. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  5133. {
  5134. $scydgyId = trim($scydgyId);
  5135. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5136. if ($scydgyId === '') {
  5137. return $empty;
  5138. }
  5139. try {
  5140. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5141. } catch (\Throwable $e) {
  5142. $anchor = null;
  5143. }
  5144. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  5145. return $empty;
  5146. }
  5147. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5148. if ($ccydh === '') {
  5149. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5150. }
  5151. try {
  5152. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  5153. } catch (\Throwable $e) {
  5154. $pos = [$anchor];
  5155. }
  5156. if (!is_array($pos) || $pos === []) {
  5157. $pos = [$anchor];
  5158. }
  5159. return [
  5160. 'ccydh' => $ccydh,
  5161. 'pos' => $pos,
  5162. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5163. ];
  5164. }
  5165. /**
  5166. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  5167. */
  5168. protected function purchaseOrderRowInConfirmStage(array $po): bool
  5169. {
  5170. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5171. return false;
  5172. }
  5173. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  5174. return false;
  5175. }
  5176. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  5177. return true;
  5178. }
  5179. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  5180. $sid = (int)($po['scydgy_id'] ?? 0);
  5181. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  5182. }
  5183. return false;
  5184. }
  5185. /**
  5186. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  5187. *
  5188. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5189. */
  5190. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  5191. {
  5192. $scydgyId = trim($scydgyId);
  5193. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5194. if ($scydgyId === '') {
  5195. return $empty;
  5196. }
  5197. try {
  5198. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5199. } catch (\Throwable $e) {
  5200. $anchor = null;
  5201. }
  5202. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  5203. return $empty;
  5204. }
  5205. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5206. if ($ccydh === '') {
  5207. return [
  5208. 'ccydh' => '',
  5209. 'pos' => [$anchor],
  5210. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  5211. ];
  5212. }
  5213. try {
  5214. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5215. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  5216. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  5217. } catch (\Throwable $e) {
  5218. $pos = [$anchor];
  5219. }
  5220. if (!is_array($pos) || $pos === []) {
  5221. $pos = [$anchor];
  5222. }
  5223. $pos = array_values(array_filter($pos, function ($po) {
  5224. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  5225. }));
  5226. if ($pos === []) {
  5227. $pos = [$anchor];
  5228. }
  5229. return [
  5230. 'ccydh' => $ccydh,
  5231. 'pos' => $pos,
  5232. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5233. ];
  5234. }
  5235. /**
  5236. * @param array<int, array<string, mixed>> $purchaseOrders
  5237. * @return array<int, array<string, mixed>>
  5238. */
  5239. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  5240. {
  5241. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  5242. $byId = [];
  5243. foreach ($pool as $r) {
  5244. if (!is_array($r)) {
  5245. continue;
  5246. }
  5247. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  5248. if ($this->isValidScydgyRowId($sid)) {
  5249. $byId[$sid] = $r;
  5250. }
  5251. }
  5252. $out = [];
  5253. foreach ($purchaseOrders as $po) {
  5254. if (!is_array($po)) {
  5255. continue;
  5256. }
  5257. $sid = (int)($po['scydgy_id'] ?? 0);
  5258. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  5259. $out[] = $byId[$sid];
  5260. }
  5261. }
  5262. return $out;
  5263. }
  5264. /**
  5265. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  5266. *
  5267. * @return array<int, array<string, mixed>>
  5268. */
  5269. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5270. {
  5271. $scydgyId = trim($scydgyId);
  5272. if ($scydgyId === '') {
  5273. return [];
  5274. }
  5275. try {
  5276. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5277. } catch (\Throwable $e) {
  5278. $anchor = null;
  5279. }
  5280. if (!is_array($anchor)) {
  5281. return [];
  5282. }
  5283. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5284. return [];
  5285. }
  5286. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5287. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5288. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5289. try {
  5290. $q = Db::table('purchase_order');
  5291. if ($ccydh !== '') {
  5292. $q->where('CCYDH', $ccydh);
  5293. } else {
  5294. $q->where('scydgy_id', $scydgyId);
  5295. }
  5296. if ($isValidPick) {
  5297. $q->where('pick_time', $pickTime);
  5298. }
  5299. $pos = $q->order('scydgy_id', 'asc')->select();
  5300. } catch (\Throwable $e) {
  5301. $pos = [$anchor];
  5302. }
  5303. if (!is_array($pos) || $pos === []) {
  5304. $pos = [$anchor];
  5305. }
  5306. $pos = array_values(array_filter($pos, function ($po) {
  5307. if (!is_array($po)) {
  5308. return false;
  5309. }
  5310. $mr = $po['mod_rq'] ?? null;
  5311. if ($mr === null || $mr === '') {
  5312. return true;
  5313. }
  5314. $mrs = trim((string)$mr);
  5315. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5316. }));
  5317. if ($pos === []) {
  5318. $pos = [$anchor];
  5319. }
  5320. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5321. if ($rows === []) {
  5322. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5323. }
  5324. return $rows;
  5325. }
  5326. /**
  5327. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5328. *
  5329. * @param array<int, array<string, mixed>> $mergeRows
  5330. * @return array<int, array<string, mixed>>
  5331. */
  5332. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5333. {
  5334. $list = array_values($mergeRows);
  5335. $n = count($list);
  5336. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5337. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5338. $mergeSame = $n > 1 && $orderKey0 !== '';
  5339. if ($mergeSame) {
  5340. foreach ($list as $rr) {
  5341. if (!is_array($rr)) {
  5342. $mergeSame = false;
  5343. break;
  5344. }
  5345. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5346. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5347. $mergeSame = false;
  5348. break;
  5349. }
  5350. }
  5351. }
  5352. $out = [];
  5353. foreach ($list as $idx => $r) {
  5354. if (!is_array($r)) {
  5355. continue;
  5356. }
  5357. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5358. if (is_scalar($qty)) {
  5359. $qty = trim((string)$qty);
  5360. } else {
  5361. $qty = '';
  5362. }
  5363. if ($qty === '') {
  5364. $gzl = $r['NGZL'] ?? '';
  5365. if (is_scalar($gzl)) {
  5366. $qty = trim((string)$gzl);
  5367. }
  5368. }
  5369. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5370. $sid = $this->extractScydgyRowId($r);
  5371. $out[] = [
  5372. 'seq' => $idx + 1,
  5373. 'scydgy_id' => $sid,
  5374. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5375. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5376. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5377. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5378. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  5379. 'NGZL' => $r['NGZL'] ?? '',
  5380. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5381. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5382. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5383. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5384. 'show_order_cells' => !$mergeSame || $idx === 0,
  5385. 'order_rowspan' => $mergeSame ? $n : 1,
  5386. ];
  5387. }
  5388. return $out;
  5389. }
  5390. /**
  5391. * 解析金额/数量(去千分位等非数字字符)
  5392. */
  5393. protected function parseProcuremenMoneyNumber($value): ?float
  5394. {
  5395. if ($value === null || $value === '') {
  5396. return null;
  5397. }
  5398. if (is_numeric($value)) {
  5399. return (float)$value;
  5400. }
  5401. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5402. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5403. }
  5404. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5405. {
  5406. if ($amount === null) {
  5407. return '';
  5408. }
  5409. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  5410. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  5411. return $s === '' ? '0' : $s;
  5412. }
  5413. /**
  5414. * 列表/详情展示:工作量为 0 时显示空
  5415. */
  5416. protected function formatProcuremenWorkloadDisplay($value): string
  5417. {
  5418. if ($value === null || $value === '') {
  5419. return '';
  5420. }
  5421. $s = trim((string)$value);
  5422. if ($s === '') {
  5423. return '';
  5424. }
  5425. if (is_numeric($s) && (float)$s == 0) {
  5426. return '';
  5427. }
  5428. return $s;
  5429. }
  5430. /**
  5431. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5432. */
  5433. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5434. {
  5435. foreach ($details as $d) {
  5436. if (!is_array($d)) {
  5437. continue;
  5438. }
  5439. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5440. $cn = trim((string)($d['company_name'] ?? ''));
  5441. if ($cn !== '') {
  5442. return $cn;
  5443. }
  5444. }
  5445. }
  5446. return trim((string)($main['pick_company_name'] ?? ''));
  5447. }
  5448. /**
  5449. * 详情报价小计:单价 × 本工序本次数量
  5450. */
  5451. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5452. {
  5453. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5454. if ($unit === null) {
  5455. return null;
  5456. }
  5457. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5458. if ($qty === null || $qty <= 0) {
  5459. return null;
  5460. }
  5461. return $unit * $qty;
  5462. }
  5463. /**
  5464. * 详情页:工序小计 + 供应商分组报价与总计
  5465. *
  5466. * @param array<int, array<string, mixed>> $mergeRows
  5467. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5468. * @return array{
  5469. * process_rows: array,
  5470. * supplier_groups: array,
  5471. * order_total_text: string,
  5472. * order_total_has: bool,
  5473. * selected_company: string
  5474. * }
  5475. */
  5476. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5477. {
  5478. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5479. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5480. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5481. $qtyBySid = [];
  5482. $gymcBySid = [];
  5483. $orderedSids = [];
  5484. foreach ($mergeRows as $mr) {
  5485. if (!is_array($mr)) {
  5486. continue;
  5487. }
  5488. $sid = $this->extractScydgyRowId($mr);
  5489. if ($this->isValidScydgyRowId($sid)) {
  5490. $orderedSids[] = $sid;
  5491. }
  5492. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5493. if ($qty === '') {
  5494. $qty = trim((string)($mr['NGZL'] ?? ''));
  5495. }
  5496. $qtyBySid[$sid] = $qty;
  5497. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5498. }
  5499. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5500. $detailByCompanySid = [];
  5501. foreach ($details as $d) {
  5502. if (!is_array($d)) {
  5503. continue;
  5504. }
  5505. $cn = trim((string)($d['company_name'] ?? ''));
  5506. $sid = (int)($d['scydgy_id'] ?? 0);
  5507. if ($cn === '' || $sid === 0) {
  5508. continue;
  5509. }
  5510. if (!isset($detailByCompanySid[$cn])) {
  5511. $detailByCompanySid[$cn] = [];
  5512. }
  5513. $detailByCompanySid[$cn][$sid] = $d;
  5514. }
  5515. $supplierGroups = [];
  5516. foreach ($detailByCompanySid as $cn => $bySid) {
  5517. $lines = [];
  5518. $groupTotal = 0.0;
  5519. $groupHas = false;
  5520. $groupVoid = true;
  5521. $usedSids = [];
  5522. $appendLine = function (int $sid, array $d) use (
  5523. &$lines,
  5524. &$groupTotal,
  5525. &$groupHas,
  5526. &$groupVoid,
  5527. $qtyBySid,
  5528. $gymcBySid,
  5529. $quoteVisible
  5530. ) {
  5531. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5532. if (!$isVoid) {
  5533. $groupVoid = false;
  5534. }
  5535. $qtyStr = $qtyBySid[$sid] ?? '';
  5536. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5537. $am = trim((string)($d['amount'] ?? ''));
  5538. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5539. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5540. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5541. $sub = null;
  5542. if (!$isVoid && $amountNum !== null) {
  5543. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5544. }
  5545. $ct = $this->resolveDetailSupplierOperTime($d);
  5546. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5547. $leadFilled = ($leadDays !== null);
  5548. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5549. $line = [
  5550. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5551. 'amount' => $am,
  5552. 'unit_price_text' => $amountFilled
  5553. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5554. : '未填写',
  5555. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5556. 'delivery_ymd' => $deliveryYmd,
  5557. 'amount_filled' => $amountFilled,
  5558. 'delivery_filled' => $deliveryFilled,
  5559. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5560. 'lead_days' => $leadFilled ? $leadDays : '',
  5561. 'lead_days_filled'=> $leadFilled,
  5562. 'lead_days_show' => $leadText,
  5563. 'lead_days_text' => $leadText,
  5564. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5565. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5566. 'is_void' => $isVoid,
  5567. 'oper_time_text' => $ct,
  5568. ];
  5569. if (!$quoteVisible && !$isVoid) {
  5570. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5571. } elseif ($sub !== null) {
  5572. $groupTotal += $sub;
  5573. $groupHas = true;
  5574. }
  5575. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5576. };
  5577. foreach ($orderedSids as $sid) {
  5578. if (!isset($bySid[$sid])) {
  5579. continue;
  5580. }
  5581. $usedSids[$sid] = true;
  5582. $appendLine($sid, $bySid[$sid]);
  5583. }
  5584. foreach ($bySid as $sid => $d) {
  5585. if (isset($usedSids[$sid])) {
  5586. continue;
  5587. }
  5588. $appendLine((int)$sid, $d);
  5589. }
  5590. $firstDetail = null;
  5591. foreach ($bySid as $d) {
  5592. if (is_array($d)) {
  5593. $firstDetail = $d;
  5594. break;
  5595. }
  5596. }
  5597. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5598. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5599. if ($username === '' && $ph !== '') {
  5600. $username = $this->resolveCustomerContactName($ph, $cn);
  5601. }
  5602. $remark = '';
  5603. foreach ($bySid as $d) {
  5604. if (!is_array($d)) {
  5605. continue;
  5606. }
  5607. $rm = '';
  5608. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5609. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5610. $rm = trim((string)$d[$rk]);
  5611. break;
  5612. }
  5613. }
  5614. if ($rm !== '') {
  5615. $remark = $rm;
  5616. break;
  5617. }
  5618. }
  5619. $lineCount = count($lines);
  5620. $hasRemark = $lineCount > 0;
  5621. $supplierGroup = [
  5622. 'company_name' => $cn,
  5623. 'username' => $username,
  5624. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5625. 'phone' => $ph,
  5626. 'remark' => $remark,
  5627. 'has_remark' => $hasRemark,
  5628. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5629. 'is_void' => $groupVoid,
  5630. 'lines' => $lines,
  5631. 'line_count' => $lineCount,
  5632. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5633. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5634. 'has_total' => $lineCount > 0,
  5635. ];
  5636. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5637. $supplierGroups[] = $supplierGroup;
  5638. }
  5639. usort($supplierGroups, function ($a, $b) {
  5640. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5641. return ($a['is_void'] ?? false) ? 1 : -1;
  5642. }
  5643. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5644. return ($a['is_selected'] ?? false) ? -1 : 1;
  5645. }
  5646. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5647. });
  5648. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  5649. return [
  5650. 'process_rows' => $processRows,
  5651. 'supplier_groups' => $supplierGroups,
  5652. 'order_total_text' => '',
  5653. 'order_total_has' => false,
  5654. 'selected_company' => $selectedCompany,
  5655. ];
  5656. }
  5657. /**
  5658. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5659. */
  5660. protected function buildProcessLinesPlain(array $mergeRows): string
  5661. {
  5662. $lines = [];
  5663. $i = 1;
  5664. foreach ($mergeRows as $r) {
  5665. if (!is_array($r)) {
  5666. continue;
  5667. }
  5668. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5669. $dw = trim((string)($r['CDW'] ?? ''));
  5670. $gzl = trim((string)($r['NGZL'] ?? ''));
  5671. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5672. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5673. if ($dw !== '') {
  5674. $parts[] = '单位:' . $dw;
  5675. }
  5676. if ($gzl !== '') {
  5677. $parts[] = '工作量:' . $gzl;
  5678. }
  5679. if ($qty !== '') {
  5680. $parts[] = '本次数量:' . $qty;
  5681. }
  5682. $lines[] = implode(' ', $parts);
  5683. $i++;
  5684. }
  5685. return implode("\n", $lines);
  5686. }
  5687. /**
  5688. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5689. *
  5690. * @return array<string, string>
  5691. */
  5692. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5693. {
  5694. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5695. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5696. }
  5697. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5698. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5699. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5700. $cyjmc = '';
  5701. foreach ($mergeRows as $mr) {
  5702. if (!is_array($mr)) {
  5703. continue;
  5704. }
  5705. if ($ccydh === '') {
  5706. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5707. }
  5708. if ($cyjmc === '') {
  5709. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5710. }
  5711. }
  5712. if ($pos !== []) {
  5713. $firstPo = $pos[0];
  5714. if (is_array($firstPo)) {
  5715. if ($ccydh === '') {
  5716. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5717. }
  5718. if ($cyjmc === '') {
  5719. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5720. }
  5721. }
  5722. }
  5723. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5724. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5725. if (is_array($any)) {
  5726. if ($ccydh === '') {
  5727. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5728. }
  5729. if ($cyjmc === '') {
  5730. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5731. }
  5732. }
  5733. }
  5734. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5735. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5736. $cgymc = '';
  5737. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5738. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5739. }
  5740. return [
  5741. 'ccydh' => $ccydh,
  5742. 'cyjmc' => $cyjmc,
  5743. 'cgymc' => $cgymc,
  5744. 'process_lines' => $processLines,
  5745. 'process_lines_html' => '',
  5746. ];
  5747. }
  5748. /**
  5749. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5750. */
  5751. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5752. {
  5753. $lines = [];
  5754. if ($ccydh !== '') {
  5755. $lines[] = '订单号:' . $ccydh;
  5756. }
  5757. if ($cyjmc !== '') {
  5758. $lines[] = '印件名称:' . $cyjmc;
  5759. }
  5760. if ($processPlain !== '') {
  5761. $lines[] = $processPlain;
  5762. }
  5763. return implode("\n", $lines);
  5764. }
  5765. /**
  5766. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5767. *
  5768. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5769. */
  5770. protected function buildPlatformLinksPlain(array $detailLinks): string
  5771. {
  5772. $lines = [];
  5773. $i = 1;
  5774. foreach ($detailLinks as $lk) {
  5775. if (!is_array($lk)) {
  5776. continue;
  5777. }
  5778. $url = trim((string)($lk['url'] ?? ''));
  5779. if ($url === '') {
  5780. continue;
  5781. }
  5782. $label = trim((string)($lk['cgymc'] ?? ''));
  5783. if ($label === '') {
  5784. $label = '工序' . $i;
  5785. }
  5786. $lines[] = $label . ':' . $url;
  5787. $i++;
  5788. }
  5789. return implode("\n", $lines);
  5790. }
  5791. /**
  5792. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5793. *
  5794. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5795. */
  5796. protected function buildPlatformLinksHtml(array $detailLinks): string
  5797. {
  5798. $parts = [];
  5799. $i = 1;
  5800. foreach ($detailLinks as $lk) {
  5801. if (!is_array($lk)) {
  5802. continue;
  5803. }
  5804. $url = trim((string)($lk['url'] ?? ''));
  5805. if ($url === '') {
  5806. continue;
  5807. }
  5808. $label = trim((string)($lk['cgymc'] ?? ''));
  5809. if ($label === '') {
  5810. $label = '工序' . $i;
  5811. }
  5812. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5813. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5814. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5815. $i++;
  5816. }
  5817. return implode("<br>\n", $parts);
  5818. }
  5819. /**
  5820. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5821. *
  5822. * @return array<string, mixed>
  5823. */
  5824. protected function loadMailerConfig(): array
  5825. {
  5826. try {
  5827. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5828. } catch (\Throwable $e) {
  5829. $cfg = [];
  5830. }
  5831. return is_array($cfg) ? $cfg : [];
  5832. }
  5833. protected function loadNotifyTemplateRow(string $scene): ?array
  5834. {
  5835. try {
  5836. $row = Db::table('purchase_sms_template')
  5837. ->where('scene', $scene)
  5838. ->where(function ($q) {
  5839. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5840. })
  5841. ->order('id', 'asc')
  5842. ->find();
  5843. } catch (\Throwable $e) {
  5844. return null;
  5845. }
  5846. if (!is_array($row) || $row === []) {
  5847. return null;
  5848. }
  5849. return [
  5850. 'title' => trim((string)($row['title'] ?? '')),
  5851. 'content' => trim((string)($row['content'] ?? '')),
  5852. ];
  5853. }
  5854. /**
  5855. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5856. */
  5857. protected function buildProcessLinesHtml(array $mergeRows): string
  5858. {
  5859. if (count($mergeRows) <= 1) {
  5860. $r = $mergeRows[0] ?? [];
  5861. if (!is_array($r)) {
  5862. return '';
  5863. }
  5864. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5865. $dw = trim((string)($r['CDW'] ?? ''));
  5866. $gzl = trim((string)($r['NGZL'] ?? ''));
  5867. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5868. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5869. if ($dw !== '') {
  5870. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5871. }
  5872. if ($gzl !== '') {
  5873. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5874. }
  5875. if ($qty !== '') {
  5876. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5877. }
  5878. return $html;
  5879. }
  5880. $rows = '';
  5881. $i = 1;
  5882. foreach ($mergeRows as $r) {
  5883. if (!is_array($r)) {
  5884. continue;
  5885. }
  5886. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5887. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5888. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5889. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5890. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5891. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5892. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5893. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5894. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5895. $i++;
  5896. }
  5897. if ($rows === '') {
  5898. return '';
  5899. }
  5900. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5901. . '<thead><tr style="background:#f5f5f5;">'
  5902. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5903. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5904. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5905. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5906. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5907. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5908. }
  5909. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  5910. {
  5911. $sysRq = trim($sysRq);
  5912. if ($sysRq === '') {
  5913. if ($required) {
  5914. $this->error('请选择招标截止日期');
  5915. }
  5916. return '';
  5917. }
  5918. $ts = strtotime($sysRq);
  5919. if ($ts === false || $ts <= 0) {
  5920. $this->error('招标截止日期格式无效');
  5921. }
  5922. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  5923. if (!$allowPast) {
  5924. $ymd = date('Y-m-d', $ts);
  5925. if ($ymd < date('Y-m-d')) {
  5926. $this->error('招标截止日期不能早于今天');
  5927. }
  5928. if ($ts <= time()) {
  5929. $this->error('招标截止时间不能早于当前时间');
  5930. }
  5931. }
  5932. return date('Y-m-d H:i:s', $ts);
  5933. }
  5934. /**
  5935. * 确保 purchase_order.czlyq(类型)存在
  5936. */
  5937. protected function ensurePurchaseOrderCzlyqColumn(): void
  5938. {
  5939. static $done = false;
  5940. if ($done) {
  5941. return;
  5942. }
  5943. $done = true;
  5944. try {
  5945. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  5946. if (empty($cols)) {
  5947. Db::execute(
  5948. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  5949. );
  5950. }
  5951. } catch (\Throwable $e) {
  5952. // ignore
  5953. }
  5954. }
  5955. /**
  5956. * 确保 purchase_order.delivery_deadline 存在
  5957. */
  5958. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  5959. {
  5960. static $done = false;
  5961. if ($done) {
  5962. return;
  5963. }
  5964. $done = true;
  5965. try {
  5966. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  5967. if (empty($cols)) {
  5968. Db::execute(
  5969. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  5970. );
  5971. }
  5972. } catch (\Throwable $e) {
  5973. // ignore
  5974. }
  5975. }
  5976. /**
  5977. * 解析交货截止日期(仅年月日)
  5978. */
  5979. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  5980. {
  5981. $raw = trim($raw);
  5982. if ($raw === '') {
  5983. if ($required) {
  5984. $this->error('请选择交货截止日期');
  5985. }
  5986. return '';
  5987. }
  5988. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  5989. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  5990. } else {
  5991. $ts = strtotime(str_replace('/', '-', $raw));
  5992. if ($ts === false || $ts <= 0) {
  5993. $this->error('交货截止日期格式无效');
  5994. }
  5995. $ymd = date('Y-m-d', $ts);
  5996. }
  5997. if ($ymd < date('Y-m-d')) {
  5998. $this->error('交货截止日期不能早于今天');
  5999. }
  6000. return $ymd;
  6001. }
  6002. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  6003. {
  6004. $s = trim((string)$value);
  6005. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  6006. return '';
  6007. }
  6008. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  6009. return $m[1];
  6010. }
  6011. $ts = strtotime(str_replace('/', '-', $s));
  6012. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  6013. }
  6014. /**
  6015. * @param array{pos?:array} $bundle
  6016. */
  6017. protected function resolveBundleDeliveryDeadline(array $bundle): string
  6018. {
  6019. foreach ($bundle['pos'] ?? [] as $po) {
  6020. if (!is_array($po)) {
  6021. continue;
  6022. }
  6023. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  6024. if ($d !== '') {
  6025. return $d;
  6026. }
  6027. }
  6028. return '';
  6029. }
  6030. protected function formatProcuremenSysRqForInput($sysRq): string
  6031. {
  6032. $sr = trim((string)$sysRq);
  6033. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  6034. return '';
  6035. }
  6036. $ts = strtotime($sr);
  6037. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  6038. }
  6039. protected function formatProcuremenSysRqForDisplay($sysRq): string
  6040. {
  6041. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  6042. if ($sr === '') {
  6043. return '—';
  6044. }
  6045. $ts = strtotime($sr);
  6046. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  6047. }
  6048. /**
  6049. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  6050. *
  6051. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  6052. * @return array{ccydh?:string,pos:array,merge_rows:array}
  6053. */
  6054. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  6055. {
  6056. return $bundle;
  6057. }
  6058. /**
  6059. * 写入/更新 purchase_order(单道工序行)
  6060. */
  6061. protected function upsertPurchaseOrderFromRow(
  6062. array $row,
  6063. string $sysRqDb,
  6064. $wflowStatus = null,
  6065. ?string $pickTime = null,
  6066. ?array $exists = null,
  6067. ?string $deliveryDeadline = null
  6068. ): void {
  6069. $ids = $this->extractScydgyRowId($row);
  6070. if (!$this->isValidScydgyRowId($ids)) {
  6071. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  6072. }
  6073. if ($exists === null) {
  6074. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6075. }
  6076. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  6077. $this->ensurePurchaseOrderCzlyqColumn();
  6078. $data = [
  6079. 'scydgy_id' => $ids,
  6080. 'CCYDH' => $row['CCYDH'] ?? null,
  6081. 'CYJMC' => $row['CYJMC'] ?? null,
  6082. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  6083. 'CDXMC' => $row['CDXMC'] ?? null,
  6084. 'CGYBH' => $row['CGYBH'] ?? null,
  6085. 'CGYMC' => $row['CGYMC'] ?? null,
  6086. 'CDW' => $row['CDW'] ?? null,
  6087. 'czlyq' => $row['czlyq'] ?? null,
  6088. 'NGZL' => $row['NGZL'] ?? null,
  6089. 'CDF' => $row['CDF'] ?? null,
  6090. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  6091. 'MBZ' => $row['MBZ'] ?? null,
  6092. 'bwjg' => $row['bwjg'] ?? null,
  6093. 'iStatus' => $row['iStatus'] ?? null,
  6094. 'dStamp' => $row['dStamp'] ?? null,
  6095. 'dputrecord' => $row['dputrecord'] ?? null,
  6096. 'cywyxm' => $row['cywyxm'] ?? null,
  6097. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  6098. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  6099. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6100. 'sys_rq' => $sysRqDb,
  6101. ];
  6102. if ($deliveryDeadline !== null) {
  6103. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  6104. }
  6105. if ($wflowStatus !== null && $wflowStatus !== '') {
  6106. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  6107. }
  6108. if ($pickTime !== null && $pickTime !== '') {
  6109. $data['pick_time'] = $pickTime;
  6110. $data['pick_company_name'] = '';
  6111. }
  6112. if ($exists) {
  6113. $upd = $data;
  6114. unset($upd['scydgy_id']);
  6115. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  6116. } else {
  6117. $data['createtime'] = date('Y-m-d H:i:s');
  6118. Db::table('purchase_order')->insert($data);
  6119. }
  6120. }
  6121. /**
  6122. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  6123. *
  6124. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  6125. */
  6126. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  6127. {
  6128. $toDb = function ($value) {
  6129. if ($value === null) {
  6130. return null;
  6131. }
  6132. if (is_scalar($value)) {
  6133. return $value;
  6134. }
  6135. return json_encode($value, JSON_UNESCAPED_UNICODE);
  6136. };
  6137. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  6138. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  6139. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  6140. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  6141. if ($username === '') {
  6142. $username = $this->resolveCustomerContactName($phone, $companyName);
  6143. }
  6144. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  6145. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  6146. }
  6147. if ($phone === '') {
  6148. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  6149. }
  6150. $detailLinks = [];
  6151. foreach ($mergeRows as $row) {
  6152. if (!is_array($row)) {
  6153. continue;
  6154. }
  6155. $sid = $this->extractScydgyRowId($row);
  6156. $detailId = 0;
  6157. if ($skipExisting) {
  6158. try {
  6159. $existsQuery = Db::table('purchase_order_detail')
  6160. ->where('scydgy_id', $sid)
  6161. ->where('company_name', $companyName);
  6162. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  6163. $exists = $existsQuery->find();
  6164. } catch (\Throwable $e) {
  6165. $exists = null;
  6166. }
  6167. if (is_array($exists)) {
  6168. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  6169. }
  6170. }
  6171. if ($detailId <= 0) {
  6172. $one = [
  6173. 'scydgy_id' => $toDb($sid),
  6174. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  6175. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  6176. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  6177. 'username' => $username !== '' ? $username : null,
  6178. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  6179. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  6180. 'createtime' => date('Y-m-d H:i:s'),
  6181. 'status' => ProcuremenStatus::POD_UNPICKED,
  6182. 'status_name' => '未提交',
  6183. ];
  6184. Db::table('purchase_order_detail')->insert($one);
  6185. $detailId = (int)Db::getLastInsID();
  6186. }
  6187. $mprocUrl = '';
  6188. if ($buildMobileLinks && $detailId > 0) {
  6189. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  6190. }
  6191. $detailLinks[] = [
  6192. 'detail_id' => $detailId,
  6193. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  6194. 'url' => $mprocUrl,
  6195. ];
  6196. }
  6197. return $detailLinks;
  6198. }
  6199. /**
  6200. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  6201. * @return array<string, mixed>
  6202. */
  6203. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  6204. {
  6205. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  6206. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  6207. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  6208. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  6209. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  6210. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  6211. $isMerge = !empty($ctx['is_merge']);
  6212. $contactName = trim((string)($c['username'] ?? ''));
  6213. if ($contactName === '') {
  6214. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  6215. }
  6216. $notifyVars = [
  6217. 'company_name' => $companyName,
  6218. 'contact_name' => $contactName,
  6219. 'phone' => $phone,
  6220. 'email' => $toEmail,
  6221. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  6222. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  6223. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  6224. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  6225. 'deadline' => (string)($ctx['deadline'] ?? ''),
  6226. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  6227. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  6228. 'platform_url' => $platformUrl,
  6229. 'platform_links' => $platformLinksPlain,
  6230. 'platform_links_html' => $platformLinksHtml,
  6231. ];
  6232. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  6233. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  6234. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  6235. return [
  6236. 'company_name' => $companyName,
  6237. 'phone' => $phone,
  6238. 'email' => $toEmail,
  6239. 'sms_content' => $smsContent,
  6240. 'mail_plain' => $mailPlain,
  6241. 'mail_body' => $mailBody,
  6242. 'notify_vars' => $notifyVars,
  6243. 'detail_links' => $detailLinks,
  6244. ];
  6245. }
  6246. /**
  6247. * @param array<string, mixed> $chosen
  6248. * @param array<int, array<string, mixed>> $mergeRows
  6249. * @param array{ccydh:string, pos:array} $bundle
  6250. */
  6251. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  6252. {
  6253. if (!$sendSms && !$sendEmail) {
  6254. return;
  6255. }
  6256. $companyName = trim((string)($chosen['name'] ?? ''));
  6257. $phone = trim((string)($chosen['phone'] ?? ''));
  6258. $toEmail = trim((string)($chosen['email'] ?? ''));
  6259. if ($companyName === '') {
  6260. throw new \Exception('供应商名称无效');
  6261. }
  6262. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  6263. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  6264. }
  6265. if ($sendSms && $phone === '') {
  6266. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  6267. }
  6268. $sids = [];
  6269. foreach ($mergeRows as $mr) {
  6270. if (!is_array($mr)) {
  6271. continue;
  6272. }
  6273. $sid = $this->extractScydgyRowId($mr);
  6274. if ($this->isValidScydgyRowId($sid)) {
  6275. $sids[$sid] = true;
  6276. }
  6277. }
  6278. if ($sids === []) {
  6279. throw new \Exception('未找到工序行,无法发送通知');
  6280. }
  6281. $sysRqNotify = '';
  6282. $pos = $bundle['pos'] ?? [];
  6283. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6284. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  6285. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  6286. $ts = strtotime($sr);
  6287. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  6288. }
  6289. }
  6290. try {
  6291. $detailsQuery = Db::table('purchase_order_detail')
  6292. ->where('scydgy_id', 'in', array_keys($sids))
  6293. ->where('company_name', $companyName);
  6294. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6295. $details = $detailsQuery->order('id', 'asc')->select();
  6296. } catch (\Throwable $e) {
  6297. $details = [];
  6298. }
  6299. if (!is_array($details) || $details === []) {
  6300. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6301. try {
  6302. $detailsQuery = Db::table('purchase_order_detail')
  6303. ->where('scydgy_id', 'in', array_keys($sids))
  6304. ->where('company_name', $companyName);
  6305. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6306. $details = $detailsQuery->order('id', 'asc')->select();
  6307. } catch (\Throwable $e) {
  6308. $details = [];
  6309. }
  6310. }
  6311. if (!is_array($details) || $details === []) {
  6312. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6313. }
  6314. $detailLinks = [];
  6315. foreach ($details as $d) {
  6316. if (!is_array($d)) {
  6317. continue;
  6318. }
  6319. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6320. if ($detailId <= 0) {
  6321. continue;
  6322. }
  6323. $sid = (int)($d['scydgy_id'] ?? 0);
  6324. $gymc = '';
  6325. foreach ($mergeRows as $mr) {
  6326. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6327. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6328. break;
  6329. }
  6330. }
  6331. $detailLinks[] = [
  6332. 'detail_id' => $detailId,
  6333. 'cgymc' => $gymc,
  6334. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6335. ];
  6336. }
  6337. if ($detailLinks === []) {
  6338. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6339. }
  6340. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6341. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6342. $notifyBundle['email_log_scene'] = $emailLogScene;
  6343. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6344. $poIdLog = 0;
  6345. $pos = $bundle['pos'] ?? [];
  6346. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6347. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6348. }
  6349. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6350. if ($sendEmail) {
  6351. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6352. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6353. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6354. }
  6355. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6356. $mailConfig = $this->loadMailerConfig();
  6357. if (!$this->isProcuremenNotifyDryRun()) {
  6358. if (empty($mailConfig['host'])) {
  6359. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6360. }
  6361. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6362. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6363. }
  6364. }
  6365. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6366. }
  6367. if ($sendSms) {
  6368. $this->issueSendSupplierSms($notifyBundle);
  6369. }
  6370. }
  6371. /**
  6372. * @param array<int, array<string, mixed>> $quoteGroups
  6373. * @return array<int, array<string, mixed>>
  6374. */
  6375. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6376. {
  6377. $names = [];
  6378. if (is_string($companiesJson) && $companiesJson !== '') {
  6379. $decoded = json_decode($companiesJson, true);
  6380. if (is_array($decoded)) {
  6381. foreach ($decoded as $nm) {
  6382. $nm = trim((string)$nm);
  6383. if ($nm !== '') {
  6384. $names[] = $nm;
  6385. }
  6386. }
  6387. }
  6388. }
  6389. $names = array_values(array_unique($names));
  6390. if ($names === [] && $selectedCompany !== '') {
  6391. $names = [$selectedCompany];
  6392. }
  6393. if ($names === []) {
  6394. return $quoteGroups;
  6395. }
  6396. $targets = [];
  6397. foreach ($quoteGroups as $g) {
  6398. if (!is_array($g)) {
  6399. continue;
  6400. }
  6401. $cn = trim((string)($g['name'] ?? ''));
  6402. if ($cn !== '' && in_array($cn, $names, true)) {
  6403. $targets[] = $g;
  6404. }
  6405. }
  6406. return $targets;
  6407. }
  6408. /**
  6409. * @return array{pos:array, merge_rows:array, bundle:array}
  6410. */
  6411. protected function loadAuditResendBundle(string $scydgyId): array
  6412. {
  6413. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6414. $pos = $bundle['pos'];
  6415. $mergeRows = $bundle['merge_rows'];
  6416. if ($pos === [] || $mergeRows === []) {
  6417. $this->error('该订单不在待确认供应商状态');
  6418. }
  6419. $sysRqDb = '';
  6420. if (isset($pos[0]) && is_array($pos[0])) {
  6421. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6422. }
  6423. foreach ($pos as $i => $poRow) {
  6424. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6425. $pos[$i]['sys_rq'] = $sysRqDb;
  6426. }
  6427. }
  6428. $bundle['pos'] = $pos;
  6429. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6430. }
  6431. /**
  6432. * @param array<int, array<string, mixed>> $targets
  6433. */
  6434. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6435. {
  6436. if ($targets === []) {
  6437. $this->error('未找到可通知的供应商');
  6438. }
  6439. $notifyErrors = [];
  6440. try {
  6441. $this->notifyDryRunPreview = [];
  6442. foreach ($targets as $g) {
  6443. if (!is_array($g)) {
  6444. continue;
  6445. }
  6446. $cname = trim((string)($g['name'] ?? ''));
  6447. if ($cname === '') {
  6448. continue;
  6449. }
  6450. $chosen = [
  6451. 'name' => $cname,
  6452. 'company_name' => $cname,
  6453. 'email' => trim((string)($g['email'] ?? '')),
  6454. 'phone' => trim((string)($g['phone'] ?? '')),
  6455. 'username' => trim((string)($g['username'] ?? '')),
  6456. ];
  6457. try {
  6458. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6459. } catch (\Throwable $e) {
  6460. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6461. }
  6462. }
  6463. } catch (\Throwable $e) {
  6464. $this->error('通知发送失败:' . $e->getMessage());
  6465. }
  6466. if ($notifyErrors !== []) {
  6467. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6468. }
  6469. if ($this->isProcuremenNotifyDryRun()) {
  6470. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6471. 'notify_dry_run' => true,
  6472. 'notify_preview' => $this->notifyDryRunPreview,
  6473. ]);
  6474. }
  6475. $nameLabels = [];
  6476. foreach ($targets as $g) {
  6477. if (!is_array($g)) {
  6478. continue;
  6479. }
  6480. $n = trim((string)($g['name'] ?? ''));
  6481. if ($n !== '') {
  6482. $nameLabels[] = $n;
  6483. }
  6484. }
  6485. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6486. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6487. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6488. $seenLogSid = [];
  6489. foreach ($bundle['pos'] ?? [] as $poRow) {
  6490. if (!is_array($poRow)) {
  6491. continue;
  6492. }
  6493. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6494. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6495. continue;
  6496. }
  6497. $seenLogSid[$sid] = true;
  6498. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6499. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6500. }
  6501. if ($seenLogSid === []) {
  6502. foreach ($mergeRows as $mr) {
  6503. if (!is_array($mr)) {
  6504. continue;
  6505. }
  6506. $sid = $this->extractScydgyRowId($mr);
  6507. if ($this->isValidScydgyRowId($sid)) {
  6508. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6509. break;
  6510. }
  6511. }
  6512. }
  6513. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6514. }
  6515. /**
  6516. * 协助下发 — 发送短信(一家供应商)
  6517. *
  6518. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6519. */
  6520. protected function issueSendSupplierSms(array $bundle): void
  6521. {
  6522. $companyName = (string)($bundle['company_name'] ?? '');
  6523. $phone = (string)($bundle['phone'] ?? '');
  6524. $smsContent = (string)($bundle['sms_content'] ?? '');
  6525. $this->logIssueNotifyDebug('短信', [
  6526. 'company' => $companyName,
  6527. 'phone' => $phone,
  6528. 'sms_content' => $smsContent,
  6529. ]);
  6530. if ($this->isProcuremenNotifyDryRun()) {
  6531. $this->recordNotifyDryRunPreview([
  6532. 'scene' => 'issue_sms',
  6533. 'company_name' => $companyName,
  6534. 'phone' => $phone,
  6535. 'sms_content' => $smsContent,
  6536. ]);
  6537. return;
  6538. }
  6539. $this->smsbao($phone, $smsContent);
  6540. }
  6541. /**
  6542. * 协助下发 — 发送邮件(一家供应商)
  6543. *
  6544. * @param array<string, mixed> $bundle
  6545. * @param array<string, mixed> $mailConfig
  6546. */
  6547. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6548. {
  6549. $companyName = (string)($bundle['company_name'] ?? '');
  6550. $toEmail = (string)($bundle['email'] ?? '');
  6551. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6552. $mailBody = (string)($bundle['mail_body'] ?? '');
  6553. $this->logIssueNotifyDebug('邮件', [
  6554. 'company' => $companyName,
  6555. 'email' => $toEmail,
  6556. 'mail_subject' => $mailSubject,
  6557. 'mail_body' => $mailPlain,
  6558. ]);
  6559. if ($this->isProcuremenNotifyDryRun()) {
  6560. $this->recordNotifyDryRunPreview([
  6561. 'scene' => 'issue_email',
  6562. 'company_name' => $companyName,
  6563. 'email' => $toEmail,
  6564. 'mail_subject' => $mailSubject,
  6565. 'mail_body' => $mailPlain,
  6566. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6567. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6568. 'detail_links' => $bundle['detail_links'] ?? [],
  6569. ]);
  6570. return;
  6571. }
  6572. $mail = new PHPMailer(true);
  6573. $mail->isSMTP();
  6574. $mail->Host = $mailConfig['host'];
  6575. $mail->SMTPAuth = true;
  6576. $mail->Username = $mailConfig['addr'];
  6577. $mail->Password = $mailConfig['pass'];
  6578. $mail->SMTPSecure = $mailConfig['security'];
  6579. $mail->Port = $mailConfig['port'];
  6580. $mail->CharSet = $mailConfig['charset'];
  6581. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6582. $mail->addAddress($toEmail, $companyName);
  6583. $mail->isHTML(true);
  6584. $mail->Subject = $mailSubject;
  6585. $mail->Body = $mailBody;
  6586. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6587. $sendOk = true;
  6588. $failReason = '';
  6589. try {
  6590. $mail->send();
  6591. } catch (\Throwable $e) {
  6592. $sendOk = false;
  6593. $failReason = $e->getMessage();
  6594. $this->persistEmailSendLog([
  6595. 'from_email' => $fromEmail,
  6596. 'to_email' => $toEmail,
  6597. 'send_time' => date('Y-m-d H:i:s'),
  6598. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6599. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6600. 'company_name' => $companyName,
  6601. 'mail_subject' => $mailSubject,
  6602. 'status' => 0,
  6603. 'fail_reason' => $failReason,
  6604. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6605. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6606. ]);
  6607. throw $e;
  6608. }
  6609. $this->persistEmailSendLog([
  6610. 'from_email' => $fromEmail,
  6611. 'to_email' => $toEmail,
  6612. 'send_time' => date('Y-m-d H:i:s'),
  6613. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6614. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6615. 'company_name' => $companyName,
  6616. 'mail_subject' => $mailSubject,
  6617. 'status' => 1,
  6618. 'fail_reason' => '',
  6619. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6620. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6621. ]);
  6622. }
  6623. /**
  6624. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6625. *
  6626. * @param array<int, array<string, mixed>> $mergeRows
  6627. * @return array<string, mixed>
  6628. */
  6629. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6630. {
  6631. $head = $mergeRows[0] ?? [];
  6632. $isMerge = count($mergeRows) > 1;
  6633. return [
  6634. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6635. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6636. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6637. 'is_merge' => $isMerge,
  6638. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6639. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6640. 'deadline' => $sysRqNotify,
  6641. ];
  6642. }
  6643. /**
  6644. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6645. *
  6646. * @param array<string, mixed> $data
  6647. */
  6648. protected function logIssueNotifyDebug(string $type, array $data): void
  6649. {
  6650. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6651. return;
  6652. }
  6653. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6654. }
  6655. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6656. {
  6657. try {
  6658. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6659. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6660. return;
  6661. } catch (\Throwable $e) {
  6662. }
  6663. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6664. if (is_file($sqlFile)) {
  6665. $sql = file_get_contents($sqlFile);
  6666. if (is_string($sql) && $sql !== '') {
  6667. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6668. $stmt = trim($stmt);
  6669. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6670. continue;
  6671. }
  6672. try {
  6673. Db::execute($stmt);
  6674. } catch (\Throwable $ignore) {
  6675. }
  6676. }
  6677. }
  6678. }
  6679. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6680. }
  6681. /**
  6682. * @param array<string, mixed> $row
  6683. */
  6684. protected function persistEmailSendLog(array $row): void
  6685. {
  6686. try {
  6687. $this->ensurePurchaseEmailSendLogTableOnce();
  6688. } catch (\Throwable $e) {
  6689. return;
  6690. }
  6691. list($adminId, $adminName) = $this->GetUseName();
  6692. $cut = function ($s, $max) {
  6693. $s = (string)$s;
  6694. if (function_exists('mb_substr')) {
  6695. return mb_substr($s, 0, $max, 'UTF-8');
  6696. }
  6697. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6698. };
  6699. $data = [
  6700. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6701. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6702. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6703. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6704. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6705. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6706. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6707. 'status' => !empty($row['status']) ? 1 : 0,
  6708. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6709. 'admin_id' => (int)$adminId,
  6710. 'admin_name' => $cut($adminName, 64),
  6711. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6712. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6713. 'createtime' => date('Y-m-d H:i:s'),
  6714. ];
  6715. try {
  6716. Db::table('purchase_email_send_log')->insert($data);
  6717. } catch (\Throwable $e) {
  6718. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6719. }
  6720. }
  6721. protected function formatEmailLogSceneText(string $scene): string
  6722. {
  6723. $map = [
  6724. 'pick_issue' => '初选下发',
  6725. 'audit_resend' => '确认页重发',
  6726. ];
  6727. return $map[$scene] ?? $scene;
  6728. }
  6729. /**
  6730. * 邮件发送日志列表
  6731. */
  6732. public function emailLog()
  6733. {
  6734. $this->relationSearch = false;
  6735. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6736. $this->request->filter(['strip_tags', 'trim']);
  6737. $bakModel = $this->model;
  6738. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6739. if ($this->request->isAjax()) {
  6740. $this->ensurePurchaseEmailSendLogTableOnce();
  6741. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6742. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6743. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6744. $list = $this->model
  6745. ->where($where)
  6746. ->order($sortField, $orderDir)
  6747. ->paginate($limit);
  6748. $rows = [];
  6749. foreach ($list->items() as $item) {
  6750. $row = is_array($item) ? $item : $item->toArray();
  6751. $scene = trim((string)($row['scene'] ?? ''));
  6752. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6753. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6754. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6755. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6756. $rows[] = $row;
  6757. }
  6758. $this->model = $bakModel;
  6759. return json(['total' => $list->total(), 'rows' => $rows]);
  6760. }
  6761. $this->model = $bakModel;
  6762. return $this->view->fetch('procuremen/emaillog');
  6763. }
  6764. /**
  6765. * 协助下发弹窗(选多家供应商并通知)
  6766. */
  6767. public function pickReview()
  6768. {
  6769. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6770. $this->error(__('You have no permission'));
  6771. }
  6772. if ($this->request->isPost()) {
  6773. $this->error('请使用弹窗内「确认下发」提交');
  6774. }
  6775. $this->view->assign('pickMode', 1);
  6776. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6777. }
  6778. /**
  6779. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6780. */
  6781. public function add()
  6782. {
  6783. if ($this->request->isPost()) {
  6784. $params = $this->request->post('row/a');
  6785. if (!is_array($params)) {
  6786. $this->error(__('Parameter %s can not be empty', ''));
  6787. }
  6788. [, $adminName] = $this->GetUseName();
  6789. $params['cywyxm'] = $adminName;
  6790. try {
  6791. $sid = $this->saveManualPickOrder($params);
  6792. } catch (\InvalidArgumentException $e) {
  6793. $this->error($e->getMessage());
  6794. } catch (\Throwable $e) {
  6795. $this->error($e->getMessage());
  6796. }
  6797. $this->success('新增成功', '', [
  6798. 'scydgy_id' => $sid,
  6799. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6800. ]);
  6801. }
  6802. [, $adminName] = $this->GetUseName();
  6803. $this->view->assign('adminNickname', $adminName);
  6804. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6805. $this->view->assign('defaultCclbmmc', '营销中心');
  6806. return $this->view->fetch();
  6807. }
  6808. /**
  6809. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6810. */
  6811. public function rfqlist()
  6812. {
  6813. $this->relationSearch = false;
  6814. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6815. $this->request->filter(['strip_tags', 'trim']);
  6816. if ($this->request->isAjax()) {
  6817. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6818. $limit = max(10, min(500, (int)$limit));
  6819. $applyFilters = function ($query) use ($where) {
  6820. $query->where('scydgy_id', '<', 0);
  6821. $query->whereRaw(
  6822. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6823. );
  6824. if (!$this->auth->isSuperAdmin()) {
  6825. [, $adminName] = $this->GetUseName();
  6826. $query->where('cywyxm', $adminName);
  6827. }
  6828. if (!empty($where)) {
  6829. $query->where($where);
  6830. }
  6831. };
  6832. $countQuery = Db::table('purchase_order');
  6833. $applyFilters($countQuery);
  6834. $total = (int)$countQuery->count();
  6835. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6836. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6837. $listQuery = Db::table('purchase_order');
  6838. $applyFilters($listQuery);
  6839. $rows = $listQuery
  6840. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6841. ->order($sortField, $orderDir)
  6842. ->limit($offset, $limit)
  6843. ->select();
  6844. if (!is_array($rows)) {
  6845. $rows = [];
  6846. }
  6847. $out = [];
  6848. foreach ($rows as $r) {
  6849. if (!is_array($r)) {
  6850. continue;
  6851. }
  6852. $sid = (int)($r['scydgy_id'] ?? 0);
  6853. if ($sid >= 0) {
  6854. continue;
  6855. }
  6856. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6857. if ($createdText === '') {
  6858. $createdText = trim((string)($r['dStamp'] ?? ''));
  6859. }
  6860. $out[] = [
  6861. 'id' => (int)($r['id'] ?? 0),
  6862. 'scydgy_id' => $sid,
  6863. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6864. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6865. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6866. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6867. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6868. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6869. 'createtime' => $r['createtime'] ?? null,
  6870. 'createtime_text' => $createdText,
  6871. ];
  6872. }
  6873. return json(['total' => $total, 'rows' => $out]);
  6874. }
  6875. [, $adminName] = $this->GetUseName();
  6876. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6877. $this->view->assign('adminNickname', $adminName);
  6878. return $this->view->fetch('procuremen/rfqlist');
  6879. }
  6880. /**
  6881. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6882. */
  6883. public function rfqlistDetails()
  6884. {
  6885. return $this->details();
  6886. }
  6887. /**
  6888. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6889. */
  6890. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6891. {
  6892. if ($scydgyId >= 0) {
  6893. return;
  6894. }
  6895. try {
  6896. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6897. } catch (\Throwable $e) {
  6898. $po = null;
  6899. }
  6900. if (!is_array($po)) {
  6901. $this->error('订单不存在');
  6902. }
  6903. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6904. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6905. $this->error('订单不存在');
  6906. }
  6907. if ($this->auth->isSuperAdmin()) {
  6908. return;
  6909. }
  6910. [, $adminName] = $this->GetUseName();
  6911. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6912. if ($cywy !== '' && $cywy === $adminName) {
  6913. return;
  6914. }
  6915. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6916. try {
  6917. if ($this->auth->check($rule)) {
  6918. return;
  6919. }
  6920. } catch (\Throwable $e) {
  6921. }
  6922. }
  6923. $this->error('无权查看该订单');
  6924. }
  6925. /**
  6926. * 手工新增协助工序进度文案
  6927. */
  6928. protected function formatProcuremenRfqProgressText(array $row): string
  6929. {
  6930. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6931. return ProcuremenStatus::PO_COMPLETED;
  6932. }
  6933. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6934. return '待采购确认';
  6935. }
  6936. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6937. return '待确认供应商';
  6938. }
  6939. $sid = (int)($row['scydgy_id'] ?? 0);
  6940. if ($sid < 0) {
  6941. try {
  6942. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6943. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6944. $detCnt = (int)$detCntQuery->count();
  6945. if ($detCnt > 0) {
  6946. return '已下发待确认';
  6947. }
  6948. } catch (\Throwable $e) {
  6949. }
  6950. }
  6951. return '待协助下发';
  6952. }
  6953. /**
  6954. * 协助初选列表 — 批量软删除
  6955. */
  6956. public function pickDelete()
  6957. {
  6958. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6959. $this->error(__('Invalid parameters'));
  6960. }
  6961. if (!$this->procuremenCanPickDelete()) {
  6962. $this->error(__('You have no permission'));
  6963. }
  6964. $rowsRaw = $this->request->post('rows_json', '[]');
  6965. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6966. if (!is_array($rows) || $rows === []) {
  6967. $this->error('请至少勾选一条工序');
  6968. }
  6969. $done = 0;
  6970. Db::startTrans();
  6971. try {
  6972. foreach ($rows as $row) {
  6973. if (!is_array($row)) {
  6974. continue;
  6975. }
  6976. $this->softDeleteProcuremenPickRow($row);
  6977. $done++;
  6978. }
  6979. if ($done < 1) {
  6980. throw new \Exception('没有可删除的工序');
  6981. }
  6982. Db::commit();
  6983. } catch (\InvalidArgumentException $e) {
  6984. Db::rollback();
  6985. $this->error($e->getMessage());
  6986. } catch (\Throwable $e) {
  6987. Db::rollback();
  6988. $this->error($e->getMessage());
  6989. }
  6990. $this->pickHiddenScydgySetCache = null;
  6991. $this->success('已删除 ' . $done . ' 条工序');
  6992. }
  6993. /**
  6994. * 下发 — 手工新增工序(弹窗)
  6995. */
  6996. public function pickAdd()
  6997. {
  6998. if ($this->request->isPost()) {
  6999. $params = $this->request->post('row/a');
  7000. if (!is_array($params)) {
  7001. $this->error(__('Parameter %s can not be empty', ''));
  7002. }
  7003. try {
  7004. $sid = $this->saveManualPickOrder($params);
  7005. } catch (\InvalidArgumentException $e) {
  7006. $this->error($e->getMessage());
  7007. } catch (\Throwable $e) {
  7008. $this->error($e->getMessage());
  7009. }
  7010. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  7011. }
  7012. return $this->view->fetch('procuremen/pick_add');
  7013. }
  7014. /**
  7015. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  7016. */
  7017. public function pickSubmit()
  7018. {
  7019. if (!$this->request->isPost()) {
  7020. $this->error(__('Invalid parameters'));
  7021. }
  7022. // ---------- 接口订单数据 ----------
  7023. $rowJson = $this->request->post('row_json', '');
  7024. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  7025. $companiesJson = $this->request->post('companies_json', '[]');
  7026. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  7027. $companies = json_decode($companiesJson, true);
  7028. if (!is_array($companies)) {
  7029. $this->error('供应商数据无效');
  7030. }
  7031. $issueCompanies = $this->normalizePickCompanies($companies);
  7032. if ($issueCompanies === []) {
  7033. $this->error('请至少选择一家合作供应商');
  7034. }
  7035. $issueNameLabels = [];
  7036. foreach ($issueCompanies as $pc) {
  7037. $issueNameLabels[] = $pc['name'];
  7038. }
  7039. $issueNamesSummary = implode('、', $issueNameLabels);
  7040. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  7041. if ($sysRq === '') {
  7042. $this->error('请选择招标截止日期');
  7043. }
  7044. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  7045. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  7046. (string)$this->request->post('delivery_deadline', ''),
  7047. true
  7048. );
  7049. $isMerge = count($mergeRows) > 1;
  7050. $ccydhLog = '';
  7051. foreach ($mergeRows as $row) {
  7052. if (!is_array($row)) {
  7053. continue;
  7054. }
  7055. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  7056. if ($ccydhLog !== '') {
  7057. break;
  7058. }
  7059. }
  7060. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  7061. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7062. $logMsg = '下发' . $orderPart . $procPart
  7063. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  7064. $issueTime = date('Y-m-d H:i:s');
  7065. $logSidList = [];
  7066. foreach ($mergeRows as $row) {
  7067. if (!is_array($row)) {
  7068. continue;
  7069. }
  7070. $sid = $this->extractScydgyRowId($row);
  7071. if ($this->isValidScydgyRowId($sid)) {
  7072. $logSidList[$sid] = true;
  7073. }
  7074. }
  7075. $existingBySid = [];
  7076. if ($logSidList !== []) {
  7077. try {
  7078. $existingRows = Db::table('purchase_order')
  7079. ->where('scydgy_id', 'in', array_keys($logSidList))
  7080. ->select();
  7081. if (is_array($existingRows)) {
  7082. foreach ($existingRows as $poRow) {
  7083. if (!is_array($poRow)) {
  7084. continue;
  7085. }
  7086. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7087. if ($this->isValidScydgyRowId($sid)) {
  7088. $existingBySid[$sid] = $poRow;
  7089. }
  7090. }
  7091. }
  7092. } catch (\Throwable $e) {
  7093. $existingBySid = [];
  7094. }
  7095. }
  7096. Db::startTrans();
  7097. try {
  7098. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  7099. foreach ($mergeRows as $row) {
  7100. if (!is_array($row)) {
  7101. continue;
  7102. }
  7103. $sid = $this->extractScydgyRowId($row);
  7104. $this->upsertPurchaseOrderFromRow(
  7105. $row,
  7106. $sysRqDb,
  7107. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7108. $issueTime,
  7109. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  7110. $deliveryDeadlineDb
  7111. );
  7112. }
  7113. foreach ($issueCompanies as $c) {
  7114. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7115. }
  7116. Db::commit();
  7117. } catch (\Throwable $e) {
  7118. Db::rollback();
  7119. $this->error($e->getMessage());
  7120. }
  7121. $poIdBySid = [];
  7122. if ($logSidList !== []) {
  7123. try {
  7124. $poIdBySid = Db::table('purchase_order')
  7125. ->where('scydgy_id', 'in', array_keys($logSidList))
  7126. ->column('id', 'scydgy_id');
  7127. } catch (\Throwable $e) {
  7128. $poIdBySid = [];
  7129. }
  7130. }
  7131. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  7132. if ($logSidList !== []) {
  7133. list($adminId, $adminName) = $this->GetUseName();
  7134. $logRows = [];
  7135. $seenLogSid = [];
  7136. foreach ($mergeRows as $row) {
  7137. if (!is_array($row)) {
  7138. continue;
  7139. }
  7140. $ids = $this->extractScydgyRowId($row);
  7141. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  7142. continue;
  7143. }
  7144. $seenLogSid[$ids] = true;
  7145. $poIdLog = null;
  7146. if (isset($poIdBySid[$ids])) {
  7147. $tid = (int)$poIdBySid[$ids];
  7148. $poIdLog = $tid > 0 ? $tid : null;
  7149. }
  7150. $logRows[] = ProcuremenOperLog::buildInsertRow(
  7151. $ids,
  7152. 'issue_submit',
  7153. $logMsg,
  7154. $poIdLog,
  7155. (int)$adminId,
  7156. (string)$adminName
  7157. );
  7158. }
  7159. if ($logRows !== []) {
  7160. try {
  7161. Db::table('purchase_order_oper_log')->insertAll($logRows);
  7162. } catch (\Throwable $e) {
  7163. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  7164. }
  7165. }
  7166. }
  7167. $notifyErrors = [];
  7168. $posNotify = [];
  7169. if ($logSidList !== []) {
  7170. try {
  7171. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  7172. } catch (\Throwable $e) {
  7173. $posNotify = [];
  7174. }
  7175. }
  7176. if (!is_array($posNotify)) {
  7177. $posNotify = [];
  7178. }
  7179. foreach ($posNotify as $i => $prow) {
  7180. if (is_array($posNotify[$i])) {
  7181. $posNotify[$i]['sys_rq'] = $sysRqDb;
  7182. }
  7183. }
  7184. $ccydhPick = '';
  7185. foreach ($mergeRows as $row) {
  7186. if (!is_array($row)) {
  7187. continue;
  7188. }
  7189. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  7190. if ($ccydhPick !== '') {
  7191. break;
  7192. }
  7193. }
  7194. $notifyBundleBase = [
  7195. 'ccydh' => $ccydhPick,
  7196. 'pos' => $posNotify,
  7197. 'merge_rows' => $mergeRows,
  7198. ];
  7199. try {
  7200. $this->notifyDryRunPreview = [];
  7201. foreach ($issueCompanies as $c) {
  7202. if (!is_array($c)) {
  7203. continue;
  7204. }
  7205. $cname = trim((string)($c['name'] ?? ''));
  7206. if ($cname === '') {
  7207. continue;
  7208. }
  7209. try {
  7210. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  7211. } catch (\Throwable $e) {
  7212. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7213. }
  7214. }
  7215. } catch (\Throwable $e) {
  7216. $this->error('通知发送失败:' . $e->getMessage());
  7217. }
  7218. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7219. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7220. }
  7221. if ($this->isProcuremenNotifyDryRun()) {
  7222. $this->success('【演练模式】已保存并生成通知预览', '', [
  7223. 'notify_dry_run' => true,
  7224. 'notify_preview' => $this->notifyDryRunPreview,
  7225. ]);
  7226. }
  7227. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  7228. }
  7229. /**
  7230. * 确认供应商弹窗
  7231. */
  7232. public function auditIssue()
  7233. {
  7234. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7235. if (is_array($ids)) {
  7236. $ids = isset($ids[0]) ? $ids[0] : '';
  7237. }
  7238. $ids = trim((string)$ids);
  7239. if ($ids === '') {
  7240. $this->error(__('Invalid parameters'));
  7241. }
  7242. if ($this->request->isPost()) {
  7243. $this->error('请使用弹窗内「确认」提交');
  7244. }
  7245. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7246. $pos = $bundle['pos'];
  7247. if ($pos === []) {
  7248. $this->error('该订单不在待确认供应商状态');
  7249. }
  7250. $po = $pos[0];
  7251. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7252. if ($quoteGroups === []) {
  7253. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  7254. }
  7255. $pickedName = '';
  7256. foreach ($pos as $poRow) {
  7257. if (!is_array($poRow)) {
  7258. continue;
  7259. }
  7260. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7261. if ($pn !== '') {
  7262. $pickedName = $pn;
  7263. break;
  7264. }
  7265. }
  7266. $this->view->assign('po', $po);
  7267. $this->view->assign('scydgyId', $ids);
  7268. $this->view->assign('orderCcydh', $bundle['ccydh']);
  7269. $mergeRows = $bundle['merge_rows'];
  7270. $this->view->assign('processRows', $mergeRows);
  7271. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  7272. $this->view->assign('processCount', count($mergeRows));
  7273. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  7274. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  7275. $this->view->assign('pickedCompanyName', $pickedName);
  7276. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7277. if ($sysRqForView === '') {
  7278. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7279. }
  7280. $this->view->assign('sysRq', $sysRqForView);
  7281. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  7282. if ($deliveryDeadlineForView === '') {
  7283. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7284. }
  7285. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7286. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  7287. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups));
  7288. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups) ? 1 : 0);
  7289. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  7290. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  7291. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  7292. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  7293. return $this->view->fetch('procuremen/audit_issue');
  7294. }
  7295. /**
  7296. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7297. *
  7298. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7299. */
  7300. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7301. {
  7302. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7303. }
  7304. /**
  7305. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7306. *
  7307. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7308. */
  7309. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7310. {
  7311. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7312. return false;
  7313. }
  7314. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7315. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7316. return true;
  7317. }
  7318. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7319. }
  7320. /**
  7321. * 确认页 — 补加供应商弹窗
  7322. */
  7323. public function auditAppend()
  7324. {
  7325. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7326. $this->error(__('You have no permission'));
  7327. }
  7328. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7329. if (is_array($ids)) {
  7330. $ids = isset($ids[0]) ? $ids[0] : '';
  7331. }
  7332. $ids = trim((string)$ids);
  7333. if ($ids === '') {
  7334. $this->error(__('Invalid parameters'));
  7335. }
  7336. if ($this->request->isPost()) {
  7337. $this->error('请使用弹窗内「确认」提交');
  7338. }
  7339. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7340. if (($bundle['pos'] ?? []) === []) {
  7341. $this->error('该订单不在待确认供应商状态');
  7342. }
  7343. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7344. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7345. $this->error('已开标验证,不能再补加供应商');
  7346. }
  7347. $this->error('已经超过了招标截止日期,不可操作');
  7348. }
  7349. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7350. $existingNames = [];
  7351. foreach ($quoteGroups as $g) {
  7352. if (!is_array($g)) {
  7353. continue;
  7354. }
  7355. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7356. if ($n !== '') {
  7357. $existingNames[$n] = true;
  7358. }
  7359. }
  7360. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7361. $mergeRows = $bundle['merge_rows'] ?? [];
  7362. $this->view->assign('scydgyId', $ids);
  7363. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7364. $this->view->assign('po', $po);
  7365. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7366. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7367. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7368. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7369. if ($sysRqForView === '') {
  7370. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7371. }
  7372. $this->view->assign('sysRq', $sysRqForView);
  7373. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7374. if ($deliveryDeadlineForView === '') {
  7375. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7376. }
  7377. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7378. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7379. }
  7380. /**
  7381. * 确认页 — 补加供应商提交
  7382. */
  7383. public function auditAppendSubmit()
  7384. {
  7385. if (!$this->request->isPost()) {
  7386. $this->error(__('Invalid parameters'));
  7387. }
  7388. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7389. $this->error(__('You have no permission'));
  7390. }
  7391. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7392. if ($ids === '') {
  7393. $this->error(__('Invalid parameters'));
  7394. }
  7395. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7396. if (($bundle['pos'] ?? []) === []) {
  7397. $this->error('该订单不在待确认供应商状态');
  7398. }
  7399. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7400. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7401. $this->error('已开标验证,不能再补加供应商');
  7402. }
  7403. $this->error('已经超过了招标截止日期,不可操作');
  7404. }
  7405. $companiesJson = $this->request->post('companies_json', '[]');
  7406. $companies = json_decode((string)$companiesJson, true);
  7407. if (!is_array($companies)) {
  7408. $this->error('供应商数据无效');
  7409. }
  7410. $issueCompanies = $this->normalizePickCompanies($companies);
  7411. if ($issueCompanies === []) {
  7412. $this->error('请至少选择一家合作供应商');
  7413. }
  7414. $mergeRows = $bundle['merge_rows'] ?? [];
  7415. if (!is_array($mergeRows) || $mergeRows === []) {
  7416. $this->error('未找到工序行,无法补加');
  7417. }
  7418. $existingNames = [];
  7419. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7420. if (!is_array($g)) {
  7421. continue;
  7422. }
  7423. $n = trim((string)($g['company_name'] ?? ''));
  7424. if ($n !== '') {
  7425. $existingNames[$n] = true;
  7426. }
  7427. }
  7428. $toAdd = [];
  7429. foreach ($issueCompanies as $c) {
  7430. if (!is_array($c)) {
  7431. continue;
  7432. }
  7433. $n = trim((string)($c['name'] ?? ''));
  7434. if ($n === '' || isset($existingNames[$n])) {
  7435. continue;
  7436. }
  7437. $toAdd[] = $c;
  7438. }
  7439. if ($toAdd === []) {
  7440. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7441. }
  7442. $addedNames = [];
  7443. Db::startTrans();
  7444. try {
  7445. foreach ($toAdd as $c) {
  7446. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7447. $addedNames[] = trim((string)($c['name'] ?? ''));
  7448. }
  7449. Db::commit();
  7450. } catch (\Throwable $e) {
  7451. Db::rollback();
  7452. $this->error($e->getMessage());
  7453. }
  7454. $notifyErrors = [];
  7455. $notifyBundleBase = [
  7456. 'ccydh' => $bundle['ccydh'] ?? '',
  7457. 'pos' => $bundle['pos'] ?? [],
  7458. 'merge_rows' => $mergeRows,
  7459. ];
  7460. foreach ($toAdd as $c) {
  7461. if (!is_array($c)) {
  7462. continue;
  7463. }
  7464. $cname = trim((string)($c['name'] ?? ''));
  7465. if ($cname === '') {
  7466. continue;
  7467. }
  7468. try {
  7469. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7470. } catch (\Throwable $e) {
  7471. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7472. }
  7473. }
  7474. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7475. $seenLogSid = [];
  7476. foreach ($bundle['pos'] ?? [] as $poRow) {
  7477. if (!is_array($poRow)) {
  7478. continue;
  7479. }
  7480. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7481. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7482. continue;
  7483. }
  7484. $seenLogSid[$sid] = true;
  7485. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7486. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7487. }
  7488. if ($seenLogSid === []) {
  7489. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7490. if ($this->isValidScydgyRowId($logSid)) {
  7491. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7492. }
  7493. }
  7494. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7495. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7496. }
  7497. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7498. }
  7499. /**
  7500. * 开标双重验证 — 可选验证人列表
  7501. */
  7502. public function bidOpenUsers()
  7503. {
  7504. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7505. $this->error('无权限');
  7506. }
  7507. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7508. if ($scydgyId !== '') {
  7509. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7510. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7511. $this->success('已完成开标验证', null, [
  7512. 'verified' => 1,
  7513. 'users' => [],
  7514. ]);
  7515. }
  7516. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7517. }
  7518. $this->success('', null, [
  7519. 'verified' => 0,
  7520. 'users' => $this->listBidOpenVerifierCandidates(),
  7521. ]);
  7522. }
  7523. /**
  7524. * 开标双重验证 — 向指定管理员发送短信验证码
  7525. */
  7526. public function bidOpenSendCode()
  7527. {
  7528. if (!$this->request->isPost()) {
  7529. $this->error(__('Invalid parameters'));
  7530. }
  7531. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7532. $this->error('无权限');
  7533. }
  7534. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7535. $adminId = (int)$this->request->post('admin_id', 0);
  7536. if ($scydgyId === '' || $adminId <= 0) {
  7537. $this->error('参数无效');
  7538. }
  7539. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7540. if ($bundle['pos'] === []) {
  7541. $this->error('该订单不在待确认供应商状态');
  7542. }
  7543. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7544. $this->success('已完成开标验证,无需重复发送');
  7545. }
  7546. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7547. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7548. if ($ccydh === '') {
  7549. $this->error('订单号无效');
  7550. }
  7551. $admin = $this->loadBidOpenAdminUser($adminId);
  7552. if ($admin === null) {
  7553. $this->error('验证人无效或未绑定手机号');
  7554. }
  7555. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7556. $cd = max(30, min(120, $cd));
  7557. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7558. $this->error('发送过于频繁,请稍后再试');
  7559. }
  7560. $code = (string)random_int(100000, 999999);
  7561. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7562. $ttl = max(60, min(600, $ttl));
  7563. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7564. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7565. try {
  7566. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7567. } catch (\Throwable $e) {
  7568. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7569. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7570. $this->error($e->getMessage());
  7571. }
  7572. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7573. }
  7574. /**
  7575. * 开标双重验证 — 两人验证码校验并记录
  7576. */
  7577. public function bidOpenVerify()
  7578. {
  7579. if (!$this->request->isPost()) {
  7580. $this->error(__('Invalid parameters'));
  7581. }
  7582. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7583. $this->error('无权限');
  7584. }
  7585. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7586. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7587. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7588. $code1 = trim((string)$this->request->post('code1', ''));
  7589. $code2 = trim((string)$this->request->post('code2', ''));
  7590. if ($scydgyId === '') {
  7591. $this->error('参数无效');
  7592. }
  7593. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7594. $this->error('请选择两位验证人');
  7595. }
  7596. if ($verifier1Id === $verifier2Id) {
  7597. $this->error('两位验证人不能相同');
  7598. }
  7599. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7600. $this->error('请输入6位短信验证码');
  7601. }
  7602. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7603. if ($bundle['pos'] === []) {
  7604. $this->error('该订单不在待确认供应商状态');
  7605. }
  7606. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7607. if ($ccydh === '') {
  7608. $this->error('订单号无效');
  7609. }
  7610. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7611. $this->success('已完成开标验证');
  7612. }
  7613. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7614. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7615. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7616. if ($verifier1 === null || $verifier2 === null) {
  7617. $this->error('验证人无效或未绑定手机号');
  7618. }
  7619. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7620. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7621. }
  7622. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7623. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7624. }
  7625. try {
  7626. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7627. } catch (\Throwable $e) {
  7628. $this->error($e->getMessage());
  7629. }
  7630. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7631. }
  7632. /**
  7633. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7634. */
  7635. public function auditSubmit()
  7636. {
  7637. if (!$this->request->isPost()) {
  7638. $this->error(__('Invalid parameters'));
  7639. }
  7640. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7641. if ($scydgyId === '') {
  7642. $this->error('参数无效');
  7643. }
  7644. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7645. $pos = $bundle['pos'];
  7646. $mergeRows = $bundle['merge_rows'];
  7647. if ($pos === [] || $mergeRows === []) {
  7648. $this->error('该订单不在待确认供应商状态');
  7649. }
  7650. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7651. if ($quoteGroups === []) {
  7652. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7653. }
  7654. $companyName = trim((string)$this->request->post('selected_company', ''));
  7655. if ($companyName === '') {
  7656. $this->error('请选择一家供应商');
  7657. }
  7658. $matched = null;
  7659. foreach ($quoteGroups as $g) {
  7660. if (!is_array($g)) {
  7661. continue;
  7662. }
  7663. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7664. $matched = $g;
  7665. break;
  7666. }
  7667. }
  7668. if ($matched === null) {
  7669. $this->error('所选供应商不在本单报价列表中');
  7670. }
  7671. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7672. if ($sysRqDb === '') {
  7673. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  7674. } else {
  7675. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  7676. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  7677. }
  7678. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  7679. $this->error('未到招标截止日期,暂不可确认');
  7680. }
  7681. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7682. $this->error('请先完成开标双重验证后再确认供应商');
  7683. }
  7684. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7685. $procCnt = count($mergeRows);
  7686. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7687. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7688. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  7689. Db::startTrans();
  7690. try {
  7691. foreach ($pos as $poRow) {
  7692. if (!is_array($poRow)) {
  7693. continue;
  7694. }
  7695. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7696. if (!$this->isValidScydgyRowId($sid)) {
  7697. continue;
  7698. }
  7699. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7700. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7701. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7702. 'pick_company_name' => $companyName,
  7703. 'sys_rq' => $sysRqDb,
  7704. ]);
  7705. }
  7706. Db::commit();
  7707. } catch (\Throwable $e) {
  7708. Db::rollback();
  7709. $this->error($e->getMessage());
  7710. }
  7711. foreach ($pos as $poRow) {
  7712. if (!is_array($poRow)) {
  7713. continue;
  7714. }
  7715. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7716. if (!$this->isValidScydgyRowId($sid)) {
  7717. continue;
  7718. }
  7719. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7720. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7721. }
  7722. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7723. }
  7724. /**
  7725. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7726. */
  7727. public function auditResendSms()
  7728. {
  7729. if (!$this->request->isPost()) {
  7730. $this->error(__('Invalid parameters'));
  7731. }
  7732. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7733. if ($scydgyId === '') {
  7734. $this->error('参数无效');
  7735. }
  7736. $loaded = $this->loadAuditResendBundle($scydgyId);
  7737. $mergeRows = $loaded['merge_rows'];
  7738. $bundle = $loaded['bundle'];
  7739. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7740. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7741. if ($quoteGroups === []) {
  7742. $this->error('暂无可通知的供应商');
  7743. }
  7744. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7745. $companiesJson = (string)$this->request->post('companies_json', '');
  7746. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7747. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7748. }
  7749. /**
  7750. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7751. */
  7752. public function auditResendEmail()
  7753. {
  7754. if (!$this->request->isPost()) {
  7755. $this->error(__('Invalid parameters'));
  7756. }
  7757. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7758. if ($scydgyId === '') {
  7759. $this->error('参数无效');
  7760. }
  7761. $loaded = $this->loadAuditResendBundle($scydgyId);
  7762. $mergeRows = $loaded['merge_rows'];
  7763. $bundle = $loaded['bundle'];
  7764. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7765. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7766. if ($quoteGroups === []) {
  7767. $this->error('暂无可通知的供应商');
  7768. }
  7769. $companiesJson = (string)$this->request->post('companies_json', '');
  7770. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7771. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7772. if ($companiesJson === '' && $selectedCompany === '') {
  7773. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7774. }
  7775. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7776. }
  7777. /**
  7778. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7779. *
  7780. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7781. * @return array<int, true> 已处理的 scydgy_id 集合
  7782. */
  7783. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7784. {
  7785. $pos = $bundle['pos'] ?? [];
  7786. if (!is_array($pos) || $pos === []) {
  7787. return [];
  7788. }
  7789. $sids = [];
  7790. foreach ($pos as $poRow) {
  7791. if (!is_array($poRow)) {
  7792. continue;
  7793. }
  7794. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7795. if ($this->isValidScydgyRowId($sid)) {
  7796. $sids[$sid] = true;
  7797. }
  7798. }
  7799. if ($sids === []) {
  7800. return [];
  7801. }
  7802. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7803. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7804. $suffix = trim((string)$logSuffix, ',, ');
  7805. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7806. $logMsg .= ':从历史存证退回协助初选';
  7807. } else {
  7808. $logMsg .= ':退回协助初选';
  7809. }
  7810. Db::table('purchase_order')
  7811. ->where('scydgy_id', 'in', array_keys($sids))
  7812. ->update([
  7813. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7814. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7815. 'pick_company_name' => '',
  7816. 'pick_time' => null,
  7817. 'sys_rq' => null,
  7818. 'mod_rq' => null,
  7819. ]);
  7820. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7821. foreach (array_keys($sids) as $sid) {
  7822. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7823. }
  7824. return $sids;
  7825. }
  7826. /**
  7827. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7828. *
  7829. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7830. */
  7831. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7832. {
  7833. $scydgyId = trim($scydgyId);
  7834. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7835. if ($scydgyId === '') {
  7836. return $empty;
  7837. }
  7838. try {
  7839. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7840. } catch (\Throwable $e) {
  7841. $anchor = null;
  7842. }
  7843. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7844. return $empty;
  7845. }
  7846. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7847. if ($ccydh === '') {
  7848. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7849. }
  7850. try {
  7851. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7852. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7853. $pos = $query->order('scydgy_id', 'asc')->select();
  7854. } catch (\Throwable $e) {
  7855. $pos = [$anchor];
  7856. }
  7857. if (!is_array($pos) || $pos === []) {
  7858. $pos = [$anchor];
  7859. }
  7860. return [
  7861. 'ccydh' => $ccydh,
  7862. 'pos' => $pos,
  7863. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7864. ];
  7865. }
  7866. protected function purchaseOrderRowIsCompleted(array $po): bool
  7867. {
  7868. $st = $po['status'] ?? null;
  7869. if ($st === 1 || $st === '1') {
  7870. return true;
  7871. }
  7872. if (is_string($st) && trim($st) === '1') {
  7873. return true;
  7874. }
  7875. return is_numeric($st) && (int)$st === 1;
  7876. }
  7877. /**
  7878. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7879. */
  7880. public function auditAbandon()
  7881. {
  7882. if (!$this->request->isPost()) {
  7883. $this->error(__('Invalid parameters'));
  7884. }
  7885. $anchorIds = [];
  7886. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7887. if ($batchRaw !== '') {
  7888. $decoded = json_decode($batchRaw, true);
  7889. if (is_array($decoded)) {
  7890. foreach ($decoded as $id) {
  7891. $s = trim((string)$id);
  7892. if ($s !== '') {
  7893. $anchorIds[] = $s;
  7894. }
  7895. }
  7896. }
  7897. }
  7898. if ($anchorIds === []) {
  7899. $single = trim((string)$this->request->post('scydgy_id', ''));
  7900. if ($single !== '') {
  7901. $anchorIds[] = $single;
  7902. }
  7903. }
  7904. if ($anchorIds === []) {
  7905. $this->error('请至少选择一条订单');
  7906. }
  7907. $processedCcydh = [];
  7908. $doneOrders = 0;
  7909. $allSids = [];
  7910. Db::startTrans();
  7911. try {
  7912. foreach ($anchorIds as $anchorId) {
  7913. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7914. if (($bundle['pos'] ?? []) === []) {
  7915. continue;
  7916. }
  7917. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7918. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7919. if (isset($processedCcydh[$dedupeKey])) {
  7920. continue;
  7921. }
  7922. $processedCcydh[$dedupeKey] = true;
  7923. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7924. if ($sids === []) {
  7925. continue;
  7926. }
  7927. $doneOrders++;
  7928. foreach (array_keys($sids) as $sid) {
  7929. $allSids[(int)$sid] = true;
  7930. }
  7931. }
  7932. if ($doneOrders < 1) {
  7933. throw new \Exception('所选订单均不在待确认供应商状态');
  7934. }
  7935. Db::commit();
  7936. } catch (\Throwable $e) {
  7937. Db::rollback();
  7938. $this->error($e->getMessage());
  7939. }
  7940. $this->pickHiddenScydgySetCache = null;
  7941. $msg = $doneOrders > 1
  7942. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7943. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7944. $this->success($msg);
  7945. }
  7946. /**
  7947. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7948. */
  7949. public function archiveAbandon()
  7950. {
  7951. if (!$this->request->isPost()) {
  7952. $this->error(__('Invalid parameters'));
  7953. }
  7954. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7955. $this->error(__('You have no permission'));
  7956. }
  7957. $anchorIds = [];
  7958. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7959. if ($batchRaw !== '') {
  7960. $decoded = json_decode($batchRaw, true);
  7961. if (is_array($decoded)) {
  7962. foreach ($decoded as $id) {
  7963. $s = trim((string)$id);
  7964. if ($s !== '') {
  7965. $anchorIds[] = $s;
  7966. }
  7967. }
  7968. }
  7969. }
  7970. if ($anchorIds === []) {
  7971. $single = trim((string)$this->request->post('scydgy_id', ''));
  7972. if ($single !== '') {
  7973. $anchorIds[] = $single;
  7974. }
  7975. }
  7976. if ($anchorIds === []) {
  7977. $this->error('请至少选择一条订单');
  7978. }
  7979. $processedCcydh = [];
  7980. $doneOrders = 0;
  7981. Db::startTrans();
  7982. try {
  7983. foreach ($anchorIds as $anchorId) {
  7984. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7985. if (($bundle['pos'] ?? []) === []) {
  7986. continue;
  7987. }
  7988. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7989. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7990. if (isset($processedCcydh[$dedupeKey])) {
  7991. continue;
  7992. }
  7993. $processedCcydh[$dedupeKey] = true;
  7994. $sids = $this->abandonOrderBundleToPick(
  7995. $bundle,
  7996. 'archive_abandon',
  7997. ',从历史存证退回协助初选'
  7998. );
  7999. if ($sids === []) {
  8000. continue;
  8001. }
  8002. $doneOrders++;
  8003. }
  8004. if ($doneOrders < 1) {
  8005. throw new \Exception('所选订单均不是已完结状态');
  8006. }
  8007. Db::commit();
  8008. } catch (\Throwable $e) {
  8009. Db::rollback();
  8010. $this->error($e->getMessage());
  8011. }
  8012. $this->pickHiddenScydgySetCache = null;
  8013. $msg = $doneOrders > 1
  8014. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  8015. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  8016. $this->success($msg);
  8017. }
  8018. /**
  8019. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  8020. */
  8021. public function purchaseApprovalReject()
  8022. {
  8023. if (!$this->request->isPost() || !$this->request->isAjax()) {
  8024. $this->error(__('Invalid parameters'));
  8025. }
  8026. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  8027. $this->error(__('You have no permission'));
  8028. }
  8029. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  8030. $decoded = json_decode($batchRaw, true);
  8031. if (!is_array($decoded) || $decoded === []) {
  8032. $this->error('提交数据无效');
  8033. }
  8034. $done = 0;
  8035. Db::startTrans();
  8036. try {
  8037. foreach ($decoded as $item) {
  8038. if (!is_array($item)) {
  8039. continue;
  8040. }
  8041. $sid = (int)($item['scydgy_id'] ?? 0);
  8042. if (!$this->isValidScydgyRowId($sid)) {
  8043. continue;
  8044. }
  8045. $this->runPurchaseApprovalRejectForSid($sid);
  8046. $done++;
  8047. }
  8048. if ($done < 1) {
  8049. throw new \Exception('所选订单均不在待审批状态');
  8050. }
  8051. Db::commit();
  8052. } catch (\Throwable $e) {
  8053. Db::rollback();
  8054. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  8055. }
  8056. $this->pickHiddenScydgySetCache = null;
  8057. $this->success('已驳回并退回「协助审批下发」');
  8058. }
  8059. /**
  8060. * @throws \Exception
  8061. */
  8062. protected function runPurchaseApprovalRejectForSid(int $sid): void
  8063. {
  8064. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  8065. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  8066. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  8067. $allIds = $this->purchaseOrderDetail($sid);
  8068. if ($allIds === []) {
  8069. throw new \Exception('未找到下发明细');
  8070. }
  8071. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8072. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  8073. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8074. 'pick_company_name' => '',
  8075. ]);
  8076. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  8077. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  8078. $poId = 0;
  8079. try {
  8080. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  8081. if (is_array($po)) {
  8082. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8083. }
  8084. } catch (\Throwable $e) {
  8085. }
  8086. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  8087. }
  8088. /**
  8089. * 审核弹窗(旧入口,POST 已关闭)
  8090. */
  8091. public function review()
  8092. {
  8093. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  8094. $this->error(__('You have no permission'));
  8095. }
  8096. if ($this->request->isPost()) {
  8097. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  8098. }
  8099. $this->view->assign('pickMode', 0);
  8100. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  8101. }
  8102. /**
  8103. * 审核弹窗获取公司列表
  8104. */
  8105. public function reviewCompanies()
  8106. {
  8107. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  8108. $this->error(__('You have no permission'));
  8109. }
  8110. if (!$this->request->isAjax()) {
  8111. $this->error(__('Invalid parameters'));
  8112. }
  8113. $list = [];
  8114. try {
  8115. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  8116. $rows = Db::table('customer')
  8117. ->where(function ($q) {
  8118. $q->where('status', 1)
  8119. ->whereOr('status', '1')
  8120. ->whereOr('status', '')
  8121. ->whereNull('status');
  8122. })
  8123. ->order('id', 'desc')
  8124. ->select();
  8125. } catch (\Throwable $e) {
  8126. $this->success('', '', []);
  8127. return;
  8128. }
  8129. if (!is_array($rows)) {
  8130. $this->success('', '', []);
  8131. return;
  8132. }
  8133. $detailColCandidates = [
  8134. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  8135. 'company_detail', 'company_desc', 'address',
  8136. ];
  8137. foreach ($rows as $row) {
  8138. if (!is_array($row)) {
  8139. continue;
  8140. }
  8141. $norm = [];
  8142. foreach ($row as $k => $v) {
  8143. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  8144. }
  8145. $row = $norm;
  8146. $st = $row['status'] ?? '';
  8147. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  8148. continue;
  8149. }
  8150. $payload = $this->buildCustomerContactPayloadFromRow($row);
  8151. if ($payload === null) {
  8152. continue;
  8153. }
  8154. $detail = '';
  8155. foreach ($detailColCandidates as $dk) {
  8156. if (!isset($row[$dk])) {
  8157. continue;
  8158. }
  8159. $dv = trim((string)$row[$dk]);
  8160. if ($dv !== '') {
  8161. $detail = $dv;
  8162. break;
  8163. }
  8164. }
  8165. $payload['detail'] = $detail;
  8166. $list[] = $this->maskSupplierContactFields($payload);
  8167. }
  8168. $this->success('', '', $list);
  8169. }
  8170. /**
  8171. * 采购确认-下发明细弹窗:
  8172. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  8173. */
  8174. public function outward_detail()
  8175. {
  8176. $ids = $this->request->param('ids', $this->request->param('id', ''));
  8177. if (is_array($ids)) {
  8178. $ids = isset($ids[0]) ? $ids[0] : '';
  8179. }
  8180. $ids = trim((string)$ids);
  8181. if ($ids === '') {
  8182. $this->error(__('Invalid parameters'));
  8183. }
  8184. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  8185. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  8186. $wffTab = 'all';
  8187. }
  8188. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  8189. $purchaseOrderId = 0;
  8190. $po = null;
  8191. try {
  8192. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8193. if (is_array($po)) {
  8194. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8195. }
  8196. } catch (\Throwable $e) {
  8197. $purchaseOrderId = 0;
  8198. $po = null;
  8199. }
  8200. if (!$isPurchaseConfirm && is_array($po)) {
  8201. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  8202. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  8203. $isPurchaseConfirm = true;
  8204. }
  8205. }
  8206. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  8207. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  8208. $confirmProcessCount = 1;
  8209. $confirmPickGroups = [];
  8210. $processDisplayRows = [];
  8211. $allDetailsBySid = [];
  8212. $requiredSidList = [];
  8213. $sidList = [$ids];
  8214. if ($isPurchaseConfirm) {
  8215. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  8216. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  8217. if ($mergeRows !== []) {
  8218. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  8219. }
  8220. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  8221. if ($confirmBundle['pos'] !== []) {
  8222. $sidList = [];
  8223. foreach ($confirmBundle['pos'] as $poRow) {
  8224. if (!is_array($poRow)) {
  8225. continue;
  8226. }
  8227. $sid = (int)($poRow['scydgy_id'] ?? 0);
  8228. if (!$this->isValidScydgyRowId($sid)) {
  8229. continue;
  8230. }
  8231. $sidList[] = (string)$sid;
  8232. $requiredSidList[] = $sid;
  8233. }
  8234. }
  8235. if ($sidList === []) {
  8236. $sidList = [$ids];
  8237. $requiredSidList = [(int)$ids];
  8238. }
  8239. $confirmProcessCount = max(1, count($requiredSidList));
  8240. if (is_array($po) && $purchaseOrderId <= 0) {
  8241. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8242. }
  8243. }
  8244. $rows = [];
  8245. try {
  8246. if (count($sidList) === 1) {
  8247. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  8248. } else {
  8249. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  8250. }
  8251. } catch (\Throwable $e) {
  8252. $rows = [];
  8253. }
  8254. if ($isPurchaseConfirm) {
  8255. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  8256. }
  8257. foreach ($rows as &$r) {
  8258. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  8259. $r['id'] = $r['ID'];
  8260. }
  8261. if (isset($r['createtime'])) {
  8262. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  8263. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  8264. } else {
  8265. $r['createtime_text'] = (string)$r['createtime'];
  8266. }
  8267. } else {
  8268. $r['createtime_text'] = '';
  8269. }
  8270. if (is_array($r)) {
  8271. $r = $this->maskSupplierContactFields($r);
  8272. }
  8273. }
  8274. unset($r);
  8275. $pickedCompanyName = '';
  8276. if ($isPurchaseConfirm) {
  8277. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  8278. if (!is_array($poRow)) {
  8279. continue;
  8280. }
  8281. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  8282. if ($pn !== '') {
  8283. $pickedCompanyName = $pn;
  8284. break;
  8285. }
  8286. }
  8287. }
  8288. $this->view->assign('rows', $rows ?: []);
  8289. $this->view->assign('rowCount', count($rows ?: []));
  8290. $this->view->assign('scydgyId', $ids);
  8291. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  8292. $this->view->assign('headTitle', $headTitle);
  8293. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  8294. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  8295. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  8296. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  8297. $this->view->assign('processDisplayRows', $processDisplayRows);
  8298. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8299. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8300. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8301. $this->view->assign('bidOpenVerified', ($isPurchaseConfirm && $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle)) ? 1 : 0);
  8302. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups));
  8303. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups) ? 1 : 0);
  8304. $sysRqDisplay = '—';
  8305. if ($isPurchaseConfirm) {
  8306. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8307. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8308. );
  8309. }
  8310. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8311. $this->view->assign('sysRq', $isPurchaseConfirm
  8312. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8313. : '');
  8314. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8315. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8316. : '');
  8317. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8318. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8319. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8320. if ($isPurchaseConfirm) {
  8321. return $this->view->fetch();
  8322. }
  8323. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8324. $this->view->engine->layout(false);
  8325. try {
  8326. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8327. $this->view->assign('dialogBody', $bodyHtml);
  8328. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8329. } finally {
  8330. if ($restoreLayout) {
  8331. $this->view->engine->layout($restoreLayout);
  8332. }
  8333. }
  8334. }
  8335. /**
  8336. * 月度导出记录表(不存在时自动创建)
  8337. */
  8338. protected function ensurePurchaseMonthExportLogTable(): void
  8339. {
  8340. try {
  8341. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8342. } catch (\Throwable $e) {
  8343. Db::execute(
  8344. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8345. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8346. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8347. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8348. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8349. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8350. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8351. `createtime` int(10) unsigned DEFAULT NULL,
  8352. PRIMARY KEY (`id`),
  8353. KEY `idx_ym` (`ym`),
  8354. KEY `idx_ct` (`createtime`)
  8355. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8356. );
  8357. }
  8358. }
  8359. /**
  8360. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8361. *
  8362. * @param array<int, mixed> $dbRows
  8363. * @return array<int, array<string, mixed>>
  8364. */
  8365. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8366. {
  8367. $keyword = trim((string)$this->request->get('search', ''));
  8368. if ($keyword === '') {
  8369. $keyword = trim((string)$this->request->request('search', ''));
  8370. }
  8371. $filter = $this->request->get('filter', '');
  8372. $op = $this->request->get('op', '');
  8373. if (is_string($filter) && $filter !== '') {
  8374. $filterArr = (array)json_decode($filter, true);
  8375. } else {
  8376. $filterArr = is_array($filter) ? $filter : [];
  8377. }
  8378. if (is_string($op) && $op !== '') {
  8379. $opArr = (array)json_decode($op, true);
  8380. } else {
  8381. $opArr = is_array($op) ? $op : [];
  8382. }
  8383. if ($keyword === '' && $filterArr === []) {
  8384. return array_values(array_filter($dbRows, 'is_array'));
  8385. }
  8386. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8387. $out = [];
  8388. foreach ($dbRows as $row) {
  8389. if (!is_array($row)) {
  8390. continue;
  8391. }
  8392. if ($keyword !== '') {
  8393. $hit = false;
  8394. foreach ($searchFields as $f) {
  8395. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8396. $hit = true;
  8397. break;
  8398. }
  8399. }
  8400. if (!$hit) {
  8401. continue;
  8402. }
  8403. }
  8404. $passFilter = true;
  8405. foreach ($filterArr as $field => $val) {
  8406. $field = (string)$field;
  8407. $val = trim((string)$val);
  8408. if ($field === '' || $val === '') {
  8409. continue;
  8410. }
  8411. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8412. continue;
  8413. }
  8414. $cell = (string)($row[$field] ?? '');
  8415. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8416. if ($mode === '=' || $mode === 'EQUAL') {
  8417. if (strcasecmp($cell, $val) !== 0) {
  8418. $passFilter = false;
  8419. break;
  8420. }
  8421. } elseif (mb_stripos($cell, $val) === false) {
  8422. $passFilter = false;
  8423. break;
  8424. }
  8425. }
  8426. if (!$passFilter) {
  8427. continue;
  8428. }
  8429. $out[] = $row;
  8430. }
  8431. return $out;
  8432. }
  8433. /**
  8434. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8435. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8436. */
  8437. public function export_month_outward()
  8438. {
  8439. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8440. $this->error(__('You have no permission'));
  8441. }
  8442. $bundle = $this->prepareMonthOutwardExportBundle();
  8443. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8444. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  8445. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  8446. $spreadsheet = new Spreadsheet();
  8447. $sheet = $spreadsheet->getActiveSheet();
  8448. $sheet->setTitle('外协加工明细');
  8449. $mon = (int)substr($ym, 5, 2);
  8450. $sheet->mergeCells('A1:H1');
  8451. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8452. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8453. $sheet->getStyle('A1')->getAlignment()
  8454. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8455. ->setVertical(Alignment::VERTICAL_CENTER);
  8456. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8457. $col = 'A';
  8458. foreach ($headers as $h) {
  8459. $sheet->setCellValue($col . '2', $h);
  8460. $col++;
  8461. }
  8462. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8463. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8464. $rowNum = 3;
  8465. $sumSubtotalCounts = 0;
  8466. $grandAmount = 0.0;
  8467. $globalSeq = 0;
  8468. if ($groups === []) {
  8469. $sheet->mergeCells('A3:H3');
  8470. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8471. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8472. $rowNum = 4;
  8473. } else {
  8474. foreach ($groups as $items) {
  8475. if ($items === []) {
  8476. continue;
  8477. }
  8478. $groupLineCount = count($items);
  8479. $subAmount = 0.0;
  8480. foreach ($items as $line) {
  8481. $globalSeq++;
  8482. $dr = $line['detail'];
  8483. $amt = $this->procuremenExportAmount($dr);
  8484. $subAmount += $amt;
  8485. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8486. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8487. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8488. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8489. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8490. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8491. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8492. $sheet->setCellValue('H' . $rowNum, $amt);
  8493. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8494. $rowNum++;
  8495. }
  8496. $sumSubtotalCounts += $groupLineCount;
  8497. $grandAmount += $subAmount;
  8498. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8499. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8500. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8501. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8502. ->setVertical(Alignment::VERTICAL_CENTER);
  8503. $rowNum++;
  8504. }
  8505. }
  8506. $sheet->setCellValue('A' . $rowNum, '总计');
  8507. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8508. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8509. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8510. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8511. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8512. $lastRow = $rowNum;
  8513. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8514. 'borders' => [
  8515. 'allBorders' => [
  8516. 'borderStyle' => Border::BORDER_THIN,
  8517. 'color' => ['rgb' => '000000'],
  8518. ],
  8519. ],
  8520. ]);
  8521. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8522. if ($lastRow >= 3) {
  8523. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8524. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8525. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8526. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8527. }
  8528. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8529. $sheet->getColumnDimension('A')->setWidth(7);
  8530. $sheet->getColumnDimension('B')->setWidth(16);
  8531. $sheet->getColumnDimension('C')->setWidth(52);
  8532. $sheet->getColumnDimension('D')->setWidth(32);
  8533. $sheet->getColumnDimension('E')->setWidth(12);
  8534. $sheet->getColumnDimension('F')->setWidth(44);
  8535. $sheet->getColumnDimension('G')->setWidth(26);
  8536. $sheet->getColumnDimension('H')->setWidth(13);
  8537. $sheet->getRowDimension(1)->setRowHeight(28);
  8538. $ymCompact = str_replace('-', '', $ym);
  8539. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8540. $filename = $fileBase . '.xlsx';
  8541. try {
  8542. $this->ensurePurchaseMonthExportLogTable();
  8543. list($adminId, $adminName) = $this->GetUseName();
  8544. Db::table('purchase_month_export_log')->insert([
  8545. 'ym' => $ym,
  8546. 'admin_id' => (int)$adminId,
  8547. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8548. 'row_count' => count($exportLines),
  8549. 'total_amount' => round($grandAmount, 2),
  8550. 'createtime' => time(),
  8551. ]);
  8552. } catch (\Throwable $e) {
  8553. Log::write('month export log: ' . $e->getMessage(), 'error');
  8554. }
  8555. if (ob_get_length()) {
  8556. ob_end_clean();
  8557. }
  8558. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8559. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8560. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8561. header('Cache-Control: max-age=0');
  8562. $writer = new Xlsx($spreadsheet);
  8563. $writer->save('php://output');
  8564. $spreadsheet->disconnectWorksheets();
  8565. unset($spreadsheet);
  8566. exit;
  8567. }
  8568. /**
  8569. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  8570. */
  8571. public function export_month_quote()
  8572. {
  8573. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  8574. $this->error(__('You have no permission'));
  8575. }
  8576. $bundle = $this->prepareMonthOutwardExportBundle();
  8577. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8578. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  8579. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  8580. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8581. $spreadsheet = new Spreadsheet();
  8582. $sheet = $spreadsheet->getActiveSheet();
  8583. $sheet->setTitle('供应商报价明细');
  8584. $mon = (int)substr($ym, 5, 2);
  8585. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  8586. $sheet->getColumnDimension('A')->setWidth(7);
  8587. $sheet->getColumnDimension('B')->setWidth(16);
  8588. $sheet->getColumnDimension('C')->setWidth(52);
  8589. $sheet->getColumnDimension('D')->setWidth(26);
  8590. $sheet->getColumnDimension('E')->setWidth(32);
  8591. $sheet->getColumnDimension('F')->setWidth(12);
  8592. $sheet->getColumnDimension('G')->setWidth(14);
  8593. $sheet->getColumnDimension('H')->setWidth(12);
  8594. if ($quoteLastRow < 1) {
  8595. $quoteLastRow = 3;
  8596. }
  8597. $ymCompact = str_replace('-', '', $ym);
  8598. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  8599. if (ob_get_length()) {
  8600. ob_end_clean();
  8601. }
  8602. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  8603. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8604. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8605. header('Cache-Control: max-age=0');
  8606. $writer = new Xlsx($spreadsheet);
  8607. $writer->save('php://output');
  8608. $spreadsheet->disconnectWorksheets();
  8609. unset($spreadsheet);
  8610. exit;
  8611. }
  8612. /**
  8613. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  8614. *
  8615. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  8616. */
  8617. protected function prepareMonthOutwardExportBundle(): array
  8618. {
  8619. $this->request->filter(['strip_tags', 'trim']);
  8620. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8621. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8622. $ym = date('Y-m');
  8623. }
  8624. $dbRows = [];
  8625. try {
  8626. $query = Db::table('purchase_order');
  8627. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8628. $dbRows = $query->select();
  8629. } catch (\Throwable $e) {
  8630. $dbRows = [];
  8631. }
  8632. if (!is_array($dbRows)) {
  8633. $dbRows = [];
  8634. }
  8635. $completeTsMap = [];
  8636. $sidList = [];
  8637. foreach ($dbRows as $dbRow) {
  8638. if (!is_array($dbRow)) {
  8639. continue;
  8640. }
  8641. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8642. if ($sid > 0) {
  8643. $sidList[$sid] = true;
  8644. }
  8645. }
  8646. if ($sidList !== []) {
  8647. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8648. }
  8649. $searchKw = trim((string)$this->request->get('search', ''));
  8650. if ($searchKw === '') {
  8651. $searchKw = trim((string)$this->request->request('search', ''));
  8652. }
  8653. $filterRaw = $this->request->get('filter', '');
  8654. $filterArrTmp = [];
  8655. if (is_string($filterRaw) && $filterRaw !== '') {
  8656. $filterArrTmp = (array)json_decode($filterRaw, true);
  8657. } elseif (is_array($filterRaw)) {
  8658. $filterArrTmp = $filterRaw;
  8659. }
  8660. $hasSearch = ($searchKw !== '');
  8661. if (!$hasSearch) {
  8662. foreach ($filterArrTmp as $fv) {
  8663. if (trim((string)$fv) !== '') {
  8664. $hasSearch = true;
  8665. break;
  8666. }
  8667. }
  8668. }
  8669. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8670. if (!is_array($dbRow)) {
  8671. return false;
  8672. }
  8673. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8674. if ($done['ts'] <= 0) {
  8675. return false;
  8676. }
  8677. if ($hasSearch) {
  8678. return true;
  8679. }
  8680. return date('Y-m', $done['ts']) === $ym;
  8681. }));
  8682. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8683. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8684. $mainBySid = [];
  8685. foreach ($pool as $rw) {
  8686. if (!is_array($rw)) {
  8687. continue;
  8688. }
  8689. $rid = (int)($rw['ID'] ?? 0);
  8690. if ($rid > 0) {
  8691. $mainBySid[$rid] = $rw;
  8692. }
  8693. }
  8694. if ($mainBySid === []) {
  8695. $detailRows = [];
  8696. } else {
  8697. try {
  8698. $detailRows = Db::table('purchase_order_detail')
  8699. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8700. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8701. ->order('status', 'desc')
  8702. ->order('CCYDH', 'asc')
  8703. ->order('company_name', 'asc')
  8704. ->order('id', 'asc')
  8705. ->select();
  8706. } catch (\Throwable $e) {
  8707. try {
  8708. $detailRows = Db::table('purchase_order_detail')
  8709. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8710. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8711. ->order('status', 'desc')
  8712. ->order('CCYDH', 'asc')
  8713. ->order('company_name', 'asc')
  8714. ->order('ID', 'asc')
  8715. ->select();
  8716. } catch (\Throwable $e2) {
  8717. $detailRows = [];
  8718. }
  8719. }
  8720. }
  8721. if (!is_array($detailRows)) {
  8722. $detailRows = [];
  8723. }
  8724. $exportLines = [];
  8725. $detailSidSeen = [];
  8726. foreach ($detailRows as $dr) {
  8727. if (!is_array($dr)) {
  8728. continue;
  8729. }
  8730. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8731. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8732. continue;
  8733. }
  8734. if (isset($detailSidSeen[$sid])) {
  8735. continue;
  8736. }
  8737. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8738. continue;
  8739. }
  8740. $detailSidSeen[$sid] = true;
  8741. $m = $mainBySid[$sid];
  8742. $exportLines[] = [
  8743. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8744. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8745. 'company_name' => (string)($dr['company_name'] ?? ''),
  8746. 'CDF' => (string)($m['CDF'] ?? ''),
  8747. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8748. 'gx' => $this->procuremenExportGxText($m),
  8749. 'detail' => $dr,
  8750. ];
  8751. }
  8752. foreach ($detailRows as $dr) {
  8753. if (!is_array($dr)) {
  8754. continue;
  8755. }
  8756. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8757. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8758. continue;
  8759. }
  8760. $detailSidSeen[$sid] = true;
  8761. $m = $mainBySid[$sid];
  8762. $exportLines[] = [
  8763. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8764. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8765. 'company_name' => (string)($dr['company_name'] ?? ''),
  8766. 'CDF' => (string)($m['CDF'] ?? ''),
  8767. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8768. 'gx' => $this->procuremenExportGxText($m),
  8769. 'detail' => $dr,
  8770. ];
  8771. }
  8772. foreach ($mainBySid as $sid => $m) {
  8773. if (isset($detailSidSeen[$sid])) {
  8774. continue;
  8775. }
  8776. $company = trim((string)($m['pick_company_name'] ?? ''));
  8777. $exportLines[] = [
  8778. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8779. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8780. 'company_name' => $company,
  8781. 'CDF' => (string)($m['CDF'] ?? ''),
  8782. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8783. 'gx' => $this->procuremenExportGxText($m),
  8784. 'detail' => [],
  8785. ];
  8786. }
  8787. $groups = [];
  8788. foreach ($exportLines as $line) {
  8789. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8790. if (!isset($groups[$k])) {
  8791. $groups[$k] = [];
  8792. }
  8793. $groups[$k][] = $line;
  8794. }
  8795. ksort($groups, SORT_STRING);
  8796. return [
  8797. 'ym' => $ym,
  8798. 'mainBySid' => $mainBySid,
  8799. 'detailRows' => $detailRows,
  8800. 'exportLines' => $exportLines,
  8801. 'groups' => $groups,
  8802. ];
  8803. }
  8804. /**
  8805. * 导出用:工序列文案
  8806. */
  8807. protected function procuremenExportGxText(array $r)
  8808. {
  8809. $a = trim((string)($r['CDXMC'] ?? ''));
  8810. $b = trim((string)($r['CGYMC'] ?? ''));
  8811. if ($a !== '' && $b !== '') {
  8812. return $a . ':' . $b;
  8813. }
  8814. return $a !== '' ? $a : $b;
  8815. }
  8816. /**
  8817. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8818. */
  8819. protected function procuremenExportAmount(array $r)
  8820. {
  8821. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8822. if (!array_key_exists($k, $r)) {
  8823. continue;
  8824. }
  8825. $v = $r[$k];
  8826. if ($v === null || $v === '') {
  8827. continue;
  8828. }
  8829. if (is_numeric($v)) {
  8830. return (float)$v;
  8831. }
  8832. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8833. if ($v !== '' && is_numeric($v)) {
  8834. return (float)$v;
  8835. }
  8836. }
  8837. return 0.0;
  8838. }
  8839. /**
  8840. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8841. *
  8842. * @param array<int, array<string, mixed>> $detailRows
  8843. * @param array<int, array<string, mixed>> $mainBySid
  8844. * @return array<int, array<string, mixed>>
  8845. */
  8846. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8847. {
  8848. $lines = [];
  8849. foreach ($detailRows as $dr) {
  8850. if (!is_array($dr)) {
  8851. continue;
  8852. }
  8853. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8854. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8855. continue;
  8856. }
  8857. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8858. continue;
  8859. }
  8860. $cn = trim((string)($dr['company_name'] ?? ''));
  8861. if ($cn === '') {
  8862. continue;
  8863. }
  8864. $m = $mainBySid[$sid];
  8865. $am = trim((string)($dr['amount'] ?? ''));
  8866. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8867. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8868. $amountText = $amountFilled
  8869. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8870. : '未填写';
  8871. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8872. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8873. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8874. $deliveryShow = $deliveryRaw;
  8875. }
  8876. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8877. ? $deliveryShow
  8878. : '未填写';
  8879. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8880. $lines[] = [
  8881. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8882. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8883. 'gx' => $this->procuremenExportGxText($m),
  8884. 'company_name' => $cn,
  8885. 'amount_text' => $amountText,
  8886. 'amount_num' => $amountFilled ? $amountNum : null,
  8887. 'delivery_text' => $deliveryText,
  8888. 'picked_text' => $picked ? '中标' : '未中标',
  8889. 'picked' => $picked,
  8890. ];
  8891. }
  8892. $winnerSupplierByOrder = [];
  8893. foreach ($lines as $line) {
  8894. $dh = trim((string)($line['CCYDH'] ?? ''));
  8895. $cn = trim((string)($line['company_name'] ?? ''));
  8896. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8897. $winnerSupplierByOrder[$dh][$cn] = true;
  8898. }
  8899. }
  8900. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8901. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8902. if ($c !== 0) {
  8903. return $c;
  8904. }
  8905. $dh = trim((string)($a['CCYDH'] ?? ''));
  8906. $aCn = trim((string)($a['company_name'] ?? ''));
  8907. $bCn = trim((string)($b['company_name'] ?? ''));
  8908. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8909. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8910. if ($aSupplierWin !== $bSupplierWin) {
  8911. return $aSupplierWin ? -1 : 1;
  8912. }
  8913. $c = strcmp($aCn, $bCn);
  8914. if ($c !== 0) {
  8915. return $c;
  8916. }
  8917. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8918. return !empty($a['picked']) ? -1 : 1;
  8919. }
  8920. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8921. if ($c !== 0) {
  8922. return $c;
  8923. }
  8924. return 0;
  8925. });
  8926. return $lines;
  8927. }
  8928. /**
  8929. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8930. *
  8931. * @param array<int, array<string, mixed>> $quoteLines
  8932. */
  8933. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8934. {
  8935. $mon = (int)substr($ym, 5, 2);
  8936. $titleRow = $startRow;
  8937. $headerRow = $startRow + 1;
  8938. $dataStartRow = $startRow + 2;
  8939. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8940. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8941. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8942. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8943. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8944. ->setVertical(Alignment::VERTICAL_CENTER);
  8945. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8946. $col = 'A';
  8947. foreach ($headers as $h) {
  8948. $sheet->setCellValue($col . $headerRow, $h);
  8949. $col++;
  8950. }
  8951. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8952. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8953. $rowNum = $dataStartRow;
  8954. if ($quoteLines === []) {
  8955. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8956. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8957. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8958. $rowNum = $dataStartRow + 1;
  8959. } else {
  8960. $i = 0;
  8961. foreach ($quoteLines as $line) {
  8962. $i++;
  8963. $sheet->setCellValue('A' . $rowNum, $i);
  8964. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8965. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8966. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8967. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8968. if ($line['amount_num'] !== null) {
  8969. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8970. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8971. } else {
  8972. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8973. }
  8974. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8975. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8976. if (!empty($line['picked'])) {
  8977. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8978. }
  8979. $rowNum++;
  8980. }
  8981. }
  8982. $lastRow = $rowNum - 1;
  8983. if ($lastRow >= $headerRow) {
  8984. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8985. 'borders' => [
  8986. 'allBorders' => [
  8987. 'borderStyle' => Border::BORDER_THIN,
  8988. 'color' => ['rgb' => '000000'],
  8989. ],
  8990. ],
  8991. ]);
  8992. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8993. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8994. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8995. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8996. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8997. if ($lastRow >= $dataStartRow) {
  8998. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8999. }
  9000. }
  9001. return $lastRow;
  9002. }
  9003. /**
  9004. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  9005. */
  9006. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  9007. {
  9008. if ($lastRow < $dataStartRow || $headerRow < 1) {
  9009. return;
  9010. }
  9011. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  9012. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9013. ->setVertical(Alignment::VERTICAL_CENTER);
  9014. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  9015. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9016. ->setVertical(Alignment::VERTICAL_CENTER);
  9017. if ($lastCol > 'B') {
  9018. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  9019. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  9020. ->setVertical(Alignment::VERTICAL_CENTER);
  9021. }
  9022. }
  9023. /**
  9024. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  9025. */
  9026. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  9027. {
  9028. $s = trim($ccydh);
  9029. if ($s === '') {
  9030. return 'ORDER';
  9031. }
  9032. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  9033. $s = trim($s, '._-');
  9034. if ($s === '') {
  9035. return 'ORDER';
  9036. }
  9037. if (function_exists('mb_substr')) {
  9038. return mb_substr($s, 0, 80, 'UTF-8');
  9039. }
  9040. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  9041. }
  9042. /**
  9043. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  9044. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  9045. *
  9046. * @return array{objectKey: string, webPath: string}
  9047. */
  9048. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  9049. {
  9050. $sid = (int)$scydgyId;
  9051. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  9052. $y = date('Y');
  9053. $m = date('m');
  9054. $d = date('d');
  9055. $basename = $safeOrder . '_' . $sid . '.pdf';
  9056. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  9057. return [
  9058. 'objectKey' => $objectKey,
  9059. 'webPath' => '/' . $objectKey,
  9060. ];
  9061. }
  9062. /**
  9063. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  9064. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  9065. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  9066. *
  9067. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  9068. */
  9069. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  9070. {
  9071. if (!$this->isValidScydgyRowId($scydgyId)) {
  9072. return '';
  9073. }
  9074. $ids = trim((string)$scydgyId);
  9075. $prep = $this->prepareProcuremenDetailsView($ids);
  9076. if (!$prep['ok']) {
  9077. return '';
  9078. }
  9079. $ccydh = $prep['ccydh'];
  9080. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  9081. $objectKey = $paths['objectKey'];
  9082. $webPath = $paths['webPath'];
  9083. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  9084. $this->view->assign([
  9085. 'pdf_export' => 1,
  9086. 'pdfMetaLine' => $meta,
  9087. ]);
  9088. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  9089. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  9090. $this->view->engine->layout(false);
  9091. try {
  9092. $html = $this->view->fetch('procuremen/details_pdf_shell');
  9093. } catch (\Throwable $e) {
  9094. if ($restoreLayout) {
  9095. $this->view->engine->layout($restoreLayout);
  9096. }
  9097. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  9098. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  9099. return '';
  9100. }
  9101. if ($restoreLayout) {
  9102. $this->view->engine->layout($restoreLayout);
  9103. }
  9104. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  9105. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  9106. if (!is_dir($tempDir)) {
  9107. @mkdir($tempDir, 0755, true);
  9108. }
  9109. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  9110. try {
  9111. $mpdf = new \Mpdf\Mpdf([
  9112. 'mode' => 'utf-8',
  9113. 'format' => 'A4',
  9114. 'margin_left' => 12,
  9115. 'margin_right' => 12,
  9116. 'margin_top' => 14,
  9117. 'margin_bottom' => 14,
  9118. 'tempDir' => $tempDir,
  9119. 'autoScriptToLang' => true,
  9120. 'autoLangToFont' => true,
  9121. ]);
  9122. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  9123. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  9124. $mpdf->SetBasePath('http://127.0.0.1/');
  9125. $mpdf->WriteHTML($html);
  9126. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  9127. } catch (\Throwable $e) {
  9128. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  9129. if (is_file($tempPdf)) {
  9130. @unlink($tempPdf);
  9131. }
  9132. return '';
  9133. }
  9134. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  9135. if ($ossUrl !== '') {
  9136. @unlink($tempPdf);
  9137. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  9138. return $ossUrl;
  9139. }
  9140. $pi = pathinfo($objectKey);
  9141. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  9142. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  9143. if ($baseFile === '') {
  9144. @unlink($tempPdf);
  9145. return '';
  9146. }
  9147. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  9148. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  9149. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  9150. @unlink($tempPdf);
  9151. return '';
  9152. }
  9153. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  9154. if (!@copy($tempPdf, $fullPath)) {
  9155. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  9156. @unlink($tempPdf);
  9157. return '';
  9158. }
  9159. @unlink($tempPdf);
  9160. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  9161. return $webPath;
  9162. }
  9163. /**
  9164. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  9165. */
  9166. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  9167. {
  9168. if ($scydgyId <= 0 || $webPath === '') {
  9169. return;
  9170. }
  9171. try {
  9172. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  9173. } catch (\Throwable $e) {
  9174. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  9175. }
  9176. }
  9177. /**
  9178. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  9179. *
  9180. * @param array<string, string> $vars
  9181. * @return array<string, string>
  9182. */
  9183. protected function normalizeSmsTemplateVars(array $vars): array
  9184. {
  9185. $out = [];
  9186. foreach ($vars as $k => $v) {
  9187. $out[(string)$k] = trim((string)$v);
  9188. }
  9189. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  9190. $out['contact_name'] = $out['company_name'];
  9191. }
  9192. return $out;
  9193. }
  9194. /**
  9195. * 按手机号或公司名称查 customer 表联系人姓名
  9196. */
  9197. protected function resolveCustomerContactName(string $phone, string $companyName): string
  9198. {
  9199. $phone = trim($phone);
  9200. $companyName = trim($companyName);
  9201. try {
  9202. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  9203. $row = Db::table('customer')
  9204. ->where(function ($q) use ($phone) {
  9205. $q->where('phone', $phone)->whereOr('account', $phone);
  9206. })
  9207. ->order('id', 'asc')
  9208. ->find();
  9209. if (is_array($row)) {
  9210. $nm = trim((string)($row['username'] ?? ''));
  9211. if ($nm !== '') {
  9212. return $nm;
  9213. }
  9214. }
  9215. }
  9216. if ($companyName !== '') {
  9217. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  9218. if (is_array($row)) {
  9219. return trim((string)($row['username'] ?? ''));
  9220. }
  9221. }
  9222. } catch (\Throwable $e) {
  9223. }
  9224. return '';
  9225. }
  9226. /**
  9227. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  9228. */
  9229. protected function plainTextToHtmlEmailBody(string $text): string
  9230. {
  9231. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  9232. $parts = explode("\n", $text);
  9233. $out = [];
  9234. foreach ($parts as $line) {
  9235. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  9236. $out[] = $line;
  9237. } else {
  9238. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  9239. }
  9240. }
  9241. return implode("<br>\n", $out);
  9242. }
  9243. /**
  9244. * 短信场景:去掉链接类变量,避免误填 URL
  9245. *
  9246. * @param array<string, string> $vars
  9247. * @return array<string, string>
  9248. */
  9249. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  9250. {
  9251. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  9252. return $vars;
  9253. }
  9254. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  9255. $vars[$k] = '';
  9256. }
  9257. return $vars;
  9258. }
  9259. /**
  9260. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  9261. *
  9262. * @param array<string, string> $vars
  9263. */
  9264. protected function renderNotifyTemplate(string $scene, array $vars): string
  9265. {
  9266. $vars = $this->normalizeSmsTemplateVars($vars);
  9267. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  9268. $row = $this->loadNotifyTemplateRow($scene);
  9269. if ($row === null) {
  9270. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9271. }
  9272. $tpl = trim((string)($row['content'] ?? ''));
  9273. if ($tpl === '') {
  9274. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9275. }
  9276. foreach ($vars as $k => $v) {
  9277. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  9278. }
  9279. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  9280. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  9281. return $tpl;
  9282. }
  9283. protected function resolveProcuremenEmailSubject(string $scene): string
  9284. {
  9285. $map = [
  9286. 'review_email' => '您有新的协助加工订单',
  9287. ];
  9288. $subject = trim((string)($map[$scene] ?? ''));
  9289. if ($subject === '') {
  9290. $this->error('未配置邮件主题:' . $scene);
  9291. }
  9292. return $subject;
  9293. }
  9294. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  9295. {
  9296. $map = [
  9297. 'review_email' => '协助下发-邮箱',
  9298. 'review_sms' => '协助下发-短信',
  9299. 'confirm_ok' => '采购确认-通过',
  9300. 'confirm_fail' => '采购确认-未通过',
  9301. 'bid_open' => '开标双重验证',
  9302. ];
  9303. $label = $map[$scene] ?? $scene;
  9304. if ($titleRequired) {
  9305. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  9306. }
  9307. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  9308. }
  9309. /**
  9310. * 是否开启协助通知演练(不发真实短信/邮件)
  9311. */
  9312. protected function isProcuremenNotifyDryRun(): bool
  9313. {
  9314. return (bool)Config::get('procuremen_notify_dry_run');
  9315. }
  9316. /**
  9317. * @param array<string, mixed> $payload
  9318. */
  9319. protected function recordNotifyDryRunPreview(array $payload): void
  9320. {
  9321. $this->notifyDryRunPreview[] = $payload;
  9322. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9323. }
  9324. /**
  9325. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  9326. * @throws \Exception
  9327. */
  9328. protected function smsbao($phone, $content)
  9329. {
  9330. if ($this->isProcuremenNotifyDryRun()) {
  9331. $this->recordNotifyDryRunPreview([
  9332. 'scene' => 'sms_only',
  9333. 'phone' => $phone,
  9334. 'sms_content' => $content,
  9335. ]);
  9336. return;
  9337. }
  9338. $statusStr = [
  9339. '0' => '短信发送成功',
  9340. '-1' => '参数不全',
  9341. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  9342. '30' => '密码错误',
  9343. '40' => '账号不存在',
  9344. '41' => '余额不足',
  9345. '42' => '帐户已过期',
  9346. '43' => 'IP地址限制',
  9347. '50' => '内容含有敏感词',
  9348. ];
  9349. $smsapi = 'http://api.smsbao.com/';
  9350. $user = 'zhuwei123';
  9351. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  9352. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  9353. $result = @file_get_contents($sendurl);
  9354. if ($result === false) {
  9355. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9356. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9357. }
  9358. $result = trim((string)$result);
  9359. if ($result !== '0') {
  9360. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9361. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9362. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9363. }
  9364. }
  9365. }