Procuremen.php 382 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161
  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 (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1341. $this->enrichProcuremenListMilestoneTimes($rows);
  1342. }
  1343. if ($wffTab === 'all' && count($rows) > 0) {
  1344. $this->mergePurchaseOrder($rows);
  1345. }
  1346. if ($wffTab === 'pick' && count($rows) > 0) {
  1347. $this->mergePurchaseOrder($rows);
  1348. }
  1349. foreach ($rows as &$rwClean) {
  1350. if (is_array($rwClean)) {
  1351. unset($rwClean['_order_merge_rows']);
  1352. if (array_key_exists('NGZL', $rwClean)) {
  1353. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1354. }
  1355. }
  1356. }
  1357. unset($rwClean);
  1358. return json([
  1359. 'total' => count($filtered),
  1360. 'rows' => $rows,
  1361. 'activeYm' => $ym,
  1362. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1363. 'filterOptions' => (
  1364. (int)$offset === 0
  1365. && !$hasActiveSearch
  1366. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1367. )
  1368. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1369. : new \stdClass(),
  1370. ]);
  1371. } catch (\Throwable $e) {
  1372. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1373. return json([
  1374. 'total' => 0,
  1375. 'rows' => [],
  1376. ]);
  1377. }
  1378. }
  1379. /**
  1380. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1381. *
  1382. * @return array<int, true>
  1383. */
  1384. protected function loadPickHiddenScydgySet(): array
  1385. {
  1386. if ($this->pickHiddenScydgySetCache !== null) {
  1387. return $this->pickHiddenScydgySetCache;
  1388. }
  1389. $hideSet = [];
  1390. try {
  1391. $poIds = Db::table('purchase_order')
  1392. ->where(function ($q) {
  1393. $q->whereIn('wflow_status', array_merge(
  1394. ProcuremenStatus::wflowPendingConfirmValues(),
  1395. ProcuremenStatus::wflowPendingApprovalValues()
  1396. ))
  1397. ->whereOr(function ($q1) {
  1398. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1399. })
  1400. ->whereOr(function ($q2) {
  1401. $q2->whereNotNull('pick_time')
  1402. ->where('pick_time', '<>', '')
  1403. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1404. })
  1405. ->whereOr(function ($q3) {
  1406. $q3->whereNotNull('mod_rq')
  1407. ->where('mod_rq', '<>', '')
  1408. ->where('mod_rq', 'not like', '0000-00-00%');
  1409. });
  1410. })
  1411. ->column('scydgy_id');
  1412. if (is_array($poIds)) {
  1413. foreach ($poIds as $pid) {
  1414. $k = (int)$pid;
  1415. if ($k !== 0) {
  1416. $hideSet[$k] = true;
  1417. }
  1418. }
  1419. }
  1420. } catch (\Throwable $e) {
  1421. }
  1422. try {
  1423. $detIdsQuery = Db::table('purchase_order_detail');
  1424. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1425. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1426. if (is_array($detIds)) {
  1427. foreach ($detIds as $pid) {
  1428. $k = (int)$pid;
  1429. if ($this->isValidScydgyRowId($k)) {
  1430. $hideSet[$k] = true;
  1431. }
  1432. }
  1433. }
  1434. } catch (\Throwable $e) {
  1435. }
  1436. $this->pickHiddenScydgySetCache = $hideSet;
  1437. return $hideSet;
  1438. }
  1439. /**
  1440. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1441. *
  1442. * @return array<int, array<string, mixed>>
  1443. */
  1444. protected function loadPickManualOrderRows(): array
  1445. {
  1446. try {
  1447. $dbRows = Db::table('purchase_order')
  1448. ->where('scydgy_id', '<', 0)
  1449. ->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%\')')
  1450. ->order('scydgy_id', 'asc')
  1451. ->select();
  1452. } catch (\Throwable $e) {
  1453. try {
  1454. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1455. } catch (\Throwable $e2) {
  1456. return [];
  1457. }
  1458. }
  1459. if (!is_array($dbRows) || $dbRows === []) {
  1460. return [];
  1461. }
  1462. $detailSidSet = [];
  1463. try {
  1464. $negIds = [];
  1465. foreach ($dbRows as $dbRow) {
  1466. if (!is_array($dbRow)) {
  1467. continue;
  1468. }
  1469. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1470. if ($sid < 0) {
  1471. $negIds[$sid] = true;
  1472. }
  1473. }
  1474. if ($negIds !== []) {
  1475. $detQuery = Db::table('purchase_order_detail')
  1476. ->where('scydgy_id', 'in', array_keys($negIds));
  1477. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1478. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1479. if (is_array($detRows)) {
  1480. foreach ($detRows as $did) {
  1481. $detailSidSet[(int)$did] = true;
  1482. }
  1483. }
  1484. }
  1485. } catch (\Throwable $e) {
  1486. }
  1487. $pool = [];
  1488. foreach ($dbRows as $dbRow) {
  1489. if (!is_array($dbRow)) {
  1490. continue;
  1491. }
  1492. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1493. if ($sid >= 0) {
  1494. continue;
  1495. }
  1496. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1497. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1498. continue;
  1499. }
  1500. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1501. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1502. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1503. continue;
  1504. }
  1505. if (isset($detailSidSet[$sid])) {
  1506. continue;
  1507. }
  1508. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1509. $r['_is_manual'] = 1;
  1510. $pool[] = $r;
  1511. }
  1512. return $pool;
  1513. }
  1514. /**
  1515. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1516. */
  1517. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1518. {
  1519. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1520. foreach ($keys as $k) {
  1521. $t = trim((string)($row[$k] ?? ''));
  1522. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1523. return $t;
  1524. }
  1525. }
  1526. return '';
  1527. }
  1528. /**
  1529. * 分配手工新增工序行 ID(负数递减)
  1530. */
  1531. protected function allocateManualScydgyId(): int
  1532. {
  1533. try {
  1534. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1535. $min = (int)$min;
  1536. return $min < 0 ? $min - 1 : -1;
  1537. } catch (\Throwable $e) {
  1538. return -1;
  1539. }
  1540. }
  1541. /**
  1542. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1543. */
  1544. protected function allocateManualOrderCcydh(): string
  1545. {
  1546. $prefix = 'YW' . date('Ymd');
  1547. $maxSeq = 0;
  1548. try {
  1549. $rows = Db::table('purchase_order')
  1550. ->where('CCYDH', 'like', $prefix . '%')
  1551. ->column('CCYDH');
  1552. if (is_array($rows)) {
  1553. foreach ($rows as $ccydh) {
  1554. $ccydh = trim((string)$ccydh);
  1555. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1556. $maxSeq = max($maxSeq, (int)$m[1]);
  1557. }
  1558. }
  1559. }
  1560. } catch (\Throwable $e) {
  1561. }
  1562. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1563. }
  1564. /**
  1565. * purchase_order.mod_rq 是否有有效软删除时间
  1566. */
  1567. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1568. {
  1569. $t = trim((string)$modRq);
  1570. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1571. }
  1572. /**
  1573. * 列表行 → purchase_order 写入字段
  1574. *
  1575. * @return array<string, mixed>
  1576. */
  1577. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1578. {
  1579. return [
  1580. 'scydgy_id' => $scydgyId,
  1581. 'CCYDH' => $row['CCYDH'] ?? null,
  1582. 'CYJMC' => $row['CYJMC'] ?? null,
  1583. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1584. 'CDXMC' => $row['CDXMC'] ?? null,
  1585. 'CGYBH' => $row['CGYBH'] ?? null,
  1586. 'CGYMC' => $row['CGYMC'] ?? null,
  1587. 'CDW' => $row['CDW'] ?? null,
  1588. 'czlyq' => $row['czlyq'] ?? null,
  1589. 'NGZL' => $row['NGZL'] ?? null,
  1590. 'CDF' => $row['CDF'] ?? null,
  1591. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1592. 'MBZ' => $row['MBZ'] ?? null,
  1593. 'bwjg' => $row['bwjg'] ?? null,
  1594. 'iStatus' => $row['iStatus'] ?? null,
  1595. 'dStamp' => $row['dStamp'] ?? null,
  1596. 'dputrecord' => $row['dputrecord'] ?? null,
  1597. 'cywyxm' => $row['cywyxm'] ?? null,
  1598. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1599. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1600. ];
  1601. }
  1602. /**
  1603. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1604. *
  1605. * @return array{po:?array<string,mixed>, hidden:bool}
  1606. */
  1607. protected function resolvePickRowPoContext(int $sid): array
  1608. {
  1609. $po = null;
  1610. try {
  1611. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1612. if (is_array($found)) {
  1613. $po = $found;
  1614. }
  1615. } catch (\Throwable $e) {
  1616. }
  1617. $hideSet = $this->loadPickHiddenScydgySet();
  1618. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1619. }
  1620. /**
  1621. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1622. */
  1623. protected function assertPickRowCanDelete(int $sid, array $row): void
  1624. {
  1625. $ctx = $this->resolvePickRowPoContext($sid);
  1626. $po = $ctx['po'];
  1627. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1628. return;
  1629. }
  1630. if (is_array($po)) {
  1631. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1632. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1633. }
  1634. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1635. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1636. }
  1637. }
  1638. if ($ctx['hidden']) {
  1639. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1640. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1641. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1642. }
  1643. }
  1644. /**
  1645. * 初选直接完结前校验
  1646. */
  1647. protected function assertPickRowCanComplete(int $sid, array $row): void
  1648. {
  1649. $ctx = $this->resolvePickRowPoContext($sid);
  1650. $po = $ctx['po'];
  1651. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1652. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1653. }
  1654. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1655. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1656. }
  1657. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1658. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1659. }
  1660. }
  1661. /**
  1662. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1663. */
  1664. protected function softDeleteProcuremenPickRow(array $row): void
  1665. {
  1666. $sid = $this->extractScydgyRowId($row);
  1667. if (!$this->isValidScydgyRowId($sid)) {
  1668. throw new \InvalidArgumentException('无效的行主键');
  1669. }
  1670. $this->assertPickRowCanDelete($sid, $row);
  1671. $po = $this->resolvePickRowPoContext($sid)['po'];
  1672. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1673. return;
  1674. }
  1675. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1676. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1677. }
  1678. $now = date('Y-m-d H:i:s');
  1679. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1680. if (is_array($exists)) {
  1681. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1682. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1683. } else {
  1684. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1685. $data['mod_rq'] = $now;
  1686. $data['createtime'] = $now;
  1687. Db::table('purchase_order')->insert($data);
  1688. $poIdLog = (int)Db::getLastInsID();
  1689. }
  1690. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1691. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1692. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1693. if ($gymcLog !== '') {
  1694. $logTail .= ' / ' . $gymcLog;
  1695. }
  1696. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1697. }
  1698. /**
  1699. * 手工新增协助工序(写入 purchase_order)
  1700. *
  1701. * @param array<string, mixed> $params
  1702. * @return int scydgy_id
  1703. */
  1704. protected function saveManualPickOrder(array $params): int
  1705. {
  1706. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1707. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1708. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1709. if ($ccydh === '') {
  1710. $ccydh = $this->allocateManualOrderCcydh();
  1711. }
  1712. $now = date('Y-m-d H:i:s');
  1713. $sid = $this->allocateManualScydgyId();
  1714. $data = [
  1715. 'scydgy_id' => $sid,
  1716. 'CCYDH' => $ccydh,
  1717. 'CYJMC' => $cyjmc,
  1718. 'CGYMC' => $cgymc,
  1719. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1720. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1721. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1722. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1723. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1724. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1725. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1726. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1727. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1728. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1729. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1730. 'createtime' => $now,
  1731. 'dStamp' => $now,
  1732. 'dputrecord' => $now,
  1733. ];
  1734. Db::table('purchase_order')->insert($data);
  1735. $poId = (int)Db::getLastInsID();
  1736. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1737. return $sid;
  1738. }
  1739. protected function formatProcuremenRowLabel(array $row): string
  1740. {
  1741. $dh = trim((string)($row['CCYDH'] ?? ''));
  1742. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1743. if ($dh !== '' && $gymc !== '') {
  1744. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1745. }
  1746. if ($dh !== '') {
  1747. return '订单「' . $dh . '」';
  1748. }
  1749. if ($gymc !== '') {
  1750. return '工序「' . $gymc . '」';
  1751. }
  1752. $id = $this->extractScydgyRowId($row);
  1753. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1754. }
  1755. /**
  1756. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1757. */
  1758. protected function extractScydgyRowId(array $row): int
  1759. {
  1760. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  1761. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  1762. return (int)$row['scydgy_id'];
  1763. }
  1764. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  1765. return (int)$row['SCYDGY_ID'];
  1766. }
  1767. return (int)($row['ID'] ?? $row['id'] ?? 0);
  1768. }
  1769. protected function isValidScydgyRowId(int $id): bool
  1770. {
  1771. return ProcuremenGuard::isValidScydgyId($id);
  1772. }
  1773. protected function isManualScydgyRowId(int $id): bool
  1774. {
  1775. return $id < 0;
  1776. }
  1777. /**
  1778. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1779. *
  1780. * @param int[] $scydgyIds
  1781. * @return array<int, string[]>
  1782. */
  1783. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1784. {
  1785. $out = [];
  1786. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1787. if ($scydgyIds === []) {
  1788. return $out;
  1789. }
  1790. try {
  1791. $rows = Db::table('purchase_order_detail')
  1792. ->where('scydgy_id', 'in', $scydgyIds)
  1793. ->field('scydgy_id,company_name')
  1794. ->order('company_name', 'asc')
  1795. ->select();
  1796. } catch (\Throwable $e) {
  1797. $rows = [];
  1798. }
  1799. if (!is_array($rows)) {
  1800. return $out;
  1801. }
  1802. foreach ($rows as $r) {
  1803. if (!is_array($r)) {
  1804. continue;
  1805. }
  1806. $sid = (int)($r['scydgy_id'] ?? 0);
  1807. $cn = trim((string)($r['company_name'] ?? ''));
  1808. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1809. continue;
  1810. }
  1811. if (!isset($out[$sid])) {
  1812. $out[$sid] = [];
  1813. }
  1814. if (!in_array($cn, $out[$sid], true)) {
  1815. $out[$sid][] = $cn;
  1816. }
  1817. }
  1818. return $out;
  1819. }
  1820. /**
  1821. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1822. *
  1823. * @param string[] $names
  1824. */
  1825. protected function formatNotifySupplierDisplay(array $names): string
  1826. {
  1827. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1828. return trim((string)$n);
  1829. }, $names))));
  1830. if ($names === []) {
  1831. return '';
  1832. }
  1833. sort($names, SORT_STRING);
  1834. return implode("\n", $names);
  1835. }
  1836. /**
  1837. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1838. *
  1839. * @param int[] $scydgyIds
  1840. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1841. */
  1842. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1843. {
  1844. $out = [];
  1845. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1846. if ($scydgyIds === []) {
  1847. return $out;
  1848. }
  1849. try {
  1850. $rows = Db::table('purchase_order_detail')
  1851. ->where('scydgy_id', 'in', $scydgyIds)
  1852. ->field('scydgy_id,company_name,amount')
  1853. ->select();
  1854. } catch (\Throwable $e) {
  1855. $rows = [];
  1856. }
  1857. if (!is_array($rows)) {
  1858. return $out;
  1859. }
  1860. foreach ($rows as $r) {
  1861. if (!is_array($r)) {
  1862. continue;
  1863. }
  1864. $sid = (int)($r['scydgy_id'] ?? 0);
  1865. $cn = trim((string)($r['company_name'] ?? ''));
  1866. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1867. continue;
  1868. }
  1869. if (!isset($out[$sid])) {
  1870. $out[$sid] = ['all' => [], 'quoted' => []];
  1871. }
  1872. $out[$sid]['all'][$cn] = true;
  1873. $am = trim((string)($r['amount'] ?? ''));
  1874. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1875. $out[$sid]['quoted'][$cn] = true;
  1876. }
  1877. }
  1878. return $out;
  1879. }
  1880. /**
  1881. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1882. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1883. */
  1884. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1885. {
  1886. $merged = ['all' => [], 'quoted' => []];
  1887. foreach ($buckets as $b) {
  1888. if (!is_array($b)) {
  1889. continue;
  1890. }
  1891. foreach ($b['all'] ?? [] as $cn => $_) {
  1892. $merged['all'][$cn] = true;
  1893. }
  1894. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1895. $merged['quoted'][$cn] = true;
  1896. }
  1897. }
  1898. return $merged;
  1899. }
  1900. /**
  1901. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1902. */
  1903. protected function formatQuotedSupplierLines(array $bucket): string
  1904. {
  1905. $all = array_keys($bucket['all'] ?? []);
  1906. if ($all === []) {
  1907. return '';
  1908. }
  1909. sort($all, SORT_STRING);
  1910. $lines = [];
  1911. foreach ($all as $cn) {
  1912. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1913. $lines[] = $cn . '(' . $status . ')';
  1914. }
  1915. return implode("\n", $lines);
  1916. }
  1917. /**
  1918. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1919. */
  1920. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1921. {
  1922. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1923. $this->view->engine->layout(false);
  1924. try {
  1925. $bodyHtml = $this->view->fetch($view);
  1926. $this->view->assign('dialogBody', $bodyHtml);
  1927. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1928. return $this->view->fetch('procuremen/dialog_lite_shell');
  1929. } finally {
  1930. if ($restoreLayout) {
  1931. $this->view->engine->layout($restoreLayout);
  1932. }
  1933. }
  1934. }
  1935. /**
  1936. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1937. */
  1938. protected function resolveBundleSysRq(array $bundle): string
  1939. {
  1940. foreach ($bundle['pos'] ?? [] as $po) {
  1941. if (!is_array($po)) {
  1942. continue;
  1943. }
  1944. $sr = trim((string)($po['sys_rq'] ?? ''));
  1945. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1946. return $sr;
  1947. }
  1948. }
  1949. return '';
  1950. }
  1951. /**
  1952. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1953. */
  1954. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1955. {
  1956. $raw = trim((string)$sysRq);
  1957. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1958. return true;
  1959. }
  1960. $ts = strtotime(str_replace('T', ' ', $raw));
  1961. if ($ts === false || $ts <= 0) {
  1962. return true;
  1963. }
  1964. return time() >= $ts;
  1965. }
  1966. /**
  1967. * 开标前校验:必须已过报价截止时间
  1968. *
  1969. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1970. */
  1971. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1972. {
  1973. $sysRq = $this->resolveBundleSysRq($bundle);
  1974. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1975. $this->error('未到招标截止日期');
  1976. }
  1977. }
  1978. /**
  1979. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1980. *
  1981. * @param array<string, mixed> $d
  1982. * @param string $deliveryYmd
  1983. */
  1984. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1985. {
  1986. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1987. return max(0, (int)$d['lead_days']);
  1988. }
  1989. if ($deliveryYmd === '') {
  1990. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1991. }
  1992. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1993. return null;
  1994. }
  1995. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1996. $t2 = strtotime($m[1] . ' 00:00:00');
  1997. if ($t1 === false || $t2 === false) {
  1998. return null;
  1999. }
  2000. return max(0, (int)round(($t2 - $t1) / 86400));
  2001. }
  2002. /**
  2003. * @param int|null $days
  2004. */
  2005. protected function formatProcuremenLeadDaysText($days): string
  2006. {
  2007. if ($days === null || $days === '') {
  2008. return '未填写';
  2009. }
  2010. if (!is_numeric($days)) {
  2011. return '未填写';
  2012. }
  2013. return ((int)$days) . '天';
  2014. }
  2015. /**
  2016. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2017. *
  2018. * @param array<string, mixed> $line
  2019. */
  2020. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2021. {
  2022. $amountFilled = !empty($line['amount_filled']);
  2023. $deliveryFilled = !empty($line['delivery_filled']);
  2024. $leadFilled = !empty($line['lead_days_filled']);
  2025. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2026. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2027. $line['amount_show'] = '';
  2028. if (array_key_exists('amount_text', $line)) {
  2029. $line['amount_text'] = $line['unit_price_text'];
  2030. }
  2031. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2032. $line['delivery_show'] = $deliveryText;
  2033. if (array_key_exists('delivery_text', $line)) {
  2034. $line['delivery_text'] = $deliveryText;
  2035. }
  2036. $line['delivery_ymd'] = '';
  2037. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2038. $line['lead_days_show'] = $leadText;
  2039. $line['lead_days_text'] = $leadText;
  2040. $line['lead_days'] = '';
  2041. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2042. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2043. $line['subtotal_num'] = null;
  2044. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2045. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2046. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2047. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2048. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2049. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2050. $line['amount_filled'] = false;
  2051. $line['delivery_filled'] = false;
  2052. $line['lead_days_filled'] = false;
  2053. $line['is_quoted'] = false;
  2054. if (array_key_exists('quote_label', $line)) {
  2055. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2056. }
  2057. }
  2058. protected function ensurePurchaseOrderBidOpenTable(): void
  2059. {
  2060. try {
  2061. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2062. } catch (\Throwable $e) {
  2063. Db::execute(
  2064. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2065. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2066. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2067. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2068. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2069. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2070. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2071. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2072. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2073. `createtime` datetime DEFAULT NULL,
  2074. PRIMARY KEY (`id`),
  2075. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2076. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2077. );
  2078. }
  2079. }
  2080. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2081. {
  2082. $ccydh = trim($ccydh);
  2083. if ($ccydh === '') {
  2084. return false;
  2085. }
  2086. $this->ensurePurchaseOrderBidOpenTable();
  2087. try {
  2088. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2089. return is_array($row);
  2090. } catch (\Throwable $e) {
  2091. return false;
  2092. }
  2093. }
  2094. /**
  2095. * 批量查询订单是否已开标验证
  2096. *
  2097. * @param array<int, string> $ccydhs
  2098. * @return array<string, bool> ccydh => true
  2099. */
  2100. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2101. {
  2102. $set = [];
  2103. $list = [];
  2104. foreach ($ccydhs as $c) {
  2105. $c = trim((string)$c);
  2106. if ($c !== '') {
  2107. $list[$c] = true;
  2108. }
  2109. }
  2110. if ($list === []) {
  2111. return $set;
  2112. }
  2113. $this->ensurePurchaseOrderBidOpenTable();
  2114. try {
  2115. $rows = Db::table('purchase_order_bid_open')
  2116. ->where('ccydh', 'in', array_keys($list))
  2117. ->field('ccydh')
  2118. ->select();
  2119. foreach ($rows as $row) {
  2120. if (!is_array($row)) {
  2121. continue;
  2122. }
  2123. $c = trim((string)($row['ccydh'] ?? ''));
  2124. if ($c !== '') {
  2125. $set[$c] = true;
  2126. }
  2127. }
  2128. } catch (\Throwable $e) {
  2129. return [];
  2130. }
  2131. return $set;
  2132. }
  2133. /**
  2134. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2135. *
  2136. * @param array<string, mixed> $group
  2137. */
  2138. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2139. {
  2140. if ($quoteVisible) {
  2141. $group['remark_quote_pending'] = 0;
  2142. return;
  2143. }
  2144. $group['remark'] = '';
  2145. $group['remark_quote_pending'] = 0;
  2146. }
  2147. /**
  2148. * @param array{ccydh?:string} $bundle
  2149. */
  2150. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2151. {
  2152. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2153. }
  2154. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2155. {
  2156. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  2157. }
  2158. protected function loadBidOpenAdminUser(int $adminId): ?array
  2159. {
  2160. if ($adminId <= 0) {
  2161. return null;
  2162. }
  2163. try {
  2164. $row = Db::name('admin')->where('id', $adminId)->find();
  2165. } catch (\Throwable $e) {
  2166. return null;
  2167. }
  2168. if (!is_array($row)) {
  2169. return null;
  2170. }
  2171. $status = strtolower(trim((string)($row['status'] ?? '')));
  2172. if ($status !== '' && $status !== 'normal') {
  2173. return null;
  2174. }
  2175. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2176. return null;
  2177. }
  2178. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2179. if (!preg_match('/^1\d{10}$/', $phone)) {
  2180. return null;
  2181. }
  2182. $name = trim((string)($row['nickname'] ?? ''));
  2183. if ($name === '') {
  2184. $name = trim((string)($row['username'] ?? ''));
  2185. }
  2186. return [
  2187. 'id' => (int)$row['id'],
  2188. 'username' => trim((string)($row['username'] ?? '')),
  2189. 'nickname' => $name,
  2190. 'mobile' => $phone,
  2191. ];
  2192. }
  2193. /**
  2194. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2195. */
  2196. protected function bidOpenVerifierAuthGroupRootId(): int
  2197. {
  2198. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2199. return $id > 0 ? $id : 10;
  2200. }
  2201. /**
  2202. * @return int[]
  2203. */
  2204. protected function loadBidOpenVerifierAuthGroupIds(): array
  2205. {
  2206. static $memo = [];
  2207. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2208. if (isset($memo[$rootId])) {
  2209. return $memo[$rootId];
  2210. }
  2211. try {
  2212. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2213. } catch (\Throwable $e) {
  2214. $memo[$rootId] = [$rootId];
  2215. return $memo[$rootId];
  2216. }
  2217. if (!is_array($groups) || $groups === []) {
  2218. $memo[$rootId] = [$rootId];
  2219. return $memo[$rootId];
  2220. }
  2221. $groupList = [];
  2222. foreach ($groups as $g) {
  2223. if (is_array($g)) {
  2224. $groupList[] = $g;
  2225. }
  2226. }
  2227. if ($groupList === []) {
  2228. $memo[$rootId] = [$rootId];
  2229. return $memo[$rootId];
  2230. }
  2231. $tree = \fast\Tree::instance();
  2232. $tree->init($groupList);
  2233. $ids = $tree->getChildrenIds($rootId, true);
  2234. if (!is_array($ids) || $ids === []) {
  2235. $memo[$rootId] = [$rootId];
  2236. return $memo[$rootId];
  2237. }
  2238. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2239. return $memo[$rootId];
  2240. }
  2241. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2242. {
  2243. if ($adminId <= 0) {
  2244. return false;
  2245. }
  2246. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2247. if ($groupIds === []) {
  2248. return false;
  2249. }
  2250. try {
  2251. return (bool)Db::name('auth_group_access')
  2252. ->where('uid', $adminId)
  2253. ->where('group_id', 'in', $groupIds)
  2254. ->count();
  2255. } catch (\Throwable $e) {
  2256. return false;
  2257. }
  2258. }
  2259. /**
  2260. * @return array<int, array<string, mixed>>
  2261. */
  2262. protected function listBidOpenVerifierCandidates(): array
  2263. {
  2264. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2265. if ($groupIds === []) {
  2266. return [];
  2267. }
  2268. try {
  2269. $adminIds = Db::name('auth_group_access')
  2270. ->where('group_id', 'in', $groupIds)
  2271. ->column('uid');
  2272. } catch (\Throwable $e) {
  2273. $adminIds = [];
  2274. }
  2275. $adminIds = is_array($adminIds)
  2276. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2277. : [];
  2278. if ($adminIds === []) {
  2279. return [];
  2280. }
  2281. try {
  2282. $rows = Db::name('admin')
  2283. ->where('status', 'normal')
  2284. ->where('id', 'in', $adminIds)
  2285. ->where('mobile', '<>', '')
  2286. ->order('id', 'asc')
  2287. ->select();
  2288. } catch (\Throwable $e) {
  2289. return [];
  2290. }
  2291. if (!is_array($rows)) {
  2292. return [];
  2293. }
  2294. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2295. $out = [];
  2296. foreach ($rows as $row) {
  2297. if (!is_array($row)) {
  2298. continue;
  2299. }
  2300. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2301. if ($one === null) {
  2302. continue;
  2303. }
  2304. $out[] = [
  2305. 'id' => $one['id'],
  2306. 'username' => $one['username'],
  2307. 'nickname' => $one['nickname'],
  2308. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2309. 'mobile' => mask_phone($one['mobile']),
  2310. ];
  2311. }
  2312. return $out;
  2313. }
  2314. /**
  2315. * @param int[] $adminIds
  2316. * @return array<int, string>
  2317. */
  2318. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2319. {
  2320. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2321. if ($adminIds === []) {
  2322. return [];
  2323. }
  2324. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2325. try {
  2326. $rows = Db::name('auth_group_access')
  2327. ->alias('aga')
  2328. ->join('auth_group ag', 'aga.group_id = ag.id')
  2329. ->where('aga.uid', 'in', $adminIds)
  2330. ->where('aga.group_id', 'in', $groupIds)
  2331. ->field('aga.uid,ag.name')
  2332. ->order('aga.uid', 'asc')
  2333. ->order('aga.group_id', 'asc')
  2334. ->select();
  2335. } catch (\Throwable $e) {
  2336. return [];
  2337. }
  2338. if (!is_array($rows)) {
  2339. return [];
  2340. }
  2341. $out = [];
  2342. foreach ($rows as $row) {
  2343. if (!is_array($row)) {
  2344. continue;
  2345. }
  2346. $uid = (int)($row['uid'] ?? 0);
  2347. $name = trim((string)($row['name'] ?? ''));
  2348. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2349. continue;
  2350. }
  2351. $out[$uid] = $name;
  2352. }
  2353. return $out;
  2354. }
  2355. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2356. {
  2357. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2358. }
  2359. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2360. {
  2361. return 'procuremen_bidopen_wait_' . $adminId;
  2362. }
  2363. protected function renderBidOpenVerifySms(string $code): string
  2364. {
  2365. $tpl = '';
  2366. try {
  2367. $row = $this->loadNotifyTemplateRow('bid_open');
  2368. if (is_array($row)) {
  2369. $tpl = trim((string)($row['content'] ?? ''));
  2370. }
  2371. } catch (\Throwable $e) {
  2372. $tpl = '';
  2373. }
  2374. if ($tpl === '') {
  2375. $tpl = '【可集达】您的短信验证码是{code}';
  2376. }
  2377. return str_replace('{code}', $code, $tpl);
  2378. }
  2379. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2380. {
  2381. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2382. }
  2383. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2384. {
  2385. $code = trim($code);
  2386. if (!preg_match('/^\d{6}$/', $code)) {
  2387. return false;
  2388. }
  2389. $mock = Config::get('mproc.mock_sms_code');
  2390. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2391. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2392. return true;
  2393. }
  2394. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2395. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2396. return false;
  2397. }
  2398. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2399. return true;
  2400. }
  2401. /**
  2402. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2403. */
  2404. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2405. {
  2406. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2407. if ($ccydh === '') {
  2408. throw new \InvalidArgumentException('订单号无效');
  2409. }
  2410. $this->ensurePurchaseOrderBidOpenTable();
  2411. list($operatorId, $operatorName) = $this->GetUseName();
  2412. $now = date('Y-m-d H:i:s');
  2413. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2414. $payload = [
  2415. 'ccydh' => $ccydh,
  2416. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2417. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2418. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2419. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2420. 'operator_id' => (int)$operatorId,
  2421. 'operator_name' => trim((string)$operatorName),
  2422. 'createtime' => $now,
  2423. ];
  2424. if (is_array($exists)) {
  2425. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2426. } else {
  2427. Db::table('purchase_order_bid_open')->insert($payload);
  2428. }
  2429. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2430. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2431. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  2432. (int)$payload['verifier1_id'],
  2433. (int)$payload['verifier2_id'],
  2434. ]);
  2435. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  2436. $name1 = $labelMap[(int)$payload['verifier1_id']];
  2437. }
  2438. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  2439. $name2 = $labelMap[(int)$payload['verifier2_id']];
  2440. }
  2441. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  2442. $seenSid = [];
  2443. foreach ($bundle['pos'] ?? [] as $poRow) {
  2444. if (!is_array($poRow)) {
  2445. continue;
  2446. }
  2447. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2448. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2449. continue;
  2450. }
  2451. $seenSid[$sid] = true;
  2452. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2453. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2454. }
  2455. if ($seenSid === []) {
  2456. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2457. if ($this->isValidScydgyRowId($anchor)) {
  2458. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2459. }
  2460. }
  2461. // 开标通过后计算并写入供应商服务评分
  2462. try {
  2463. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  2464. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  2465. } catch (\Throwable $e) {
  2466. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  2467. }
  2468. }
  2469. /**
  2470. * 报价行展示字段默认值(模板安全访问)
  2471. *
  2472. * @param array<string, mixed> $line
  2473. * @return array<string, mixed>
  2474. */
  2475. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2476. {
  2477. if (!array_key_exists('amount_quote_pending', $line)) {
  2478. $line['amount_quote_pending'] = 0;
  2479. }
  2480. if (!array_key_exists('delivery_quote_pending', $line)) {
  2481. $line['delivery_quote_pending'] = 0;
  2482. }
  2483. if (!array_key_exists('quote_before_deadline', $line)) {
  2484. $line['quote_before_deadline'] = 0;
  2485. }
  2486. if (!array_key_exists('amount_filled', $line)) {
  2487. $line['amount_filled'] = 0;
  2488. }
  2489. if (!array_key_exists('delivery_filled', $line)) {
  2490. $line['delivery_filled'] = 0;
  2491. }
  2492. if (!array_key_exists('lead_days_filled', $line)) {
  2493. $line['lead_days_filled'] = 0;
  2494. }
  2495. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2496. $line['lead_days_quote_pending'] = 0;
  2497. }
  2498. if (!array_key_exists('lead_days_show', $line)) {
  2499. $line['lead_days_show'] = '未填写';
  2500. }
  2501. if (!array_key_exists('lead_days_text', $line)) {
  2502. $line['lead_days_text'] = $line['lead_days_show'];
  2503. }
  2504. return $line;
  2505. }
  2506. /**
  2507. * 审核弹窗:按供应商汇总报价明细
  2508. *
  2509. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2510. * @return array<int, array<string, mixed>>
  2511. */
  2512. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2513. {
  2514. $sids = [];
  2515. foreach ($bundle['pos'] ?? [] as $po) {
  2516. if (!is_array($po)) {
  2517. continue;
  2518. }
  2519. $sid = (int)($po['scydgy_id'] ?? 0);
  2520. if ($this->isValidScydgyRowId($sid)) {
  2521. $sids[$sid] = true;
  2522. }
  2523. }
  2524. if ($sids === []) {
  2525. return [];
  2526. }
  2527. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2528. $gymcMap = [];
  2529. $qtyBySid = [];
  2530. $orderedSids = [];
  2531. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2532. if (!is_array($mr)) {
  2533. continue;
  2534. }
  2535. $gid = $this->extractScydgyRowId($mr);
  2536. if ($this->isValidScydgyRowId($gid)) {
  2537. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2538. $orderedSids[] = $gid;
  2539. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2540. if ($qty === '') {
  2541. $qty = trim((string)($mr['NGZL'] ?? ''));
  2542. }
  2543. $qtyBySid[$gid] = $qty;
  2544. }
  2545. }
  2546. foreach ($bundle['pos'] ?? [] as $po) {
  2547. if (!is_array($po)) {
  2548. continue;
  2549. }
  2550. $gid = (int)($po['scydgy_id'] ?? 0);
  2551. if ($this->isValidScydgyRowId($gid)) {
  2552. $nm = trim((string)($po['CGYMC'] ?? ''));
  2553. if ($nm !== '') {
  2554. $gymcMap[$gid] = $nm;
  2555. }
  2556. if (!in_array($gid, $orderedSids, true)) {
  2557. $orderedSids[] = $gid;
  2558. }
  2559. }
  2560. }
  2561. try {
  2562. $detailsQuery = Db::table('purchase_order_detail')
  2563. ->where('scydgy_id', 'in', array_keys($sids));
  2564. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2565. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2566. } catch (\Throwable $e) {
  2567. try {
  2568. $detailsQuery = Db::table('purchase_order_detail')
  2569. ->where('scydgy_id', 'in', array_keys($sids));
  2570. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2571. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2572. } catch (\Throwable $e2) {
  2573. $details = [];
  2574. }
  2575. }
  2576. if (!is_array($details)) {
  2577. $details = [];
  2578. }
  2579. $byCompany = [];
  2580. foreach ($details as $d) {
  2581. if (!is_array($d)) {
  2582. continue;
  2583. }
  2584. $cn = trim((string)($d['company_name'] ?? ''));
  2585. if ($cn === '') {
  2586. continue;
  2587. }
  2588. if (!isset($byCompany[$cn])) {
  2589. $ph = trim((string)($d['phone'] ?? ''));
  2590. $username = trim((string)($d['username'] ?? ''));
  2591. if ($username === '') {
  2592. $username = $this->resolveCustomerContactName($ph, $cn);
  2593. }
  2594. $byCompany[$cn] = [
  2595. 'name' => $cn,
  2596. 'email' => trim((string)($d['email'] ?? '')),
  2597. 'phone' => $ph,
  2598. 'username' => $username,
  2599. 'remark' => '',
  2600. 'has_quote' => false,
  2601. 'lines_map' => [],
  2602. ];
  2603. }
  2604. if ($byCompany[$cn]['remark'] === '') {
  2605. $rm = '';
  2606. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2607. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2608. $rm = trim((string)$d[$rk]);
  2609. break;
  2610. }
  2611. }
  2612. if ($rm !== '') {
  2613. $byCompany[$cn]['remark'] = $rm;
  2614. }
  2615. }
  2616. $sid = (int)($d['scydgy_id'] ?? 0);
  2617. $am = trim((string)($d['amount'] ?? ''));
  2618. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2619. if ($gymc === '') {
  2620. $gymc = '工序';
  2621. }
  2622. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2623. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2624. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2625. $deliveryShow = $deliveryRaw;
  2626. }
  2627. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2628. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2629. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2630. $subtotal = null;
  2631. if ($amountNum !== null) {
  2632. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2633. }
  2634. $unitPriceText = $amountFilled
  2635. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2636. : '未填写';
  2637. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2638. $leadFilled = ($leadDays !== null);
  2639. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2640. $lineRow = [
  2641. 'cgymc' => $gymc,
  2642. 'amount' => $am,
  2643. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2644. 'amount_filled' => $amountFilled,
  2645. 'unit_price_text' => $unitPriceText,
  2646. 'delivery' => $deliveryRaw,
  2647. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2648. 'delivery_filled' => $deliveryFilled,
  2649. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2650. 'lead_days' => $leadFilled ? $leadDays : '',
  2651. 'lead_days_filled'=> $leadFilled,
  2652. 'lead_days_show' => $leadText,
  2653. 'lead_days_text' => $leadText,
  2654. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2655. 'subtotal_num' => $subtotal,
  2656. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2657. 'is_quoted' => $amountFilled,
  2658. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2659. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2660. ];
  2661. if (!$quoteVisible) {
  2662. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2663. }
  2664. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2665. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2666. }
  2667. foreach ($byCompany as $cn => $g) {
  2668. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2669. $lines = [];
  2670. $usedSids = [];
  2671. foreach ($orderedSids as $sid) {
  2672. if (!isset($linesMap[$sid])) {
  2673. continue;
  2674. }
  2675. $lines[] = $linesMap[$sid];
  2676. $usedSids[$sid] = true;
  2677. }
  2678. foreach ($linesMap as $sid => $ln) {
  2679. if (isset($usedSids[$sid])) {
  2680. continue;
  2681. }
  2682. $lines[] = $ln;
  2683. }
  2684. $total = count($lines);
  2685. $quoted = 0;
  2686. $groupTotal = 0.0;
  2687. $groupHasTotal = false;
  2688. if ($quoteVisible) {
  2689. foreach ($lines as $ln) {
  2690. $am = trim((string)($ln['amount'] ?? ''));
  2691. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2692. $quoted++;
  2693. }
  2694. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2695. $groupTotal += (float)$ln['subtotal_num'];
  2696. $groupHasTotal = true;
  2697. }
  2698. }
  2699. }
  2700. unset($byCompany[$cn]['lines_map']);
  2701. $byCompany[$cn]['lines'] = $lines;
  2702. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2703. $byCompany[$cn]['line_count'] = $total;
  2704. $byCompany[$cn]['has_total'] = $total > 0;
  2705. $byCompany[$cn]['has_remark'] = $total > 0;
  2706. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2707. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2708. // 工序行 + 备注行 + 总计行
  2709. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2710. }
  2711. $groups = array_values($byCompany);
  2712. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2713. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  2714. }
  2715. /**
  2716. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2717. *
  2718. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2719. * @return array<int, array<string, mixed>>
  2720. */
  2721. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2722. {
  2723. $sids = [];
  2724. $poIdMap = [];
  2725. foreach ($bundle['pos'] ?? [] as $po) {
  2726. if (!is_array($po)) {
  2727. continue;
  2728. }
  2729. $sid = (int)($po['scydgy_id'] ?? 0);
  2730. if ($this->isValidScydgyRowId($sid)) {
  2731. $sids[$sid] = true;
  2732. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2733. }
  2734. }
  2735. if ($sids === []) {
  2736. return [];
  2737. }
  2738. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2739. $gymcMap = [];
  2740. $qtyBySid = [];
  2741. $orderedSids = [];
  2742. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2743. if (!is_array($mr)) {
  2744. continue;
  2745. }
  2746. $gid = $this->extractScydgyRowId($mr);
  2747. if ($this->isValidScydgyRowId($gid)) {
  2748. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2749. $orderedSids[] = $gid;
  2750. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2751. if ($qty === '') {
  2752. $qty = trim((string)($mr['NGZL'] ?? ''));
  2753. }
  2754. $qtyBySid[$gid] = $qty;
  2755. }
  2756. }
  2757. foreach ($bundle['pos'] ?? [] as $po) {
  2758. if (!is_array($po)) {
  2759. continue;
  2760. }
  2761. $gid = (int)($po['scydgy_id'] ?? 0);
  2762. if ($this->isValidScydgyRowId($gid)) {
  2763. $nm = trim((string)($po['CGYMC'] ?? ''));
  2764. if ($nm !== '') {
  2765. $gymcMap[$gid] = $nm;
  2766. }
  2767. }
  2768. }
  2769. try {
  2770. $details = Db::table('purchase_order_detail')
  2771. ->where('scydgy_id', 'in', array_keys($sids))
  2772. ->order('company_name', 'asc')
  2773. ->order('id', 'asc')
  2774. ->select();
  2775. } catch (\Throwable $e) {
  2776. try {
  2777. $details = Db::table('purchase_order_detail')
  2778. ->where('scydgy_id', 'in', array_keys($sids))
  2779. ->order('company_name', 'asc')
  2780. ->order('ID', 'asc')
  2781. ->select();
  2782. } catch (\Throwable $e2) {
  2783. $details = [];
  2784. }
  2785. }
  2786. if (!is_array($details)) {
  2787. $details = [];
  2788. }
  2789. $byCompany = [];
  2790. foreach ($details as $d) {
  2791. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2792. continue;
  2793. }
  2794. $cn = trim((string)($d['company_name'] ?? ''));
  2795. if ($cn === '') {
  2796. continue;
  2797. }
  2798. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2799. $sid = (int)($d['scydgy_id'] ?? 0);
  2800. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2801. continue;
  2802. }
  2803. if (!isset($byCompany[$cn])) {
  2804. $ph = trim((string)($d['phone'] ?? ''));
  2805. $username = trim((string)($d['username'] ?? ''));
  2806. if ($username === '') {
  2807. $username = $this->resolveCustomerContactName($ph, $cn);
  2808. }
  2809. $byCompany[$cn] = [
  2810. 'name' => $cn,
  2811. 'email' => trim((string)($d['email'] ?? '')),
  2812. 'phone' => $ph,
  2813. 'username' => $username,
  2814. 'remark' => '',
  2815. 'pick_lines' => [],
  2816. 'detail_picks' => [],
  2817. ];
  2818. }
  2819. if ($byCompany[$cn]['remark'] === '') {
  2820. $rm = '';
  2821. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2822. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2823. $rm = trim((string)$d[$rk]);
  2824. break;
  2825. }
  2826. }
  2827. if ($rm !== '') {
  2828. $byCompany[$cn]['remark'] = $rm;
  2829. }
  2830. }
  2831. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2832. if ($gymc === '') {
  2833. $gymc = '工序';
  2834. }
  2835. $am = trim((string)($d['amount'] ?? ''));
  2836. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2837. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2838. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2839. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2840. $deliveryShow = $deliveryRaw;
  2841. }
  2842. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2843. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2844. $subtotal = null;
  2845. if ($amountNum !== null) {
  2846. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2847. }
  2848. $unitPriceText = $amountFilled
  2849. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2850. : '未填写';
  2851. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2852. $leadFilled = ($leadDays !== null);
  2853. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2854. $pickLine = [
  2855. 'cgymc' => $gymc,
  2856. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  2857. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2858. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2859. 'amount_filled' => $amountFilled,
  2860. 'delivery_filled' => $deliveryFilled,
  2861. 'unit_price_text' => $unitPriceText,
  2862. 'lead_days' => $leadFilled ? $leadDays : '',
  2863. 'lead_days_filled'=> $leadFilled,
  2864. 'lead_days_show' => $leadText,
  2865. 'lead_days_text' => $leadText,
  2866. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2867. 'subtotal_num' => $subtotal,
  2868. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2869. 'is_quoted' => $amountFilled,
  2870. ];
  2871. if (!$quoteVisible) {
  2872. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2873. }
  2874. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2875. $byCompany[$cn]['detail_picks'][$sid] = [
  2876. 'scydgy_id' => $sid,
  2877. 'detail_id' => $detailId,
  2878. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2879. 'cgymc' => $gymc,
  2880. ];
  2881. }
  2882. $out = [];
  2883. foreach ($byCompany as $g) {
  2884. $pickLinesMap = $g['pick_lines'] ?? [];
  2885. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2886. continue;
  2887. }
  2888. $pickLines = [];
  2889. $usedLineSids = [];
  2890. foreach ($orderedSids as $sid) {
  2891. if (!isset($pickLinesMap[$sid])) {
  2892. continue;
  2893. }
  2894. $pickLines[] = $pickLinesMap[$sid];
  2895. $usedLineSids[$sid] = true;
  2896. }
  2897. foreach ($pickLinesMap as $sid => $ln) {
  2898. if (isset($usedLineSids[$sid])) {
  2899. continue;
  2900. }
  2901. $pickLines[] = $ln;
  2902. }
  2903. $groupTotal = 0.0;
  2904. $groupHasTotal = false;
  2905. if ($quoteVisible) {
  2906. foreach ($pickLines as $ln) {
  2907. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2908. $groupTotal += (float)$ln['subtotal_num'];
  2909. $groupHasTotal = true;
  2910. }
  2911. }
  2912. }
  2913. $lineCount = count($pickLines);
  2914. $g['pick_lines'] = $pickLines;
  2915. $g['line_count'] = $lineCount;
  2916. $g['has_total'] = $lineCount > 0;
  2917. $g['has_remark'] = $lineCount > 0;
  2918. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2919. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2920. // 工序行 + 备注行 + 总计行
  2921. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2922. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2923. $detailPicks = [];
  2924. $usedPickSids = [];
  2925. foreach ($orderedSids as $sid) {
  2926. if (!isset($detailPicksMap[$sid])) {
  2927. continue;
  2928. }
  2929. $detailPicks[] = $detailPicksMap[$sid];
  2930. $usedPickSids[$sid] = true;
  2931. }
  2932. foreach ($detailPicksMap as $sid => $dp) {
  2933. if (isset($usedPickSids[$sid])) {
  2934. continue;
  2935. }
  2936. $detailPicks[] = $dp;
  2937. }
  2938. $g['detail_picks'] = $detailPicks;
  2939. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2940. unset($g['detail_picks']);
  2941. $out[] = $g;
  2942. }
  2943. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2944. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  2945. }
  2946. /**
  2947. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2948. * @return array<int, int[]> scydgy_id => detail_id[]
  2949. */
  2950. protected function mapDetailIdsByScydgyId(array $details): array
  2951. {
  2952. $out = [];
  2953. foreach ($details as $d) {
  2954. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2955. continue;
  2956. }
  2957. $sid = (int)($d['scydgy_id'] ?? 0);
  2958. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2959. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2960. continue;
  2961. }
  2962. if (!isset($out[$sid])) {
  2963. $out[$sid] = [];
  2964. }
  2965. $out[$sid][] = $pk;
  2966. }
  2967. foreach ($out as $sid => $ids) {
  2968. $out[$sid] = array_values(array_unique($ids));
  2969. }
  2970. return $out;
  2971. }
  2972. /**
  2973. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2974. *
  2975. * @param array<string, mixed> $dbRow
  2976. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2977. */
  2978. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2979. {
  2980. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2981. $r = [
  2982. 'ID' => $sid,
  2983. 'scydgy_id' => $sid,
  2984. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2985. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2986. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2987. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2988. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2989. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2990. 'CDW' => $dbRow['CDW'] ?? '',
  2991. 'czlyq' => $dbRow['czlyq'] ?? '',
  2992. 'NGZL' => $dbRow['NGZL'] ?? '',
  2993. 'CDF' => $dbRow['CDF'] ?? '',
  2994. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2995. 'MBZ' => $dbRow['MBZ'] ?? '',
  2996. 'bwjg' => $dbRow['bwjg'] ?? '',
  2997. 'iStatus' => $dbRow['iStatus'] ?? '',
  2998. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2999. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3000. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3001. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3002. 'dStamp' => $dbRow['dStamp'] ?? '',
  3003. 'pick_time' => $dbRow['pick_time'] ?? '',
  3004. ];
  3005. if ($sid > 0 && isset($dStampMap[$sid])) {
  3006. $t = trim((string)$dStampMap[$sid]);
  3007. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3008. $r['dStamp'] = $dStampMap[$sid];
  3009. }
  3010. }
  3011. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3012. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3013. $ct = $dbRow['createtime'];
  3014. if (is_numeric($ct) && (int)$ct > 946684800) {
  3015. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3016. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3017. $r['dStamp'] = trim($ct);
  3018. }
  3019. }
  3020. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3021. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3022. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3023. $fallback = trim((string)($r['dStamp'] ?? ''));
  3024. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3025. $r['dputrecord'] = $fallback;
  3026. }
  3027. }
  3028. if (array_key_exists('id', $dbRow)) {
  3029. $r['purchase_order_id'] = (int)$dbRow['id'];
  3030. }
  3031. if ($sid < 0) {
  3032. $r['_is_manual'] = 1;
  3033. }
  3034. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3035. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3036. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3037. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3038. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3039. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3040. $r['pick_time'] = $pickFallback;
  3041. break;
  3042. }
  3043. }
  3044. }
  3045. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3046. if ($pickNm !== '') {
  3047. $r['pick_company_name'] = $pickNm;
  3048. $r['picked_supplier_name'] = $pickNm;
  3049. }
  3050. return $r;
  3051. }
  3052. /**
  3053. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3054. *
  3055. * @return array<int, array<string, mixed>>
  3056. */
  3057. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3058. {
  3059. $pool = [];
  3060. if (!is_array($dbRows) || $dbRows === []) {
  3061. return $pool;
  3062. }
  3063. $dStampMap = [];
  3064. $sidList = [];
  3065. foreach ($dbRows as $tmpRow) {
  3066. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3067. $sid = (int)$tmpRow['scydgy_id'];
  3068. if ($sid > 0) {
  3069. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3070. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3071. $sidList[$sid] = true;
  3072. }
  3073. }
  3074. }
  3075. }
  3076. if ($sidList !== []) {
  3077. try {
  3078. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3079. } catch (\Throwable $e) {
  3080. $dStampMap = [];
  3081. }
  3082. }
  3083. foreach ($dbRows as $dbRow) {
  3084. if (!is_array($dbRow)) {
  3085. continue;
  3086. }
  3087. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3088. }
  3089. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3090. $needCcydh = [];
  3091. foreach ($pool as $row) {
  3092. if (!is_array($row)) {
  3093. continue;
  3094. }
  3095. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3096. continue;
  3097. }
  3098. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3099. if ($ccydh !== '') {
  3100. $needCcydh[$ccydh] = true;
  3101. }
  3102. }
  3103. if ($needCcydh !== []) {
  3104. $czMap = [];
  3105. try {
  3106. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3107. } catch (\Throwable $e) {
  3108. $czMap = [];
  3109. }
  3110. if (is_array($czMap) && $czMap !== []) {
  3111. foreach ($pool as &$row) {
  3112. if (!is_array($row)) {
  3113. continue;
  3114. }
  3115. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3116. continue;
  3117. }
  3118. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3119. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3120. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3121. }
  3122. }
  3123. unset($row);
  3124. }
  3125. }
  3126. return $pool;
  3127. }
  3128. /**
  3129. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3130. *
  3131. * @param int[] $scydgyIds
  3132. * @return array<int, array<string, mixed>>
  3133. */
  3134. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3135. {
  3136. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3137. if ($scydgyIds === []) {
  3138. return [];
  3139. }
  3140. try {
  3141. $list = Db::table('purchase_order_detail')
  3142. ->where('scydgy_id', 'in', $scydgyIds)
  3143. ->field('scydgy_id,company_name,amount,delivery')
  3144. ->select();
  3145. } catch (\Throwable $e) {
  3146. $list = [];
  3147. }
  3148. return is_array($list) ? $list : [];
  3149. }
  3150. /**
  3151. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3152. *
  3153. * @param int[] $scydgyIds
  3154. * @param array<int, array<string, mixed>> $allRows
  3155. * @return array{cnt:int, amt:int, deliv:int}
  3156. */
  3157. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3158. {
  3159. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3160. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3161. if ($scydgyIds === [] || $allRows === []) {
  3162. return $out;
  3163. }
  3164. $idSet = array_flip($scydgyIds);
  3165. $all = [];
  3166. $withAmt = [];
  3167. $withDeliv = [];
  3168. foreach ($allRows as $r) {
  3169. if (!is_array($r)) {
  3170. continue;
  3171. }
  3172. $sid = (int)($r['scydgy_id'] ?? 0);
  3173. if (!isset($idSet[$sid])) {
  3174. continue;
  3175. }
  3176. $cn = trim((string)($r['company_name'] ?? ''));
  3177. if ($cn === '') {
  3178. continue;
  3179. }
  3180. $all[$cn] = true;
  3181. $am = $r['amount'] ?? null;
  3182. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3183. $withAmt[$cn] = true;
  3184. }
  3185. $dv = $r['delivery'] ?? null;
  3186. if ($dv !== null && trim((string)$dv) !== '') {
  3187. $withDeliv[$cn] = true;
  3188. }
  3189. }
  3190. return [
  3191. 'cnt' => count($all),
  3192. 'amt' => count($withAmt),
  3193. 'deliv' => count($withDeliv),
  3194. ];
  3195. }
  3196. /**
  3197. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  3198. *
  3199. * @param int[] $scydgyIds
  3200. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  3201. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  3202. */
  3203. protected function OrderDetailSummary(array $scydgyIds)
  3204. {
  3205. $out = [];
  3206. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3207. if ($scydgyIds === []) {
  3208. return $out;
  3209. }
  3210. $list = [];
  3211. try {
  3212. $list = Db::table('purchase_order_detail')
  3213. ->where('scydgy_id', 'in', $scydgyIds)
  3214. ->field('id,scydgy_id,amount,delivery')
  3215. ->select();
  3216. } catch (\Throwable $e) {
  3217. $list = [];
  3218. }
  3219. if (!is_array($list)) {
  3220. return $out;
  3221. }
  3222. foreach ($list as $r) {
  3223. if (!is_array($r)) {
  3224. continue;
  3225. }
  3226. $ids = (int)($r['scydgy_id'] ?? 0);
  3227. if (!$this->isValidScydgyRowId($ids)) {
  3228. continue;
  3229. }
  3230. if (!isset($out[$ids])) {
  3231. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3232. }
  3233. $out[$ids]['cnt']++;
  3234. $am = $r['amount'] ?? null;
  3235. if ($am !== null && $am !== '') {
  3236. if (!(is_string($am) && trim($am) === '')) {
  3237. $out[$ids]['amt']++;
  3238. }
  3239. }
  3240. $dv = $r['delivery'] ?? null;
  3241. if ($dv !== null && trim((string)$dv) !== '') {
  3242. $out[$ids]['deliv']++;
  3243. }
  3244. }
  3245. return $out;
  3246. }
  3247. /**
  3248. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3249. *
  3250. * @return array
  3251. */
  3252. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3253. {
  3254. $strContains = function ($haystack, $needle) {
  3255. if ($needle === '') {
  3256. return false;
  3257. }
  3258. $haystack = (string)$haystack;
  3259. if (function_exists('mb_stripos')) {
  3260. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3261. }
  3262. return stripos($haystack, $needle) !== false;
  3263. };
  3264. $stripAlias = function ($f) {
  3265. return preg_replace('/^[ab]\./i', '', (string)$f);
  3266. };
  3267. $searchColNames = [];
  3268. foreach (explode(',', $this->searchFields) as $colRaw) {
  3269. $c = $stripAlias(trim($colRaw));
  3270. if ($c !== '') {
  3271. $searchColNames[] = $c;
  3272. }
  3273. }
  3274. // 等值条件先行(表头下拉),减少后续日期解析量
  3275. $eqFilters = [];
  3276. $otherFilters = [];
  3277. foreach ($filterArr as $fk => $fv) {
  3278. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3279. continue;
  3280. }
  3281. if (is_array($fv)) {
  3282. continue;
  3283. }
  3284. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3285. continue;
  3286. }
  3287. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3288. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3289. $field = $stripAlias($fk);
  3290. if ($sym === '=' || $sym === '') {
  3291. $eqFilters[$field] = trim((string)$fv);
  3292. } else {
  3293. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  3294. }
  3295. }
  3296. $ymTarget = '';
  3297. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  3298. $ymTarget = $ymM[1];
  3299. }
  3300. $filtered = [];
  3301. foreach ($pool as $r) {
  3302. if (!is_array($r)) {
  3303. continue;
  3304. }
  3305. foreach ($eqFilters as $field => $fv) {
  3306. if (trim((string)($r[$field] ?? '')) !== $fv) {
  3307. continue 2;
  3308. }
  3309. }
  3310. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3311. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3312. if (!$isManual) {
  3313. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3314. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3315. continue;
  3316. }
  3317. if ($applyMonthRange) {
  3318. $mo = (int)$m[2];
  3319. if ($mo < 1 || $mo > 12) {
  3320. continue;
  3321. }
  3322. if ($ymTarget !== '') {
  3323. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3324. if ($ymRow !== $ymTarget) {
  3325. continue;
  3326. }
  3327. } else {
  3328. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3329. $rowMonthStart = $ymRow . '-01 00:00:00';
  3330. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3331. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3332. continue;
  3333. }
  3334. }
  3335. }
  3336. } elseif ($applyMonthRange) {
  3337. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3338. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3339. $ds = $listTime;
  3340. }
  3341. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3342. continue;
  3343. }
  3344. $mo = (int)$m[2];
  3345. if ($mo < 1 || $mo > 12) {
  3346. continue;
  3347. }
  3348. if ($ymTarget !== '') {
  3349. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3350. if ($ymRow !== $ymTarget) {
  3351. continue;
  3352. }
  3353. } else {
  3354. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3355. $rowMonthStart = $ymRow . '-01 00:00:00';
  3356. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3357. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3358. continue;
  3359. }
  3360. }
  3361. }
  3362. if ($search !== '') {
  3363. $hitSearch = false;
  3364. foreach ($searchColNames as $c) {
  3365. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3366. if ($cell !== '' && $strContains($cell, $search)) {
  3367. $hitSearch = true;
  3368. break;
  3369. }
  3370. }
  3371. if (!$hitSearch) {
  3372. continue;
  3373. }
  3374. }
  3375. foreach ($otherFilters as $item) {
  3376. $fv = $item['fv'];
  3377. $sym = $item['sym'];
  3378. $field = $item['field'];
  3379. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3380. $cellStr = trim((string)$cell);
  3381. switch ($sym) {
  3382. case '<>':
  3383. if ((string)$cell === (string)$fv) {
  3384. continue 3;
  3385. }
  3386. break;
  3387. case 'LIKE':
  3388. case 'NOT LIKE':
  3389. $needle = trim((string)$fv);
  3390. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3391. if ($sym === 'LIKE' && !$hit) {
  3392. continue 3;
  3393. }
  3394. if ($sym === 'NOT LIKE' && $hit) {
  3395. continue 3;
  3396. }
  3397. break;
  3398. case 'BETWEEN':
  3399. case 'RANGE':
  3400. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  3401. if (count($parts) < 2) {
  3402. $parts = is_string($fv) ? explode(',', $fv) : [];
  3403. }
  3404. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  3405. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  3406. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  3407. continue 3;
  3408. }
  3409. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  3410. continue 3;
  3411. }
  3412. break;
  3413. case '>':
  3414. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  3415. continue 3;
  3416. }
  3417. break;
  3418. case '>=':
  3419. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  3420. continue 3;
  3421. }
  3422. break;
  3423. case '<':
  3424. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  3425. continue 3;
  3426. }
  3427. break;
  3428. case '<=':
  3429. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  3430. continue 3;
  3431. }
  3432. break;
  3433. default:
  3434. if ((string)$cell !== (string)$fv) {
  3435. continue 3;
  3436. }
  3437. break;
  3438. }
  3439. }
  3440. $filtered[] = $r;
  3441. }
  3442. return $filtered;
  3443. }
  3444. /**
  3445. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3446. */
  3447. public function snapshotToProcure()
  3448. {
  3449. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3450. $this->error(__('Invalid parameters'));
  3451. }
  3452. $row = json_decode($this->request->post('row_json', ''), true);
  3453. if (!is_array($row)) {
  3454. $this->error(__('Invalid parameters'));
  3455. }
  3456. try {
  3457. $ids = $this->extractScydgyRowId($row);
  3458. if (!$this->isValidScydgyRowId($ids)) {
  3459. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3460. }
  3461. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3462. $data = [
  3463. 'scydgy_id' => $ids,
  3464. 'CCYDH' => $row['CCYDH'] ?? null,
  3465. 'CYJMC' => $row['CYJMC'] ?? null,
  3466. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3467. 'CDXMC' => $row['CDXMC'] ?? null,
  3468. 'CGYBH' => $row['CGYBH'] ?? null,
  3469. 'CGYMC' => $row['CGYMC'] ?? null,
  3470. 'CDW' => $row['CDW'] ?? null,
  3471. 'czlyq' => $row['czlyq'] ?? null,
  3472. 'NGZL' => $row['NGZL'] ?? null,
  3473. 'CDF' => $row['CDF'] ?? null,
  3474. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3475. 'MBZ' => $row['MBZ'] ?? null,
  3476. 'bwjg' => $row['bwjg'] ?? null,
  3477. 'iStatus' => $row['iStatus'] ?? null,
  3478. 'dStamp' => $row['dStamp'] ?? null,
  3479. 'dputrecord' => $row['dputrecord'] ?? null,
  3480. 'cywyxm' => $row['cywyxm'] ?? null,
  3481. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3482. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3483. ];
  3484. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3485. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3486. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3487. $this->success('操作成功');
  3488. return;
  3489. }
  3490. if ($exists) {
  3491. $upd = $data;
  3492. unset($upd['scydgy_id'], $upd['status']);
  3493. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3494. } else {
  3495. // 新增:不写 status(空/走库默认);仅写创建时间
  3496. $data['createtime'] = date('Y-m-d H:i:s');
  3497. Db::table('purchase_order')->insert($data);
  3498. }
  3499. } catch (\Throwable $e) {
  3500. $this->error($e->getMessage());
  3501. }
  3502. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3503. $this->success('操作成功');
  3504. }
  3505. /**
  3506. * 未发列表
  3507. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3508. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3509. */
  3510. public function completeDirectly()
  3511. {
  3512. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3513. $this->error(__('参数错误'));
  3514. }
  3515. if (!$this->procuremenCanComplete()) {
  3516. $this->error(__('You have no permission'));
  3517. }
  3518. $row = json_decode($this->request->post('row_json', ''), true);
  3519. if (!is_array($row)) {
  3520. $this->error(__('Invalid parameters'));
  3521. }
  3522. $finishRaw = $this->request->post('finish', '1');
  3523. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3524. $poIdLog = null;
  3525. try {
  3526. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3527. $ids = $this->extractScydgyRowId($row);
  3528. if (!$this->isValidScydgyRowId($ids)) {
  3529. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3530. }
  3531. if ($asComplete) {
  3532. $this->assertPickRowCanComplete($ids, $row);
  3533. }
  3534. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3535. $data = [
  3536. 'scydgy_id' => $ids,
  3537. 'CCYDH' => $row['CCYDH'] ?? null,
  3538. 'CYJMC' => $row['CYJMC'] ?? null,
  3539. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3540. 'CDXMC' => $row['CDXMC'] ?? null,
  3541. 'CGYBH' => $row['CGYBH'] ?? null,
  3542. 'CGYMC' => $row['CGYMC'] ?? null,
  3543. 'CDW' => $row['CDW'] ?? null,
  3544. 'czlyq' => $row['czlyq'] ?? null,
  3545. 'NGZL' => $row['NGZL'] ?? null,
  3546. 'CDF' => $row['CDF'] ?? null,
  3547. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3548. 'MBZ' => $row['MBZ'] ?? null,
  3549. 'bwjg' => $row['bwjg'] ?? null,
  3550. 'iStatus' => $row['iStatus'] ?? null,
  3551. 'dStamp' => $row['dStamp'] ?? null,
  3552. 'dputrecord' => $row['dputrecord'] ?? null,
  3553. 'cywyxm' => $row['cywyxm'] ?? null,
  3554. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3555. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3556. ];
  3557. if ($asComplete) {
  3558. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3559. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3560. }
  3561. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3562. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3563. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3564. $this->success('操作成功');
  3565. return;
  3566. }
  3567. if ($exists) {
  3568. $upd = $data;
  3569. unset($upd['scydgy_id']);
  3570. if (!$asComplete) {
  3571. unset($upd['status']);
  3572. }
  3573. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3574. } else {
  3575. // 新增:不写 status;完结时 $data 已含 status=1
  3576. $data['createtime'] = date('Y-m-d H:i:s');
  3577. Db::table('purchase_order')->insert($data);
  3578. }
  3579. } catch (\Throwable $e) {
  3580. $this->error($e->getMessage());
  3581. }
  3582. try {
  3583. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3584. if (is_array($rpo)) {
  3585. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3586. $poIdLog = $tid > 0 ? $tid : null;
  3587. }
  3588. } catch (\Throwable $e) {
  3589. $poIdLog = null;
  3590. }
  3591. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3592. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3593. if ($asComplete) {
  3594. $this->addOrderLog(
  3595. $ids,
  3596. 'mark_complete',
  3597. '点击「完结」,已标记为已完结',
  3598. $poIdLog
  3599. );
  3600. try {
  3601. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3602. if ($pdfPublicPath === '') {
  3603. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3604. }
  3605. } catch (\Throwable $e) {
  3606. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3607. }
  3608. } else {
  3609. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  3610. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  3611. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  3612. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  3613. $this->addOrderLog(
  3614. $ids,
  3615. 'save_qty_price',
  3616. '保存本次数量、最高限价:' . $detail,
  3617. $poIdLog
  3618. );
  3619. }
  3620. $this->pickHiddenScydgySetCache = null;
  3621. $this->success("操作成功");
  3622. }
  3623. /**
  3624. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3625. *
  3626. * @param array<int, array> $rows 引用传递当前页行
  3627. */
  3628. protected function mergePurchaseOrder(array &$rows)
  3629. {
  3630. if ($rows === []) {
  3631. return;
  3632. }
  3633. $ids = [];
  3634. foreach ($rows as $rw) {
  3635. if (!is_array($rw)) {
  3636. continue;
  3637. }
  3638. $id = (int)($rw['ID'] ?? 0);
  3639. if ($id > 0) {
  3640. $ids[$id] = true;
  3641. }
  3642. }
  3643. $idList = array_keys($ids);
  3644. if ($idList === []) {
  3645. return;
  3646. }
  3647. try {
  3648. $list = Db::table('purchase_order')
  3649. ->where('scydgy_id', 'in', $idList)
  3650. ->field('scydgy_id,This_quantity,ceilingPrice')
  3651. ->select();
  3652. } catch (\Throwable $e) {
  3653. return;
  3654. }
  3655. if (!is_array($list)) {
  3656. return;
  3657. }
  3658. $byId = [];
  3659. foreach ($list as $dbRow) {
  3660. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3661. continue;
  3662. }
  3663. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3664. }
  3665. foreach ($rows as &$rw) {
  3666. if (!is_array($rw)) {
  3667. continue;
  3668. }
  3669. $sid = (int)($rw['ID'] ?? 0);
  3670. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3671. continue;
  3672. }
  3673. $db = $byId[$sid];
  3674. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3675. if (array_key_exists('This_quantity', $db)) {
  3676. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3677. }
  3678. if (array_key_exists('ceilingPrice', $db)) {
  3679. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3680. } elseif (array_key_exists('ceiling_price', $db)) {
  3681. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3682. }
  3683. }
  3684. unset($rw);
  3685. }
  3686. /**
  3687. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3688. */
  3689. public function purchaseConfirmPick()
  3690. {
  3691. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3692. $this->error(__('Invalid parameters'));
  3693. }
  3694. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3695. $this->error(__('You have no permission'));
  3696. }
  3697. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3698. if ($batchRaw !== '') {
  3699. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3700. return;
  3701. }
  3702. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3703. $sid = (int)$scydgyId;
  3704. if (!$this->isValidScydgyRowId($sid)) {
  3705. $this->error('参数无效');
  3706. }
  3707. $parseIdList = function ($raw) {
  3708. if (is_array($raw)) {
  3709. $arr = $raw;
  3710. } else {
  3711. $decoded = json_decode((string)$raw, true);
  3712. $arr = is_array($decoded) ? $decoded : [];
  3713. }
  3714. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3715. };
  3716. $selectedRaw = $this->request->post('selected_ids', null);
  3717. if ($selectedRaw === null || $selectedRaw === '') {
  3718. $legacy = (int)$this->request->post('selected_id', 0);
  3719. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3720. } else {
  3721. $selectedIds = $parseIdList($selectedRaw);
  3722. }
  3723. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3724. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3725. try {
  3726. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3727. } catch (\InvalidArgumentException $e) {
  3728. $this->error($e->getMessage());
  3729. } catch (\Throwable $e) {
  3730. $this->error($e->getMessage());
  3731. }
  3732. $this->pickHiddenScydgySetCache = null;
  3733. $this->success('操作成功', '', $result);
  3734. }
  3735. /**
  3736. * 整单采购确认(多道工序一次提交)
  3737. */
  3738. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3739. {
  3740. $decoded = json_decode($batchRaw, true);
  3741. if (!is_array($decoded) || $decoded === []) {
  3742. $this->error('提交数据无效');
  3743. }
  3744. $picks = [];
  3745. foreach ($decoded as $item) {
  3746. if (!is_array($item)) {
  3747. continue;
  3748. }
  3749. $sid = (int)($item['scydgy_id'] ?? 0);
  3750. if (!$this->isValidScydgyRowId($sid)) {
  3751. continue;
  3752. }
  3753. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3754. if (!is_array($sel)) {
  3755. $sel = [(int)$sel];
  3756. }
  3757. $unsel = $item['unselected_ids'] ?? [];
  3758. if (!is_array($unsel)) {
  3759. $unsel = json_decode((string)$unsel, true);
  3760. $unsel = is_array($unsel) ? $unsel : [];
  3761. }
  3762. $picks[] = [
  3763. 'scydgy_id' => $sid,
  3764. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3765. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3766. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3767. ];
  3768. }
  3769. if ($picks === []) {
  3770. $this->error('提交数据无效');
  3771. }
  3772. Db::startTrans();
  3773. $results = [];
  3774. try {
  3775. foreach ($picks as $pick) {
  3776. $results[] = $this->runPurchaseConfirmPick(
  3777. (int)$pick['scydgy_id'],
  3778. $pick['selected_ids'],
  3779. $pick['unselected_ids'],
  3780. (int)$pick['purchase_order_id'],
  3781. false,
  3782. false
  3783. );
  3784. }
  3785. Db::commit();
  3786. } catch (\Throwable $e) {
  3787. Db::rollback();
  3788. $msg = $e->getMessage();
  3789. $this->error($msg !== '' ? $msg : '提交失败');
  3790. }
  3791. try {
  3792. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3793. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3794. } catch (\Throwable $e) {
  3795. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3796. }
  3797. $this->pickHiddenScydgySetCache = null;
  3798. $this->success('操作成功', '', ['batch' => $results]);
  3799. }
  3800. /**
  3801. * @return array<string, mixed>
  3802. */
  3803. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3804. {
  3805. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3806. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3807. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3808. $scydgyId = (string)$sid;
  3809. if ($selectedIds === []) {
  3810. throw new \InvalidArgumentException('请至少勾选一条明细');
  3811. }
  3812. $inter = array_intersect($selectedIds, $unselectedIds);
  3813. if ($inter !== []) {
  3814. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3815. }
  3816. $allIds = $this->purchaseOrderDetail($sid);
  3817. if ($allIds === []) {
  3818. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3819. }
  3820. foreach ($selectedIds as $id) {
  3821. if (!in_array($id, $allIds, true)) {
  3822. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3823. }
  3824. }
  3825. foreach ($unselectedIds as $id) {
  3826. if (!in_array($id, $allIds, true)) {
  3827. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3828. }
  3829. }
  3830. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3831. sort($union, SORT_NUMERIC);
  3832. $expect = $allIds;
  3833. sort($expect, SORT_NUMERIC);
  3834. if ($union !== $expect) {
  3835. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3836. }
  3837. if ($manageTransaction) {
  3838. Db::startTrans();
  3839. }
  3840. try {
  3841. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3842. $aff = 0;
  3843. try {
  3844. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3845. } catch (\Throwable $e) {
  3846. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3847. }
  3848. if ($aff < 1) {
  3849. throw new \Exception('更新选中状态失败');
  3850. }
  3851. $poPayload = [
  3852. 'status' => ProcuremenStatus::PO_COMPLETED,
  3853. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3854. ];
  3855. if ($purchaseOrderId > 0) {
  3856. $poAff = (int)Db::table('purchase_order')
  3857. ->where('id', $purchaseOrderId)
  3858. ->where('scydgy_id', $sid)
  3859. ->update($poPayload);
  3860. if ($poAff < 1) {
  3861. throw new \Exception('主表订单不存在或与工序行不匹配');
  3862. }
  3863. } else {
  3864. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3865. if ($poAff < 1) {
  3866. throw new \Exception('未找到');
  3867. }
  3868. }
  3869. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3870. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3871. if ($manageTransaction) {
  3872. Db::commit();
  3873. }
  3874. } catch (\Throwable $e) {
  3875. if ($manageTransaction) {
  3876. Db::rollback();
  3877. }
  3878. throw $e;
  3879. }
  3880. $poIdFinal = $purchaseOrderId;
  3881. if ($poIdFinal <= 0) {
  3882. try {
  3883. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3884. if (is_array($rpo)) {
  3885. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3886. }
  3887. } catch (\Throwable $e) {
  3888. $poIdFinal = 0;
  3889. }
  3890. }
  3891. $pickNames = [];
  3892. foreach ($selectedIds as $pid) {
  3893. $dr = $this->purchaseOrderDetai($sid, $pid);
  3894. $nm = trim((string)($dr['company_name'] ?? ''));
  3895. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3896. }
  3897. $this->addOrderLog(
  3898. $sid,
  3899. 'purchase_confirm',
  3900. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3901. $poIdFinal > 0 ? $poIdFinal : null
  3902. );
  3903. if ($sendNotifications) {
  3904. try {
  3905. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3906. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3907. 'scydgy_id' => $sid,
  3908. 'selected_ids' => $selectedIds,
  3909. 'unselected_ids' => $unselectedIds,
  3910. 'purchase_order_id' => $purchaseOrderId,
  3911. ]]);
  3912. } catch (\Throwable $e) {
  3913. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3914. }
  3915. }
  3916. Log::write(sprintf(
  3917. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3918. $scydgyId,
  3919. $purchaseOrderId,
  3920. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3921. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3922. ), 'notice');
  3923. $pdfPublicPath = '';
  3924. try {
  3925. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3926. } catch (\Throwable $e) {
  3927. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3928. }
  3929. return [
  3930. 'scydgy_id' => $scydgyId,
  3931. 'purchase_order_id' => $purchaseOrderId,
  3932. 'selected_ids' => $selectedIds,
  3933. 'unselected_ids' => $unselectedIds,
  3934. 'purchase_confirm_pdf' => $pdfPublicPath,
  3935. ];
  3936. }
  3937. /**
  3938. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3939. *
  3940. * @param int[]|string[] $scydgyIds
  3941. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3942. */
  3943. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3944. {
  3945. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3946. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3947. if ($scydgyIds === []) {
  3948. return $empty;
  3949. }
  3950. $pos = [];
  3951. try {
  3952. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3953. } catch (\Throwable $e) {
  3954. $rows = [];
  3955. }
  3956. if (is_array($rows)) {
  3957. foreach ($rows as $po) {
  3958. if (is_array($po)) {
  3959. $pos[] = $po;
  3960. }
  3961. }
  3962. }
  3963. if ($pos === []) {
  3964. return $empty;
  3965. }
  3966. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3967. return [
  3968. 'ccydh' => $ccydh,
  3969. 'pos' => $pos,
  3970. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3971. ];
  3972. }
  3973. /**
  3974. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3975. *
  3976. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3977. * @param array<int, array<string, mixed>> $picks
  3978. */
  3979. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3980. {
  3981. if ($picks === []) {
  3982. return;
  3983. }
  3984. $fallbackDetailId = 0;
  3985. $winners = [];
  3986. $losers = [];
  3987. foreach ($picks as $pick) {
  3988. if (!is_array($pick)) {
  3989. continue;
  3990. }
  3991. $sid = (int)($pick['scydgy_id'] ?? 0);
  3992. if (!$this->isValidScydgyRowId($sid)) {
  3993. continue;
  3994. }
  3995. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3996. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3997. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3998. $fallbackDetailId = (int)$selectedIds[0];
  3999. }
  4000. foreach ($selectedIds as $pid) {
  4001. $dr = $this->purchaseOrderDetai($sid, $pid);
  4002. if (!is_array($dr)) {
  4003. continue;
  4004. }
  4005. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4006. }
  4007. foreach ($unselectedIds as $pid) {
  4008. $dr = $this->purchaseOrderDetai($sid, $pid);
  4009. if (!is_array($dr)) {
  4010. continue;
  4011. }
  4012. $key = $this->notifySupplierDedupeKey($dr);
  4013. if (!isset($winners[$key])) {
  4014. $losers[$key] = $dr;
  4015. }
  4016. }
  4017. }
  4018. if ($winners === [] && $losers === []) {
  4019. return;
  4020. }
  4021. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4022. $sendSmsSafe = function ($phone, $content) {
  4023. $phone = trim((string)$phone);
  4024. if ($phone === '') {
  4025. return;
  4026. }
  4027. try {
  4028. $this->smsbao($phone, $content);
  4029. } catch (\Throwable $e) {
  4030. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4031. }
  4032. };
  4033. foreach ($winners as $dr) {
  4034. $cname = trim((string)($dr['company_name'] ?? ''));
  4035. $ph = trim((string)($dr['phone'] ?? ''));
  4036. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4037. 'company_name' => $cname,
  4038. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4039. 'phone' => $ph,
  4040. ]));
  4041. $sendSmsSafe($ph, $sms);
  4042. }
  4043. foreach ($losers as $dr) {
  4044. $cname = trim((string)($dr['company_name'] ?? ''));
  4045. $ph = trim((string)($dr['phone'] ?? ''));
  4046. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4047. 'company_name' => $cname,
  4048. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4049. 'phone' => $ph,
  4050. ]));
  4051. $sendSmsSafe($ph, $sms);
  4052. }
  4053. }
  4054. /**
  4055. * 短信去重键:优先手机号,否则公司名
  4056. */
  4057. protected function notifySupplierDedupeKey(array $detailRow): string
  4058. {
  4059. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4060. if ($ph !== '') {
  4061. return 'p:' . $ph;
  4062. }
  4063. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4064. return 'c:' . $cn;
  4065. }
  4066. /**
  4067. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4068. *
  4069. * @param int[] $detailIds
  4070. */
  4071. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4072. {
  4073. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4074. if ($detailIds === []) {
  4075. return;
  4076. }
  4077. $payload = ['status_name' => $statusName];
  4078. try {
  4079. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4080. } catch (\Throwable $e) {
  4081. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4082. }
  4083. }
  4084. /**
  4085. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4086. */
  4087. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4088. {
  4089. try {
  4090. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4091. } catch (\Throwable $e) {
  4092. return;
  4093. }
  4094. if (!is_array($rows)) {
  4095. return;
  4096. }
  4097. foreach ($rows as $dr) {
  4098. if (!is_array($dr)) {
  4099. continue;
  4100. }
  4101. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4102. if ($id <= 0) {
  4103. continue;
  4104. }
  4105. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4106. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4107. try {
  4108. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4109. } catch (\Throwable $e) {
  4110. }
  4111. }
  4112. }
  4113. /**
  4114. * @param array<string, mixed> $detailRow
  4115. */
  4116. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4117. {
  4118. $am = $detailRow['amount'] ?? null;
  4119. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4120. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4121. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4122. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4123. }
  4124. /**
  4125. * @return int[]
  4126. */
  4127. protected function purchaseOrderDetail(int $scydgyId): array
  4128. {
  4129. if (!$this->isValidScydgyRowId($scydgyId)) {
  4130. return [];
  4131. }
  4132. try {
  4133. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4134. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  4135. $list = $listQuery->select();
  4136. } catch (\Throwable $e) {
  4137. return [];
  4138. }
  4139. if (!is_array($list)) {
  4140. return [];
  4141. }
  4142. $ids = [];
  4143. foreach ($list as $r) {
  4144. if (!is_array($r)) {
  4145. continue;
  4146. }
  4147. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  4148. if ($pk > 0) {
  4149. $ids[] = $pk;
  4150. }
  4151. }
  4152. return array_values(array_unique($ids));
  4153. }
  4154. /**
  4155. * 获取当前登录用户信息 [id, 展示名]
  4156. */
  4157. protected function GetUseName(): array
  4158. {
  4159. $id = 0;
  4160. $name = '';
  4161. try {
  4162. if ($this->auth && $this->auth->isLogin()) {
  4163. $u = $this->auth->getUserInfo();
  4164. if (is_array($u)) {
  4165. $id = (int)($u['id'] ?? 0);
  4166. $name = trim((string)($u['nickname'] ?? ''));
  4167. if ($name === '') {
  4168. $name = trim((string)($u['username'] ?? ''));
  4169. }
  4170. }
  4171. }
  4172. } catch (\Throwable $e) {
  4173. }
  4174. if ($name === '') {
  4175. $name = '未知用户';
  4176. }
  4177. return [$id, $name];
  4178. }
  4179. /**
  4180. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  4181. */
  4182. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  4183. {
  4184. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  4185. }
  4186. /**
  4187. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  4188. *
  4189. * @param array<int, array<string, mixed>> $rows
  4190. */
  4191. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  4192. {
  4193. $sidList = [];
  4194. foreach ($rows as $rw) {
  4195. if (!is_array($rw)) {
  4196. continue;
  4197. }
  4198. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4199. foreach ($rw['_order_merge_rows'] as $mr) {
  4200. $mid = (int)($mr['ID'] ?? 0);
  4201. if ($this->isValidScydgyRowId($mid)) {
  4202. $sidList[$mid] = true;
  4203. }
  4204. }
  4205. }
  4206. $id = (int)($rw['ID'] ?? 0);
  4207. if ($this->isValidScydgyRowId($id)) {
  4208. $sidList[$id] = true;
  4209. }
  4210. }
  4211. $sids = array_keys($sidList);
  4212. $issueBySid = [];
  4213. $confirmBySid = [];
  4214. $approveBySid = [];
  4215. if ($sids !== []) {
  4216. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  4217. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  4218. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  4219. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  4220. try {
  4221. $logs = Db::table('purchase_order_oper_log')
  4222. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  4223. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  4224. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  4225. ->order('id', 'asc')
  4226. ->select();
  4227. } catch (\Throwable $e) {
  4228. $logs = [];
  4229. }
  4230. if (is_array($logs)) {
  4231. $issueSet = array_fill_keys($issueActs, true);
  4232. $confirmSet = array_fill_keys($confirmActs, true);
  4233. $approveSet = array_fill_keys($approveActs, true);
  4234. foreach ($logs as $lg) {
  4235. if (!is_array($lg)) {
  4236. continue;
  4237. }
  4238. $lg = ProcuremenOperLog::normalizeRow($lg);
  4239. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  4240. if ($sid === 0) {
  4241. continue;
  4242. }
  4243. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  4244. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  4245. if ($t === '') {
  4246. continue;
  4247. }
  4248. if (isset($issueSet[$action])) {
  4249. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  4250. $issueBySid[$sid] = $t;
  4251. }
  4252. }
  4253. if (isset($confirmSet[$action])) {
  4254. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  4255. $confirmBySid[$sid] = $t;
  4256. }
  4257. }
  4258. if (isset($approveSet[$action])) {
  4259. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  4260. $approveBySid[$sid] = $t;
  4261. }
  4262. }
  4263. }
  4264. }
  4265. }
  4266. foreach ($rows as &$rw) {
  4267. if (!is_array($rw)) {
  4268. continue;
  4269. }
  4270. $mergeSids = [];
  4271. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4272. foreach ($rw['_order_merge_rows'] as $mr) {
  4273. $mid = (int)($mr['ID'] ?? 0);
  4274. if ($this->isValidScydgyRowId($mid)) {
  4275. $mergeSids[] = $mid;
  4276. }
  4277. }
  4278. }
  4279. $rid = (int)($rw['ID'] ?? 0);
  4280. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  4281. $mergeSids[] = $rid;
  4282. }
  4283. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  4284. $issue = $pick;
  4285. $confirm = '';
  4286. $approve = '';
  4287. foreach ($mergeSids as $sid) {
  4288. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  4289. $issue = $issueBySid[$sid];
  4290. }
  4291. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  4292. $confirm = $confirmBySid[$sid];
  4293. }
  4294. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  4295. $approve = $approveBySid[$sid];
  4296. }
  4297. }
  4298. if ($issue === '' && $pick !== '') {
  4299. $issue = $pick;
  4300. }
  4301. $rw['issue_time'] = $issue;
  4302. $rw['confirm_time'] = $confirm;
  4303. $rw['approve_time'] = $approve;
  4304. }
  4305. unset($rw);
  4306. }
  4307. /**
  4308. * 按主键取一条
  4309. */
  4310. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  4311. {
  4312. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  4313. return [];
  4314. }
  4315. try {
  4316. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  4317. if (is_array($one)) {
  4318. return $one;
  4319. }
  4320. } catch (\Throwable $e) {
  4321. }
  4322. try {
  4323. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  4324. if (is_array($one)) {
  4325. return $one;
  4326. }
  4327. } catch (\Throwable $e) {
  4328. }
  4329. return [];
  4330. }
  4331. /**
  4332. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  4333. */
  4334. protected function formatProcuremenDetailTime($v): string
  4335. {
  4336. if ($v === null || $v === '') {
  4337. return '';
  4338. }
  4339. if (is_numeric($v) && (int)$v > 946684800) {
  4340. return date('Y-m-d H:i:s', (int)$v);
  4341. }
  4342. return ProcuremenTime::formatDisplayDateTime($v);
  4343. }
  4344. /**
  4345. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  4346. */
  4347. protected function formatDeliveryYmd($v): string
  4348. {
  4349. if ($v === null || $v === '') {
  4350. return '';
  4351. }
  4352. $s = trim((string)$v);
  4353. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  4354. return '';
  4355. }
  4356. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4357. return $m[1];
  4358. }
  4359. $ts = strtotime($s);
  4360. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4361. }
  4362. /**
  4363. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4364. */
  4365. protected function detailRowSupplierOperated(array $r): bool
  4366. {
  4367. $am = $r['amount'] ?? null;
  4368. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4369. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4370. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4371. return $okAmt || $okDel;
  4372. }
  4373. /**
  4374. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4375. */
  4376. protected function resolveDetailSupplierOperTime(array $r): string
  4377. {
  4378. if (!$this->detailRowSupplierOperated($r)) {
  4379. return '';
  4380. }
  4381. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4382. if ($t !== '') {
  4383. return $t;
  4384. }
  4385. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4386. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4387. continue;
  4388. }
  4389. $t = $this->formatProcuremenDetailTime($r[$col]);
  4390. if ($t !== '') {
  4391. return $t;
  4392. }
  4393. }
  4394. return '';
  4395. }
  4396. /**
  4397. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4398. */
  4399. protected function detailRowSupplierAccepted(array $r): bool
  4400. {
  4401. $am = $r['amount'] ?? null;
  4402. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4403. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4404. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4405. return $okAmt && $okDel;
  4406. }
  4407. /**
  4408. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4409. */
  4410. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4411. {
  4412. if ($detailCount > 0) {
  4413. return true;
  4414. }
  4415. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4416. return true;
  4417. }
  4418. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4419. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4420. return true;
  4421. }
  4422. return false;
  4423. }
  4424. /**
  4425. * 下发时间:优先 pick_time,其次首条下发明细时间
  4426. */
  4427. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4428. {
  4429. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4430. if ($issueTime !== '') {
  4431. return $issueTime;
  4432. }
  4433. foreach ($details as $dr) {
  4434. if (!is_array($dr)) {
  4435. continue;
  4436. }
  4437. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4438. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4439. $issueTime = $t;
  4440. }
  4441. }
  4442. if ($issueTime !== '') {
  4443. return $issueTime;
  4444. }
  4445. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4446. }
  4447. /**
  4448. * 直接点「完结」时间:优先操作记录 mark_complete
  4449. */
  4450. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4451. {
  4452. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4453. }
  4454. /**
  4455. * 操作记录时间(取指定 action 最近一条)
  4456. *
  4457. * @param string|array<int, string> $actions
  4458. */
  4459. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4460. {
  4461. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4462. }
  4463. /**
  4464. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4465. *
  4466. * @param array $main purchase_order 一行
  4467. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4468. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4469. */
  4470. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4471. {
  4472. $issueCnt = count($details);
  4473. $acceptCnt = 0;
  4474. $pickedName = '';
  4475. $pickedTime = '';
  4476. foreach ($details as $dr) {
  4477. if (!is_array($dr)) {
  4478. continue;
  4479. }
  4480. if ($this->detailRowSupplierAccepted($dr)) {
  4481. $acceptCnt++;
  4482. }
  4483. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4484. if ($pickedName === '') {
  4485. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4486. }
  4487. if ($pickedTime === '') {
  4488. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4489. if ($pickedTime === '') {
  4490. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4491. }
  4492. }
  4493. }
  4494. }
  4495. $hasMain = $main !== [];
  4496. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4497. if ($poTime === '') {
  4498. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4499. }
  4500. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4501. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4502. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4503. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4504. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4505. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4506. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4507. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4508. $supplierTime = '';
  4509. if ($acceptCnt > 0) {
  4510. foreach ($details as $dr) {
  4511. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4512. continue;
  4513. }
  4514. $t = $this->resolveDetailSupplierOperTime($dr);
  4515. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4516. $supplierTime = $t;
  4517. }
  4518. }
  4519. }
  4520. $directComplete = ($mainCompleted && !$issued);
  4521. $doneTime = '';
  4522. if ($mainCompleted) {
  4523. if ($directComplete) {
  4524. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4525. }
  4526. if ($doneTime === '') {
  4527. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4528. }
  4529. if ($doneTime === '') {
  4530. foreach ($details as $dr) {
  4531. if (!is_array($dr)) {
  4532. continue;
  4533. }
  4534. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4535. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4536. $doneTime = $t;
  4537. }
  4538. }
  4539. }
  4540. if ($doneTime === '') {
  4541. $doneTime = $poTime;
  4542. }
  4543. if ($confirmApproveTime !== '') {
  4544. $doneTime = $confirmApproveTime;
  4545. }
  4546. }
  4547. if ($directComplete) {
  4548. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4549. $step1Done = $hasMain;
  4550. $step2Done = false;
  4551. $step3Done = false;
  4552. $step4Done = false;
  4553. $step5Done = false;
  4554. $step6Done = true;
  4555. } else {
  4556. $step1Done = $issued;
  4557. $step2Done = $issued;
  4558. $step3Done = $acceptCnt > 0;
  4559. $step4Done = $wflowPendingApproval;
  4560. if (!$step4Done) {
  4561. foreach ($details as $dr) {
  4562. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4563. $step4Done = true;
  4564. break;
  4565. }
  4566. }
  4567. }
  4568. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4569. $step6Done = $mainCompleted;
  4570. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4571. if ($mainCompleted && $issued) {
  4572. $step3Done = true;
  4573. $step4Done = true;
  4574. $step5Done = true;
  4575. if ($supplierTime === '') {
  4576. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4577. if ($fillT !== '') {
  4578. $supplierTime = $fillT;
  4579. }
  4580. }
  4581. if ($pickedTime === '') {
  4582. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4583. if ($fillT !== '') {
  4584. $pickedTime = $fillT;
  4585. }
  4586. }
  4587. if ($auditSelectTime === '') {
  4588. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4589. if ($fillT !== '') {
  4590. $auditSelectTime = $fillT;
  4591. }
  4592. }
  4593. if ($confirmApproveTime === '') {
  4594. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4595. if ($fillT !== '') {
  4596. $confirmApproveTime = $fillT;
  4597. }
  4598. }
  4599. }
  4600. }
  4601. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4602. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4603. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4604. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4605. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4606. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4607. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4608. $deadlineLines = [];
  4609. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4610. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4611. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4612. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4613. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  4614. }
  4615. }
  4616. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  4617. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  4618. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  4619. if ($deliveryDisp === '') {
  4620. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  4621. }
  4622. if ($deliveryDisp !== '') {
  4623. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  4624. }
  4625. }
  4626. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  4627. $deadlineText = implode("\n", $deadlineLines);
  4628. $prefixOperTime = static function (string $t): string {
  4629. $t = trim($t);
  4630. if ($t === '' || $t === '—') {
  4631. return $t;
  4632. }
  4633. if (strpos($t, '操作时间') === 0) {
  4634. return $t;
  4635. }
  4636. return '操作时间:' . $t;
  4637. };
  4638. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  4639. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  4640. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '';
  4641. $step6Time = $step6Done ? $doneTime : '';
  4642. $steps = [
  4643. [
  4644. 'title' => '未发',
  4645. 'subtitle' => '',
  4646. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  4647. 'done' => $step1Done,
  4648. ],
  4649. [
  4650. 'title' => '下发',
  4651. 'subtitle' => $deadlineText,
  4652. 'time' => $prefixOperTime($step2Time),
  4653. 'done' => $step2Done,
  4654. ],
  4655. [
  4656. 'title' => '供应商接单',
  4657. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4658. 'time' => '',
  4659. 'done' => $step3Done,
  4660. ],
  4661. [
  4662. 'title' => '待确认',
  4663. 'subtitle' => $step4Done
  4664. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4665. : ($issued ? '待选供应商' : ''),
  4666. 'time' => $prefixOperTime($step4Time),
  4667. 'done' => $step4Done,
  4668. ],
  4669. [
  4670. 'title' => '待审批',
  4671. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4672. 'time' => $prefixOperTime($step5Time),
  4673. 'done' => $step5Done,
  4674. ],
  4675. [
  4676. 'title' => '已完结',
  4677. 'subtitle' => '',
  4678. 'time' => $prefixOperTime($step6Time),
  4679. 'done' => $step6Done,
  4680. ],
  4681. ];
  4682. $currentIdx = count($steps) - 1;
  4683. if (!$directComplete) {
  4684. foreach ($steps as $i => $s) {
  4685. if (!$s['done']) {
  4686. $currentIdx = $i;
  4687. break;
  4688. }
  4689. }
  4690. }
  4691. $nSteps = count($steps);
  4692. foreach ($steps as $idx => &$s) {
  4693. $s['current'] = ($idx === $currentIdx);
  4694. if ($idx === 0) {
  4695. $s['pdf_left_bg'] = '';
  4696. } else {
  4697. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4698. }
  4699. if ($idx >= $nSteps - 1) {
  4700. $s['pdf_right_bg'] = '';
  4701. } else {
  4702. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4703. }
  4704. }
  4705. unset($s);
  4706. $labelMap = [
  4707. 'CCYDH' => '订单号',
  4708. 'CYJMC' => '印件名称',
  4709. 'CCLBMMC' => '承揽部门',
  4710. 'CGYMC' => '工序名称',
  4711. 'CDW' => '单位',
  4712. 'czlyq' => '类型',
  4713. 'NGZL' => '工作量',
  4714. 'CDF' => '单价',
  4715. 'cGzzxMc' => '工作中心',
  4716. 'MBZ' => '备注',
  4717. 'This_quantity' => '本次数量',
  4718. 'ceilingPrice' => '最高限价',
  4719. ];
  4720. $orderSummary = [];
  4721. foreach ($labelMap as $key => $lab) {
  4722. if (!array_key_exists($key, $main)) {
  4723. continue;
  4724. }
  4725. $val = $main[$key];
  4726. if ($val === null) {
  4727. $val = '';
  4728. } elseif (!is_scalar($val)) {
  4729. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4730. } else {
  4731. $val = (string)$val;
  4732. }
  4733. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4734. }
  4735. $orderSummaryGrid = [];
  4736. $n = count($orderSummary);
  4737. for ($i = 0; $i < $n; $i += 2) {
  4738. $left = $orderSummary[$i];
  4739. $hasRight = ($i + 1) < $n;
  4740. $orderSummaryGrid[] = [
  4741. 'l1' => $left['label'],
  4742. 'v1' => $left['value'],
  4743. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4744. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4745. ];
  4746. }
  4747. return [
  4748. 'steps' => $steps,
  4749. 'orderSummary' => $orderSummary,
  4750. 'orderSummaryGrid' => $orderSummaryGrid,
  4751. 'detailRows' => $details,
  4752. ];
  4753. }
  4754. /**
  4755. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4756. *
  4757. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4758. */
  4759. protected function prepareProcuremenDetailsView(string $ids): array
  4760. {
  4761. $main = [];
  4762. try {
  4763. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4764. $main = is_array($one) ? $one : [];
  4765. } catch (\Throwable $e) {
  4766. $main = [];
  4767. }
  4768. $details = [];
  4769. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4770. if ($mergeRows === []) {
  4771. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4772. if ($mergeRows === [] && $main !== []) {
  4773. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4774. }
  4775. }
  4776. $detailSidList = [];
  4777. $anchorSid = (int)$ids;
  4778. if ($anchorSid !== 0) {
  4779. $detailSidList[$anchorSid] = true;
  4780. }
  4781. foreach ($mergeRows as $mr) {
  4782. if (!is_array($mr)) {
  4783. continue;
  4784. }
  4785. $sid = $this->extractScydgyRowId($mr);
  4786. if ($sid !== 0) {
  4787. $detailSidList[$sid] = true;
  4788. }
  4789. }
  4790. try {
  4791. if ($detailSidList !== []) {
  4792. $details = Db::table('purchase_order_detail')
  4793. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4794. ->order('id', 'asc')
  4795. ->select();
  4796. }
  4797. } catch (\Throwable $e) {
  4798. $details = [];
  4799. }
  4800. if (!is_array($details)) {
  4801. $details = [];
  4802. }
  4803. foreach ($details as &$r) {
  4804. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4805. $r['id'] = $r['ID'];
  4806. }
  4807. if (isset($r['createtime'])) {
  4808. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4809. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4810. } else {
  4811. $r['createtime_text'] = (string)$r['createtime'];
  4812. }
  4813. } else {
  4814. $r['createtime_text'] = '';
  4815. }
  4816. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4817. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4818. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4819. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4820. if (is_array($r)) {
  4821. $r = $this->maskSupplierContactFields($r);
  4822. }
  4823. }
  4824. unset($r);
  4825. $activeDetails = [];
  4826. foreach ($details as $r) {
  4827. if (is_array($r) && empty($r['is_void'])) {
  4828. $activeDetails[] = $r;
  4829. }
  4830. }
  4831. $operLogs = [];
  4832. try {
  4833. $operSidList = array_keys($detailSidList);
  4834. if ($operSidList === [] && (int)$ids !== 0) {
  4835. $operSidList = [(int)$ids];
  4836. }
  4837. if ($operSidList !== []) {
  4838. $operLogs = Db::table('purchase_order_oper_log')
  4839. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  4840. ->order('id', 'asc')
  4841. ->select();
  4842. }
  4843. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  4844. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  4845. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  4846. if ($poId > 0) {
  4847. $operLogs = Db::table('purchase_order_oper_log')
  4848. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  4849. ->order('id', 'asc')
  4850. ->select();
  4851. }
  4852. }
  4853. } catch (\Throwable $e) {
  4854. $operLogs = [];
  4855. }
  4856. if (!is_array($operLogs)) {
  4857. $operLogs = [];
  4858. }
  4859. $processNameBySid = [];
  4860. foreach ($mergeRows as $mr) {
  4861. if (!is_array($mr)) {
  4862. continue;
  4863. }
  4864. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  4865. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  4866. if ($psid !== 0 && $gymc !== '') {
  4867. $processNameBySid[$psid] = $gymc;
  4868. }
  4869. }
  4870. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  4871. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4872. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4873. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4874. if ($ccydh === '') {
  4875. foreach ($details as $r) {
  4876. if (!is_array($r)) {
  4877. continue;
  4878. }
  4879. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4880. if ($ccydh !== '') {
  4881. break;
  4882. }
  4883. }
  4884. }
  4885. $this->view->assign('ccydh', $ccydh);
  4886. $this->view->assign('steps', $bundle['steps']);
  4887. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4888. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4889. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4890. $this->view->assign('processCount', count($mergeRows));
  4891. $this->view->assign('detailRows', $details);
  4892. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4893. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4894. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4895. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4896. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4897. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4898. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4899. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4900. $this->view->assign('operLogs', $operLogs);
  4901. $sg = $quoteView['supplier_groups'] ?? [];
  4902. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : []));
  4903. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : []) ? 1 : 0);
  4904. return [
  4905. 'ok' => $main !== [] || $details !== [],
  4906. 'ccydh' => $ccydh,
  4907. ];
  4908. }
  4909. /**
  4910. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4911. */
  4912. public function details()
  4913. {
  4914. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4915. if (is_array($ids)) {
  4916. $ids = isset($ids[0]) ? $ids[0] : '';
  4917. }
  4918. $ids = trim((string)$ids);
  4919. if ($ids === '') {
  4920. $this->error(__('Invalid parameters'));
  4921. }
  4922. $this->assertManualOrderDetailsViewable((int)$ids);
  4923. $this->prepareProcuremenDetailsView($ids);
  4924. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4925. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4926. $this->view->engine->layout(false);
  4927. try {
  4928. return $this->view->fetch('procuremen/details_dialog_shell');
  4929. } finally {
  4930. if ($restoreLayout) {
  4931. $this->view->engine->layout($restoreLayout);
  4932. }
  4933. }
  4934. }
  4935. /**
  4936. * 解析合并审核工序行(订单号须一致,且均未协助)
  4937. *
  4938. * @return array<int, array<string, mixed>>
  4939. */
  4940. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4941. {
  4942. $primary = json_decode($rowJson, true);
  4943. if (!is_array($primary)) {
  4944. $this->error(__('Invalid parameters'));
  4945. }
  4946. $merge = json_decode($mergeRowsJson, true);
  4947. if (!is_array($merge) || $merge === []) {
  4948. $merge = [$primary];
  4949. }
  4950. $seen = [];
  4951. $out = [];
  4952. foreach ($merge as $r) {
  4953. if (!is_array($r)) {
  4954. continue;
  4955. }
  4956. $id = $this->extractScydgyRowId($r);
  4957. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4958. continue;
  4959. }
  4960. $seen[$id] = true;
  4961. $out[] = $r;
  4962. }
  4963. if ($out === []) {
  4964. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4965. }
  4966. $ccydh = null;
  4967. foreach ($out as $r) {
  4968. $dh = trim((string)($r['CCYDH'] ?? ''));
  4969. if ($ccydh === null) {
  4970. $ccydh = $dh;
  4971. } elseif ($dh !== $ccydh) {
  4972. $this->error('合并审核要求所选行的订单号一致');
  4973. }
  4974. }
  4975. $ids = [];
  4976. foreach ($out as $r) {
  4977. $id = $this->extractScydgyRowId($r);
  4978. if ($this->isValidScydgyRowId($id)) {
  4979. $ids[$id] = true;
  4980. }
  4981. }
  4982. $poBySid = [];
  4983. $detCntBySid = [];
  4984. if ($ids !== []) {
  4985. $idList = array_keys($ids);
  4986. try {
  4987. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4988. if (is_array($poList)) {
  4989. foreach ($poList as $po) {
  4990. if (!is_array($po)) {
  4991. continue;
  4992. }
  4993. $sid = (int)($po['scydgy_id'] ?? 0);
  4994. if ($this->isValidScydgyRowId($sid)) {
  4995. $poBySid[$sid] = $po;
  4996. }
  4997. }
  4998. }
  4999. } catch (\Throwable $e) {
  5000. }
  5001. try {
  5002. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5003. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5004. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5005. if (is_array($detRows)) {
  5006. foreach ($detRows as $dr) {
  5007. if (!is_array($dr)) {
  5008. continue;
  5009. }
  5010. $sid = (int)($dr['scydgy_id'] ?? 0);
  5011. if ($this->isValidScydgyRowId($sid)) {
  5012. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5013. }
  5014. }
  5015. }
  5016. } catch (\Throwable $e) {
  5017. }
  5018. }
  5019. foreach ($out as $r) {
  5020. $id = $this->extractScydgyRowId($r);
  5021. if (!$this->isValidScydgyRowId($id)) {
  5022. continue;
  5023. }
  5024. $po = $poBySid[$id] ?? null;
  5025. if (!is_array($po)) {
  5026. continue;
  5027. }
  5028. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5029. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5030. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5031. }
  5032. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5033. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5034. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5035. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5036. }
  5037. }
  5038. return $out;
  5039. }
  5040. /**
  5041. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5042. */
  5043. protected function maskSupplierContactFields(array $item): array
  5044. {
  5045. if (array_key_exists('email', $item)) {
  5046. $item['email'] = mask_email((string)$item['email']);
  5047. }
  5048. if (array_key_exists('phone', $item)) {
  5049. $item['phone'] = mask_phone((string)$item['phone']);
  5050. }
  5051. return $item;
  5052. }
  5053. /**
  5054. * @param array<int, array<string, mixed>> $list
  5055. * @return array<int, array<string, mixed>>
  5056. */
  5057. protected function maskSupplierContactList(array $list): array
  5058. {
  5059. $out = [];
  5060. foreach ($list as $item) {
  5061. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5062. }
  5063. return $out;
  5064. }
  5065. /**
  5066. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5067. *
  5068. * @return array<string, string>|null
  5069. */
  5070. protected function buildCustomerContactPayloadFromRow($row): ?array
  5071. {
  5072. if (!is_array($row)) {
  5073. return null;
  5074. }
  5075. $norm = [];
  5076. foreach ($row as $k => $v) {
  5077. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  5078. }
  5079. $row = $norm;
  5080. $st = $row['status'] ?? '';
  5081. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  5082. return null;
  5083. }
  5084. $companyName = '';
  5085. foreach (['company_name', 'name'] as $nk) {
  5086. if (!empty($row[$nk])) {
  5087. $companyName = trim((string)$row[$nk]);
  5088. break;
  5089. }
  5090. }
  5091. if ($companyName === '') {
  5092. return null;
  5093. }
  5094. $username = '';
  5095. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  5096. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  5097. $username = trim((string)$row[$uk]);
  5098. break;
  5099. }
  5100. }
  5101. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  5102. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  5103. if ($phone === '' && isset($row['account'])) {
  5104. $phone = trim((string)$row['account']);
  5105. }
  5106. if ($phone === '' && isset($row['mobile'])) {
  5107. $phone = trim((string)$row['mobile']);
  5108. }
  5109. if ($email === '' && $phone === '') {
  5110. return null;
  5111. }
  5112. $category = '';
  5113. foreach (['company_type', 'category', 'type_name'] as $ck) {
  5114. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  5115. $category = trim((string)$row[$ck]);
  5116. break;
  5117. }
  5118. }
  5119. return [
  5120. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  5121. 'name' => $companyName,
  5122. 'company_name' => $companyName,
  5123. 'username' => $username,
  5124. 'email' => $email,
  5125. 'phone' => $phone,
  5126. 'category' => $category,
  5127. 'company_type' => $category,
  5128. ];
  5129. }
  5130. /**
  5131. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  5132. */
  5133. protected function resolveCustomerContactById(string $id): ?array
  5134. {
  5135. $id = trim($id);
  5136. if ($id === '' || !ctype_digit($id)) {
  5137. return null;
  5138. }
  5139. try {
  5140. $row = Db::table('customer')->where('id', (int)$id)->find();
  5141. } catch (\Throwable $e) {
  5142. return null;
  5143. }
  5144. return $this->buildCustomerContactPayloadFromRow($row);
  5145. }
  5146. /**
  5147. * 按供应商名称解析联系信息(兼容旧提交数据)
  5148. */
  5149. protected function resolveCustomerContactByCompanyName(string $name): ?array
  5150. {
  5151. $name = trim($name);
  5152. if ($name === '') {
  5153. return null;
  5154. }
  5155. try {
  5156. $row = Db::table('customer')
  5157. ->where(function ($q) use ($name) {
  5158. $q->where('company_name', $name)->whereOr('name', $name);
  5159. })
  5160. ->order('id', 'desc')
  5161. ->find();
  5162. } catch (\Throwable $e) {
  5163. return null;
  5164. }
  5165. return $this->buildCustomerContactPayloadFromRow($row);
  5166. }
  5167. /**
  5168. * 规范化下发/确认时勾选的供应商
  5169. *
  5170. * @param array<int, mixed> $companies
  5171. * @return array<int, array<string, string>>
  5172. */
  5173. protected function normalizePickCompanies(array $companies): array
  5174. {
  5175. $out = [];
  5176. foreach ($companies as $c) {
  5177. if (!is_array($c)) {
  5178. continue;
  5179. }
  5180. $resolved = null;
  5181. $cid = trim((string)($c['id'] ?? ''));
  5182. if ($cid !== '') {
  5183. $resolved = $this->resolveCustomerContactById($cid);
  5184. }
  5185. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  5186. if ($resolved === null && $name !== '') {
  5187. $resolved = $this->resolveCustomerContactByCompanyName($name);
  5188. }
  5189. if ($resolved === null) {
  5190. continue;
  5191. }
  5192. $out[] = $resolved;
  5193. }
  5194. return $out;
  5195. }
  5196. /**
  5197. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  5198. *
  5199. * @param array<int, array<string, mixed>> $pool
  5200. * @return array<int, array<string, mixed>>
  5201. */
  5202. protected function collapseProcuremenPoolByOrder(array $pool): array
  5203. {
  5204. if ($pool === []) {
  5205. return [];
  5206. }
  5207. $groups = [];
  5208. foreach ($pool as $row) {
  5209. if (!is_array($row)) {
  5210. continue;
  5211. }
  5212. $dh = trim((string)($row['CCYDH'] ?? ''));
  5213. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  5214. if (!isset($groups[$key])) {
  5215. $groups[$key] = [];
  5216. }
  5217. $groups[$key][] = $row;
  5218. }
  5219. $out = [];
  5220. foreach ($groups as $ccydh => $rows) {
  5221. if ($rows === []) {
  5222. continue;
  5223. }
  5224. usort($rows, function ($a, $b) {
  5225. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  5226. });
  5227. $head = $rows[0];
  5228. $gymcList = [];
  5229. foreach ($rows as $r) {
  5230. $g = trim((string)($r['CGYMC'] ?? ''));
  5231. if ($g !== '' && !in_array($g, $gymcList, true)) {
  5232. $gymcList[] = $g;
  5233. }
  5234. }
  5235. $merged = $head;
  5236. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  5237. $merged['process_count'] = count($rows);
  5238. $merged['_order_merge_rows'] = $rows;
  5239. if (count($rows) > 1) {
  5240. $merged['CGYMC'] = implode('、', $gymcList);
  5241. }
  5242. $mergedPickTime = '';
  5243. foreach ($rows as $r) {
  5244. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  5245. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  5246. $mergedPickTime = $t;
  5247. }
  5248. }
  5249. if ($mergedPickTime !== '') {
  5250. $merged['pick_time'] = $mergedPickTime;
  5251. }
  5252. $out[] = $merged;
  5253. }
  5254. usort($out, function ($a, $b) {
  5255. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  5256. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  5257. if ($ta === $tb) {
  5258. $ida = (int)($a['purchase_order_id'] ?? 0);
  5259. $idb = (int)($b['purchase_order_id'] ?? 0);
  5260. if ($ida !== $idb) {
  5261. return $idb <=> $ida;
  5262. }
  5263. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  5264. }
  5265. if ($ta === '') {
  5266. return 1;
  5267. }
  5268. if ($tb === '') {
  5269. return -1;
  5270. }
  5271. return strcmp($tb, $ta);
  5272. });
  5273. return $out;
  5274. }
  5275. /**
  5276. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  5277. *
  5278. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5279. */
  5280. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  5281. {
  5282. $scydgyId = trim($scydgyId);
  5283. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5284. if ($scydgyId === '') {
  5285. return $empty;
  5286. }
  5287. try {
  5288. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5289. } catch (\Throwable $e) {
  5290. $anchor = null;
  5291. }
  5292. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  5293. return $empty;
  5294. }
  5295. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5296. if ($ccydh === '') {
  5297. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5298. }
  5299. try {
  5300. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  5301. } catch (\Throwable $e) {
  5302. $pos = [$anchor];
  5303. }
  5304. if (!is_array($pos) || $pos === []) {
  5305. $pos = [$anchor];
  5306. }
  5307. return [
  5308. 'ccydh' => $ccydh,
  5309. 'pos' => $pos,
  5310. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5311. ];
  5312. }
  5313. /**
  5314. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  5315. */
  5316. protected function purchaseOrderRowInConfirmStage(array $po): bool
  5317. {
  5318. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5319. return false;
  5320. }
  5321. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  5322. return false;
  5323. }
  5324. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  5325. return true;
  5326. }
  5327. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  5328. $sid = (int)($po['scydgy_id'] ?? 0);
  5329. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  5330. }
  5331. return false;
  5332. }
  5333. /**
  5334. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  5335. *
  5336. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5337. */
  5338. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  5339. {
  5340. $scydgyId = trim($scydgyId);
  5341. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5342. if ($scydgyId === '') {
  5343. return $empty;
  5344. }
  5345. try {
  5346. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5347. } catch (\Throwable $e) {
  5348. $anchor = null;
  5349. }
  5350. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  5351. return $empty;
  5352. }
  5353. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5354. if ($ccydh === '') {
  5355. return [
  5356. 'ccydh' => '',
  5357. 'pos' => [$anchor],
  5358. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  5359. ];
  5360. }
  5361. try {
  5362. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5363. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  5364. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  5365. } catch (\Throwable $e) {
  5366. $pos = [$anchor];
  5367. }
  5368. if (!is_array($pos) || $pos === []) {
  5369. $pos = [$anchor];
  5370. }
  5371. $pos = array_values(array_filter($pos, function ($po) {
  5372. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  5373. }));
  5374. if ($pos === []) {
  5375. $pos = [$anchor];
  5376. }
  5377. return [
  5378. 'ccydh' => $ccydh,
  5379. 'pos' => $pos,
  5380. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5381. ];
  5382. }
  5383. /**
  5384. * @param array<int, array<string, mixed>> $purchaseOrders
  5385. * @return array<int, array<string, mixed>>
  5386. */
  5387. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  5388. {
  5389. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  5390. $byId = [];
  5391. foreach ($pool as $r) {
  5392. if (!is_array($r)) {
  5393. continue;
  5394. }
  5395. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  5396. if ($this->isValidScydgyRowId($sid)) {
  5397. $byId[$sid] = $r;
  5398. }
  5399. }
  5400. $out = [];
  5401. foreach ($purchaseOrders as $po) {
  5402. if (!is_array($po)) {
  5403. continue;
  5404. }
  5405. $sid = (int)($po['scydgy_id'] ?? 0);
  5406. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  5407. $out[] = $byId[$sid];
  5408. }
  5409. }
  5410. return $out;
  5411. }
  5412. /**
  5413. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  5414. *
  5415. * @return array<int, array<string, mixed>>
  5416. */
  5417. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5418. {
  5419. $scydgyId = trim($scydgyId);
  5420. if ($scydgyId === '') {
  5421. return [];
  5422. }
  5423. try {
  5424. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5425. } catch (\Throwable $e) {
  5426. $anchor = null;
  5427. }
  5428. if (!is_array($anchor)) {
  5429. return [];
  5430. }
  5431. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5432. return [];
  5433. }
  5434. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5435. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5436. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5437. try {
  5438. $q = Db::table('purchase_order');
  5439. if ($ccydh !== '') {
  5440. $q->where('CCYDH', $ccydh);
  5441. } else {
  5442. $q->where('scydgy_id', $scydgyId);
  5443. }
  5444. if ($isValidPick) {
  5445. $q->where('pick_time', $pickTime);
  5446. }
  5447. $pos = $q->order('scydgy_id', 'asc')->select();
  5448. } catch (\Throwable $e) {
  5449. $pos = [$anchor];
  5450. }
  5451. if (!is_array($pos) || $pos === []) {
  5452. $pos = [$anchor];
  5453. }
  5454. $pos = array_values(array_filter($pos, function ($po) {
  5455. if (!is_array($po)) {
  5456. return false;
  5457. }
  5458. $mr = $po['mod_rq'] ?? null;
  5459. if ($mr === null || $mr === '') {
  5460. return true;
  5461. }
  5462. $mrs = trim((string)$mr);
  5463. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5464. }));
  5465. if ($pos === []) {
  5466. $pos = [$anchor];
  5467. }
  5468. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5469. if ($rows === []) {
  5470. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5471. }
  5472. return $rows;
  5473. }
  5474. /**
  5475. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5476. *
  5477. * @param array<int, array<string, mixed>> $mergeRows
  5478. * @return array<int, array<string, mixed>>
  5479. */
  5480. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5481. {
  5482. $list = array_values($mergeRows);
  5483. $n = count($list);
  5484. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5485. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5486. $mergeSame = $n > 1 && $orderKey0 !== '';
  5487. if ($mergeSame) {
  5488. foreach ($list as $rr) {
  5489. if (!is_array($rr)) {
  5490. $mergeSame = false;
  5491. break;
  5492. }
  5493. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5494. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5495. $mergeSame = false;
  5496. break;
  5497. }
  5498. }
  5499. }
  5500. $out = [];
  5501. foreach ($list as $idx => $r) {
  5502. if (!is_array($r)) {
  5503. continue;
  5504. }
  5505. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5506. if (is_scalar($qty)) {
  5507. $qty = trim((string)$qty);
  5508. } else {
  5509. $qty = '';
  5510. }
  5511. if ($qty === '') {
  5512. $gzl = $r['NGZL'] ?? '';
  5513. if (is_scalar($gzl)) {
  5514. $qty = trim((string)$gzl);
  5515. }
  5516. }
  5517. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5518. $sid = $this->extractScydgyRowId($r);
  5519. $out[] = [
  5520. 'seq' => $idx + 1,
  5521. 'scydgy_id' => $sid,
  5522. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5523. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5524. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5525. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5526. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  5527. 'NGZL' => $r['NGZL'] ?? '',
  5528. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5529. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5530. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5531. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5532. 'show_order_cells' => !$mergeSame || $idx === 0,
  5533. 'order_rowspan' => $mergeSame ? $n : 1,
  5534. ];
  5535. }
  5536. return $out;
  5537. }
  5538. /**
  5539. * 解析金额/数量(去千分位等非数字字符)
  5540. */
  5541. protected function parseProcuremenMoneyNumber($value): ?float
  5542. {
  5543. if ($value === null || $value === '') {
  5544. return null;
  5545. }
  5546. if (is_numeric($value)) {
  5547. return (float)$value;
  5548. }
  5549. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5550. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5551. }
  5552. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5553. {
  5554. if ($amount === null) {
  5555. return '';
  5556. }
  5557. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  5558. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  5559. return $s === '' ? '0' : $s;
  5560. }
  5561. /**
  5562. * 列表/详情展示:工作量为 0 时显示空
  5563. */
  5564. protected function formatProcuremenWorkloadDisplay($value): string
  5565. {
  5566. if ($value === null || $value === '') {
  5567. return '';
  5568. }
  5569. $s = trim((string)$value);
  5570. if ($s === '') {
  5571. return '';
  5572. }
  5573. if (is_numeric($s) && (float)$s == 0) {
  5574. return '';
  5575. }
  5576. return $s;
  5577. }
  5578. /**
  5579. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5580. */
  5581. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5582. {
  5583. foreach ($details as $d) {
  5584. if (!is_array($d)) {
  5585. continue;
  5586. }
  5587. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5588. $cn = trim((string)($d['company_name'] ?? ''));
  5589. if ($cn !== '') {
  5590. return $cn;
  5591. }
  5592. }
  5593. }
  5594. return trim((string)($main['pick_company_name'] ?? ''));
  5595. }
  5596. /**
  5597. * 详情报价小计:单价 × 本工序本次数量
  5598. */
  5599. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5600. {
  5601. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5602. if ($unit === null) {
  5603. return null;
  5604. }
  5605. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5606. if ($qty === null || $qty <= 0) {
  5607. return null;
  5608. }
  5609. return $unit * $qty;
  5610. }
  5611. /**
  5612. * 详情页:工序小计 + 供应商分组报价与总计
  5613. *
  5614. * @param array<int, array<string, mixed>> $mergeRows
  5615. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5616. * @return array{
  5617. * process_rows: array,
  5618. * supplier_groups: array,
  5619. * order_total_text: string,
  5620. * order_total_has: bool,
  5621. * selected_company: string
  5622. * }
  5623. */
  5624. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5625. {
  5626. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5627. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5628. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5629. $qtyBySid = [];
  5630. $gymcBySid = [];
  5631. $orderedSids = [];
  5632. foreach ($mergeRows as $mr) {
  5633. if (!is_array($mr)) {
  5634. continue;
  5635. }
  5636. $sid = $this->extractScydgyRowId($mr);
  5637. if ($this->isValidScydgyRowId($sid)) {
  5638. $orderedSids[] = $sid;
  5639. }
  5640. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5641. if ($qty === '') {
  5642. $qty = trim((string)($mr['NGZL'] ?? ''));
  5643. }
  5644. $qtyBySid[$sid] = $qty;
  5645. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5646. }
  5647. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5648. $detailByCompanySid = [];
  5649. foreach ($details as $d) {
  5650. if (!is_array($d)) {
  5651. continue;
  5652. }
  5653. $cn = trim((string)($d['company_name'] ?? ''));
  5654. $sid = (int)($d['scydgy_id'] ?? 0);
  5655. if ($cn === '' || $sid === 0) {
  5656. continue;
  5657. }
  5658. if (!isset($detailByCompanySid[$cn])) {
  5659. $detailByCompanySid[$cn] = [];
  5660. }
  5661. $detailByCompanySid[$cn][$sid] = $d;
  5662. }
  5663. $supplierGroups = [];
  5664. foreach ($detailByCompanySid as $cn => $bySid) {
  5665. $lines = [];
  5666. $groupTotal = 0.0;
  5667. $groupHas = false;
  5668. $groupVoid = true;
  5669. $usedSids = [];
  5670. $appendLine = function (int $sid, array $d) use (
  5671. &$lines,
  5672. &$groupTotal,
  5673. &$groupHas,
  5674. &$groupVoid,
  5675. $qtyBySid,
  5676. $gymcBySid,
  5677. $quoteVisible
  5678. ) {
  5679. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5680. if (!$isVoid) {
  5681. $groupVoid = false;
  5682. }
  5683. $qtyStr = $qtyBySid[$sid] ?? '';
  5684. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5685. $am = trim((string)($d['amount'] ?? ''));
  5686. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5687. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5688. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5689. $sub = null;
  5690. if (!$isVoid && $amountNum !== null) {
  5691. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5692. }
  5693. $ct = $this->resolveDetailSupplierOperTime($d);
  5694. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5695. $leadFilled = ($leadDays !== null);
  5696. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5697. $line = [
  5698. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5699. 'amount' => $am,
  5700. 'unit_price_text' => $amountFilled
  5701. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5702. : '未填写',
  5703. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5704. 'delivery_ymd' => $deliveryYmd,
  5705. 'amount_filled' => $amountFilled,
  5706. 'delivery_filled' => $deliveryFilled,
  5707. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5708. 'lead_days' => $leadFilled ? $leadDays : '',
  5709. 'lead_days_filled'=> $leadFilled,
  5710. 'lead_days_show' => $leadText,
  5711. 'lead_days_text' => $leadText,
  5712. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5713. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5714. 'is_void' => $isVoid,
  5715. 'oper_time_text' => $ct,
  5716. ];
  5717. if (!$quoteVisible && !$isVoid) {
  5718. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5719. } elseif ($sub !== null) {
  5720. $groupTotal += $sub;
  5721. $groupHas = true;
  5722. }
  5723. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5724. };
  5725. foreach ($orderedSids as $sid) {
  5726. if (!isset($bySid[$sid])) {
  5727. continue;
  5728. }
  5729. $usedSids[$sid] = true;
  5730. $appendLine($sid, $bySid[$sid]);
  5731. }
  5732. foreach ($bySid as $sid => $d) {
  5733. if (isset($usedSids[$sid])) {
  5734. continue;
  5735. }
  5736. $appendLine((int)$sid, $d);
  5737. }
  5738. $firstDetail = null;
  5739. foreach ($bySid as $d) {
  5740. if (is_array($d)) {
  5741. $firstDetail = $d;
  5742. break;
  5743. }
  5744. }
  5745. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5746. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5747. if ($username === '' && $ph !== '') {
  5748. $username = $this->resolveCustomerContactName($ph, $cn);
  5749. }
  5750. $remark = '';
  5751. foreach ($bySid as $d) {
  5752. if (!is_array($d)) {
  5753. continue;
  5754. }
  5755. $rm = '';
  5756. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5757. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5758. $rm = trim((string)$d[$rk]);
  5759. break;
  5760. }
  5761. }
  5762. if ($rm !== '') {
  5763. $remark = $rm;
  5764. break;
  5765. }
  5766. }
  5767. $lineCount = count($lines);
  5768. $hasRemark = $lineCount > 0;
  5769. $supplierGroup = [
  5770. 'company_name' => $cn,
  5771. 'username' => $username,
  5772. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5773. 'phone' => $ph,
  5774. 'remark' => $remark,
  5775. 'has_remark' => $hasRemark,
  5776. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5777. 'is_void' => $groupVoid,
  5778. 'lines' => $lines,
  5779. 'line_count' => $lineCount,
  5780. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5781. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5782. 'has_total' => $lineCount > 0,
  5783. ];
  5784. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5785. $supplierGroups[] = $supplierGroup;
  5786. }
  5787. usort($supplierGroups, function ($a, $b) {
  5788. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5789. return ($a['is_void'] ?? false) ? 1 : -1;
  5790. }
  5791. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5792. return ($a['is_selected'] ?? false) ? -1 : 1;
  5793. }
  5794. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5795. });
  5796. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  5797. return [
  5798. 'process_rows' => $processRows,
  5799. 'supplier_groups' => $supplierGroups,
  5800. 'order_total_text' => '',
  5801. 'order_total_has' => false,
  5802. 'selected_company' => $selectedCompany,
  5803. ];
  5804. }
  5805. /**
  5806. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5807. */
  5808. protected function buildProcessLinesPlain(array $mergeRows): string
  5809. {
  5810. $lines = [];
  5811. $i = 1;
  5812. foreach ($mergeRows as $r) {
  5813. if (!is_array($r)) {
  5814. continue;
  5815. }
  5816. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5817. $dw = trim((string)($r['CDW'] ?? ''));
  5818. $gzl = trim((string)($r['NGZL'] ?? ''));
  5819. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5820. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5821. if ($dw !== '') {
  5822. $parts[] = '单位:' . $dw;
  5823. }
  5824. if ($gzl !== '') {
  5825. $parts[] = '工作量:' . $gzl;
  5826. }
  5827. if ($qty !== '') {
  5828. $parts[] = '本次数量:' . $qty;
  5829. }
  5830. $lines[] = implode(' ', $parts);
  5831. $i++;
  5832. }
  5833. return implode("\n", $lines);
  5834. }
  5835. /**
  5836. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5837. *
  5838. * @return array<string, string>
  5839. */
  5840. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5841. {
  5842. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5843. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5844. }
  5845. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5846. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5847. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5848. $cyjmc = '';
  5849. foreach ($mergeRows as $mr) {
  5850. if (!is_array($mr)) {
  5851. continue;
  5852. }
  5853. if ($ccydh === '') {
  5854. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5855. }
  5856. if ($cyjmc === '') {
  5857. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5858. }
  5859. }
  5860. if ($pos !== []) {
  5861. $firstPo = $pos[0];
  5862. if (is_array($firstPo)) {
  5863. if ($ccydh === '') {
  5864. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5865. }
  5866. if ($cyjmc === '') {
  5867. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5868. }
  5869. }
  5870. }
  5871. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5872. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5873. if (is_array($any)) {
  5874. if ($ccydh === '') {
  5875. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5876. }
  5877. if ($cyjmc === '') {
  5878. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5879. }
  5880. }
  5881. }
  5882. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5883. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5884. $cgymc = '';
  5885. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5886. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5887. }
  5888. return [
  5889. 'ccydh' => $ccydh,
  5890. 'cyjmc' => $cyjmc,
  5891. 'cgymc' => $cgymc,
  5892. 'process_lines' => $processLines,
  5893. 'process_lines_html' => '',
  5894. ];
  5895. }
  5896. /**
  5897. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5898. */
  5899. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5900. {
  5901. $lines = [];
  5902. if ($ccydh !== '') {
  5903. $lines[] = '订单号:' . $ccydh;
  5904. }
  5905. if ($cyjmc !== '') {
  5906. $lines[] = '印件名称:' . $cyjmc;
  5907. }
  5908. if ($processPlain !== '') {
  5909. $lines[] = $processPlain;
  5910. }
  5911. return implode("\n", $lines);
  5912. }
  5913. /**
  5914. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5915. *
  5916. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5917. */
  5918. protected function buildPlatformLinksPlain(array $detailLinks): string
  5919. {
  5920. $lines = [];
  5921. $i = 1;
  5922. foreach ($detailLinks as $lk) {
  5923. if (!is_array($lk)) {
  5924. continue;
  5925. }
  5926. $url = trim((string)($lk['url'] ?? ''));
  5927. if ($url === '') {
  5928. continue;
  5929. }
  5930. $label = trim((string)($lk['cgymc'] ?? ''));
  5931. if ($label === '') {
  5932. $label = '工序' . $i;
  5933. }
  5934. $lines[] = $label . ':' . $url;
  5935. $i++;
  5936. }
  5937. return implode("\n", $lines);
  5938. }
  5939. /**
  5940. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5941. *
  5942. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5943. */
  5944. protected function buildPlatformLinksHtml(array $detailLinks): string
  5945. {
  5946. $parts = [];
  5947. $i = 1;
  5948. foreach ($detailLinks as $lk) {
  5949. if (!is_array($lk)) {
  5950. continue;
  5951. }
  5952. $url = trim((string)($lk['url'] ?? ''));
  5953. if ($url === '') {
  5954. continue;
  5955. }
  5956. $label = trim((string)($lk['cgymc'] ?? ''));
  5957. if ($label === '') {
  5958. $label = '工序' . $i;
  5959. }
  5960. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5961. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5962. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5963. $i++;
  5964. }
  5965. return implode("<br>\n", $parts);
  5966. }
  5967. /**
  5968. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5969. *
  5970. * @return array<string, mixed>
  5971. */
  5972. protected function loadMailerConfig(): array
  5973. {
  5974. try {
  5975. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5976. } catch (\Throwable $e) {
  5977. $cfg = [];
  5978. }
  5979. return is_array($cfg) ? $cfg : [];
  5980. }
  5981. protected function loadNotifyTemplateRow(string $scene): ?array
  5982. {
  5983. try {
  5984. $row = Db::table('purchase_sms_template')
  5985. ->where('scene', $scene)
  5986. ->where(function ($q) {
  5987. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5988. })
  5989. ->order('id', 'asc')
  5990. ->find();
  5991. } catch (\Throwable $e) {
  5992. return null;
  5993. }
  5994. if (!is_array($row) || $row === []) {
  5995. return null;
  5996. }
  5997. return [
  5998. 'title' => trim((string)($row['title'] ?? '')),
  5999. 'content' => trim((string)($row['content'] ?? '')),
  6000. ];
  6001. }
  6002. /**
  6003. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6004. */
  6005. protected function buildProcessLinesHtml(array $mergeRows): string
  6006. {
  6007. if (count($mergeRows) <= 1) {
  6008. $r = $mergeRows[0] ?? [];
  6009. if (!is_array($r)) {
  6010. return '';
  6011. }
  6012. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6013. $dw = trim((string)($r['CDW'] ?? ''));
  6014. $gzl = trim((string)($r['NGZL'] ?? ''));
  6015. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6016. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6017. if ($dw !== '') {
  6018. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6019. }
  6020. if ($gzl !== '') {
  6021. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6022. }
  6023. if ($qty !== '') {
  6024. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6025. }
  6026. return $html;
  6027. }
  6028. $rows = '';
  6029. $i = 1;
  6030. foreach ($mergeRows as $r) {
  6031. if (!is_array($r)) {
  6032. continue;
  6033. }
  6034. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6035. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6036. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6037. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6038. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6039. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6040. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6041. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6042. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6043. $i++;
  6044. }
  6045. if ($rows === '') {
  6046. return '';
  6047. }
  6048. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  6049. . '<thead><tr style="background:#f5f5f5;">'
  6050. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  6051. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  6052. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  6053. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  6054. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  6055. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  6056. }
  6057. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  6058. {
  6059. $sysRq = trim($sysRq);
  6060. if ($sysRq === '') {
  6061. if ($required) {
  6062. $this->error('请选择招标截止日期');
  6063. }
  6064. return '';
  6065. }
  6066. $ts = strtotime($sysRq);
  6067. if ($ts === false || $ts <= 0) {
  6068. $this->error('招标截止日期格式无效');
  6069. }
  6070. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  6071. if (!$allowPast) {
  6072. $ymd = date('Y-m-d', $ts);
  6073. if ($ymd < date('Y-m-d')) {
  6074. $this->error('招标截止日期不能早于今天');
  6075. }
  6076. if ($ts <= time()) {
  6077. $this->error('招标截止时间不能早于当前时间');
  6078. }
  6079. }
  6080. return date('Y-m-d H:i:s', $ts);
  6081. }
  6082. /**
  6083. * 确保 purchase_order.czlyq(类型)存在
  6084. */
  6085. protected function ensurePurchaseOrderCzlyqColumn(): void
  6086. {
  6087. static $done = false;
  6088. if ($done) {
  6089. return;
  6090. }
  6091. $done = true;
  6092. try {
  6093. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  6094. if (empty($cols)) {
  6095. Db::execute(
  6096. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  6097. );
  6098. }
  6099. } catch (\Throwable $e) {
  6100. // ignore
  6101. }
  6102. }
  6103. /**
  6104. * 确保 purchase_order.delivery_deadline 存在
  6105. */
  6106. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  6107. {
  6108. static $done = false;
  6109. if ($done) {
  6110. return;
  6111. }
  6112. $done = true;
  6113. try {
  6114. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  6115. if (empty($cols)) {
  6116. Db::execute(
  6117. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  6118. );
  6119. }
  6120. } catch (\Throwable $e) {
  6121. // ignore
  6122. }
  6123. }
  6124. /**
  6125. * 解析交货截止日期(仅年月日)
  6126. */
  6127. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  6128. {
  6129. $raw = trim($raw);
  6130. if ($raw === '') {
  6131. if ($required) {
  6132. $this->error('请选择交货截止日期');
  6133. }
  6134. return '';
  6135. }
  6136. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  6137. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  6138. } else {
  6139. $ts = strtotime(str_replace('/', '-', $raw));
  6140. if ($ts === false || $ts <= 0) {
  6141. $this->error('交货截止日期格式无效');
  6142. }
  6143. $ymd = date('Y-m-d', $ts);
  6144. }
  6145. if ($ymd < date('Y-m-d')) {
  6146. $this->error('交货截止日期不能早于今天');
  6147. }
  6148. return $ymd;
  6149. }
  6150. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  6151. {
  6152. $s = trim((string)$value);
  6153. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  6154. return '';
  6155. }
  6156. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  6157. return $m[1];
  6158. }
  6159. $ts = strtotime(str_replace('/', '-', $s));
  6160. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  6161. }
  6162. /**
  6163. * @param array{pos?:array} $bundle
  6164. */
  6165. protected function resolveBundleDeliveryDeadline(array $bundle): string
  6166. {
  6167. foreach ($bundle['pos'] ?? [] as $po) {
  6168. if (!is_array($po)) {
  6169. continue;
  6170. }
  6171. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  6172. if ($d !== '') {
  6173. return $d;
  6174. }
  6175. }
  6176. return '';
  6177. }
  6178. protected function formatProcuremenSysRqForInput($sysRq): string
  6179. {
  6180. $sr = trim((string)$sysRq);
  6181. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  6182. return '';
  6183. }
  6184. $ts = strtotime($sr);
  6185. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  6186. }
  6187. protected function formatProcuremenSysRqForDisplay($sysRq): string
  6188. {
  6189. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  6190. if ($sr === '') {
  6191. return '—';
  6192. }
  6193. $ts = strtotime($sr);
  6194. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  6195. }
  6196. /**
  6197. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  6198. *
  6199. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  6200. * @return array{ccydh?:string,pos:array,merge_rows:array}
  6201. */
  6202. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  6203. {
  6204. return $bundle;
  6205. }
  6206. /**
  6207. * 写入/更新 purchase_order(单道工序行)
  6208. */
  6209. protected function upsertPurchaseOrderFromRow(
  6210. array $row,
  6211. string $sysRqDb,
  6212. $wflowStatus = null,
  6213. ?string $pickTime = null,
  6214. ?array $exists = null,
  6215. ?string $deliveryDeadline = null
  6216. ): void {
  6217. $ids = $this->extractScydgyRowId($row);
  6218. if (!$this->isValidScydgyRowId($ids)) {
  6219. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  6220. }
  6221. if ($exists === null) {
  6222. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6223. }
  6224. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  6225. $this->ensurePurchaseOrderCzlyqColumn();
  6226. $data = [
  6227. 'scydgy_id' => $ids,
  6228. 'CCYDH' => $row['CCYDH'] ?? null,
  6229. 'CYJMC' => $row['CYJMC'] ?? null,
  6230. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  6231. 'CDXMC' => $row['CDXMC'] ?? null,
  6232. 'CGYBH' => $row['CGYBH'] ?? null,
  6233. 'CGYMC' => $row['CGYMC'] ?? null,
  6234. 'CDW' => $row['CDW'] ?? null,
  6235. 'czlyq' => $row['czlyq'] ?? null,
  6236. 'NGZL' => $row['NGZL'] ?? null,
  6237. 'CDF' => $row['CDF'] ?? null,
  6238. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  6239. 'MBZ' => $row['MBZ'] ?? null,
  6240. 'bwjg' => $row['bwjg'] ?? null,
  6241. 'iStatus' => $row['iStatus'] ?? null,
  6242. 'dStamp' => $row['dStamp'] ?? null,
  6243. 'dputrecord' => $row['dputrecord'] ?? null,
  6244. 'cywyxm' => $row['cywyxm'] ?? null,
  6245. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  6246. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  6247. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6248. 'sys_rq' => $sysRqDb,
  6249. ];
  6250. if ($deliveryDeadline !== null) {
  6251. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  6252. }
  6253. if ($wflowStatus !== null && $wflowStatus !== '') {
  6254. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  6255. }
  6256. if ($pickTime !== null && $pickTime !== '') {
  6257. $data['pick_time'] = $pickTime;
  6258. $data['pick_company_name'] = '';
  6259. }
  6260. if ($exists) {
  6261. $upd = $data;
  6262. unset($upd['scydgy_id']);
  6263. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  6264. } else {
  6265. $data['createtime'] = date('Y-m-d H:i:s');
  6266. Db::table('purchase_order')->insert($data);
  6267. }
  6268. }
  6269. /**
  6270. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  6271. *
  6272. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  6273. */
  6274. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  6275. {
  6276. $toDb = function ($value) {
  6277. if ($value === null) {
  6278. return null;
  6279. }
  6280. if (is_scalar($value)) {
  6281. return $value;
  6282. }
  6283. return json_encode($value, JSON_UNESCAPED_UNICODE);
  6284. };
  6285. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  6286. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  6287. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  6288. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  6289. if ($username === '') {
  6290. $username = $this->resolveCustomerContactName($phone, $companyName);
  6291. }
  6292. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  6293. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  6294. }
  6295. if ($phone === '') {
  6296. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  6297. }
  6298. $detailLinks = [];
  6299. foreach ($mergeRows as $row) {
  6300. if (!is_array($row)) {
  6301. continue;
  6302. }
  6303. $sid = $this->extractScydgyRowId($row);
  6304. $detailId = 0;
  6305. if ($skipExisting) {
  6306. try {
  6307. $existsQuery = Db::table('purchase_order_detail')
  6308. ->where('scydgy_id', $sid)
  6309. ->where('company_name', $companyName);
  6310. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  6311. $exists = $existsQuery->find();
  6312. } catch (\Throwable $e) {
  6313. $exists = null;
  6314. }
  6315. if (is_array($exists)) {
  6316. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  6317. }
  6318. }
  6319. if ($detailId <= 0) {
  6320. $one = [
  6321. 'scydgy_id' => $toDb($sid),
  6322. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  6323. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  6324. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  6325. 'username' => $username !== '' ? $username : null,
  6326. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  6327. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  6328. 'createtime' => date('Y-m-d H:i:s'),
  6329. 'status' => ProcuremenStatus::POD_UNPICKED,
  6330. 'status_name' => '未提交',
  6331. ];
  6332. Db::table('purchase_order_detail')->insert($one);
  6333. $detailId = (int)Db::getLastInsID();
  6334. }
  6335. $mprocUrl = '';
  6336. if ($buildMobileLinks && $detailId > 0) {
  6337. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  6338. }
  6339. $detailLinks[] = [
  6340. 'detail_id' => $detailId,
  6341. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  6342. 'url' => $mprocUrl,
  6343. ];
  6344. }
  6345. return $detailLinks;
  6346. }
  6347. /**
  6348. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  6349. * @return array<string, mixed>
  6350. */
  6351. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  6352. {
  6353. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  6354. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  6355. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  6356. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  6357. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  6358. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  6359. $isMerge = !empty($ctx['is_merge']);
  6360. $contactName = trim((string)($c['username'] ?? ''));
  6361. if ($contactName === '') {
  6362. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  6363. }
  6364. $notifyVars = [
  6365. 'company_name' => $companyName,
  6366. 'contact_name' => $contactName,
  6367. 'phone' => $phone,
  6368. 'email' => $toEmail,
  6369. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  6370. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  6371. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  6372. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  6373. 'deadline' => (string)($ctx['deadline'] ?? ''),
  6374. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  6375. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  6376. 'platform_url' => $platformUrl,
  6377. 'platform_links' => $platformLinksPlain,
  6378. 'platform_links_html' => $platformLinksHtml,
  6379. ];
  6380. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  6381. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  6382. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  6383. return [
  6384. 'company_name' => $companyName,
  6385. 'phone' => $phone,
  6386. 'email' => $toEmail,
  6387. 'sms_content' => $smsContent,
  6388. 'mail_plain' => $mailPlain,
  6389. 'mail_body' => $mailBody,
  6390. 'notify_vars' => $notifyVars,
  6391. 'detail_links' => $detailLinks,
  6392. ];
  6393. }
  6394. /**
  6395. * @param array<string, mixed> $chosen
  6396. * @param array<int, array<string, mixed>> $mergeRows
  6397. * @param array{ccydh:string, pos:array} $bundle
  6398. */
  6399. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  6400. {
  6401. if (!$sendSms && !$sendEmail) {
  6402. return;
  6403. }
  6404. $companyName = trim((string)($chosen['name'] ?? ''));
  6405. $phone = trim((string)($chosen['phone'] ?? ''));
  6406. $toEmail = trim((string)($chosen['email'] ?? ''));
  6407. if ($companyName === '') {
  6408. throw new \Exception('供应商名称无效');
  6409. }
  6410. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  6411. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  6412. }
  6413. if ($sendSms && $phone === '') {
  6414. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  6415. }
  6416. $sids = [];
  6417. foreach ($mergeRows as $mr) {
  6418. if (!is_array($mr)) {
  6419. continue;
  6420. }
  6421. $sid = $this->extractScydgyRowId($mr);
  6422. if ($this->isValidScydgyRowId($sid)) {
  6423. $sids[$sid] = true;
  6424. }
  6425. }
  6426. if ($sids === []) {
  6427. throw new \Exception('未找到工序行,无法发送通知');
  6428. }
  6429. $sysRqNotify = '';
  6430. $pos = $bundle['pos'] ?? [];
  6431. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6432. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  6433. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  6434. $ts = strtotime($sr);
  6435. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  6436. }
  6437. }
  6438. try {
  6439. $detailsQuery = Db::table('purchase_order_detail')
  6440. ->where('scydgy_id', 'in', array_keys($sids))
  6441. ->where('company_name', $companyName);
  6442. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6443. $details = $detailsQuery->order('id', 'asc')->select();
  6444. } catch (\Throwable $e) {
  6445. $details = [];
  6446. }
  6447. if (!is_array($details) || $details === []) {
  6448. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6449. try {
  6450. $detailsQuery = Db::table('purchase_order_detail')
  6451. ->where('scydgy_id', 'in', array_keys($sids))
  6452. ->where('company_name', $companyName);
  6453. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6454. $details = $detailsQuery->order('id', 'asc')->select();
  6455. } catch (\Throwable $e) {
  6456. $details = [];
  6457. }
  6458. }
  6459. if (!is_array($details) || $details === []) {
  6460. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6461. }
  6462. $detailLinks = [];
  6463. foreach ($details as $d) {
  6464. if (!is_array($d)) {
  6465. continue;
  6466. }
  6467. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6468. if ($detailId <= 0) {
  6469. continue;
  6470. }
  6471. $sid = (int)($d['scydgy_id'] ?? 0);
  6472. $gymc = '';
  6473. foreach ($mergeRows as $mr) {
  6474. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6475. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6476. break;
  6477. }
  6478. }
  6479. $detailLinks[] = [
  6480. 'detail_id' => $detailId,
  6481. 'cgymc' => $gymc,
  6482. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6483. ];
  6484. }
  6485. if ($detailLinks === []) {
  6486. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6487. }
  6488. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6489. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6490. $notifyBundle['email_log_scene'] = $emailLogScene;
  6491. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6492. $poIdLog = 0;
  6493. $pos = $bundle['pos'] ?? [];
  6494. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6495. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6496. }
  6497. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6498. if ($sendEmail) {
  6499. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6500. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6501. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6502. }
  6503. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6504. $mailConfig = $this->loadMailerConfig();
  6505. if (!$this->isProcuremenNotifyDryRun()) {
  6506. if (empty($mailConfig['host'])) {
  6507. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6508. }
  6509. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6510. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6511. }
  6512. }
  6513. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6514. }
  6515. if ($sendSms) {
  6516. $this->issueSendSupplierSms($notifyBundle);
  6517. }
  6518. }
  6519. /**
  6520. * @param array<int, array<string, mixed>> $quoteGroups
  6521. * @return array<int, array<string, mixed>>
  6522. */
  6523. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6524. {
  6525. $names = [];
  6526. if (is_string($companiesJson) && $companiesJson !== '') {
  6527. $decoded = json_decode($companiesJson, true);
  6528. if (is_array($decoded)) {
  6529. foreach ($decoded as $nm) {
  6530. $nm = trim((string)$nm);
  6531. if ($nm !== '') {
  6532. $names[] = $nm;
  6533. }
  6534. }
  6535. }
  6536. }
  6537. $names = array_values(array_unique($names));
  6538. if ($names === [] && $selectedCompany !== '') {
  6539. $names = [$selectedCompany];
  6540. }
  6541. if ($names === []) {
  6542. return $quoteGroups;
  6543. }
  6544. $targets = [];
  6545. foreach ($quoteGroups as $g) {
  6546. if (!is_array($g)) {
  6547. continue;
  6548. }
  6549. $cn = trim((string)($g['name'] ?? ''));
  6550. if ($cn !== '' && in_array($cn, $names, true)) {
  6551. $targets[] = $g;
  6552. }
  6553. }
  6554. return $targets;
  6555. }
  6556. /**
  6557. * @return array{pos:array, merge_rows:array, bundle:array}
  6558. */
  6559. protected function loadAuditResendBundle(string $scydgyId): array
  6560. {
  6561. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6562. $pos = $bundle['pos'];
  6563. $mergeRows = $bundle['merge_rows'];
  6564. if ($pos === [] || $mergeRows === []) {
  6565. $this->error('该订单不在待确认供应商状态');
  6566. }
  6567. $sysRqDb = '';
  6568. if (isset($pos[0]) && is_array($pos[0])) {
  6569. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6570. }
  6571. foreach ($pos as $i => $poRow) {
  6572. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6573. $pos[$i]['sys_rq'] = $sysRqDb;
  6574. }
  6575. }
  6576. $bundle['pos'] = $pos;
  6577. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6578. }
  6579. /**
  6580. * @param array<int, array<string, mixed>> $targets
  6581. */
  6582. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6583. {
  6584. if ($targets === []) {
  6585. $this->error('未找到可通知的供应商');
  6586. }
  6587. $notifyErrors = [];
  6588. try {
  6589. $this->notifyDryRunPreview = [];
  6590. foreach ($targets as $g) {
  6591. if (!is_array($g)) {
  6592. continue;
  6593. }
  6594. $cname = trim((string)($g['name'] ?? ''));
  6595. if ($cname === '') {
  6596. continue;
  6597. }
  6598. $chosen = [
  6599. 'name' => $cname,
  6600. 'company_name' => $cname,
  6601. 'email' => trim((string)($g['email'] ?? '')),
  6602. 'phone' => trim((string)($g['phone'] ?? '')),
  6603. 'username' => trim((string)($g['username'] ?? '')),
  6604. ];
  6605. try {
  6606. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6607. } catch (\Throwable $e) {
  6608. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6609. }
  6610. }
  6611. } catch (\Throwable $e) {
  6612. $this->error('通知发送失败:' . $e->getMessage());
  6613. }
  6614. if ($notifyErrors !== []) {
  6615. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6616. }
  6617. if ($this->isProcuremenNotifyDryRun()) {
  6618. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6619. 'notify_dry_run' => true,
  6620. 'notify_preview' => $this->notifyDryRunPreview,
  6621. ]);
  6622. }
  6623. $nameLabels = [];
  6624. foreach ($targets as $g) {
  6625. if (!is_array($g)) {
  6626. continue;
  6627. }
  6628. $n = trim((string)($g['name'] ?? ''));
  6629. if ($n !== '') {
  6630. $nameLabels[] = $n;
  6631. }
  6632. }
  6633. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6634. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6635. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6636. $seenLogSid = [];
  6637. foreach ($bundle['pos'] ?? [] as $poRow) {
  6638. if (!is_array($poRow)) {
  6639. continue;
  6640. }
  6641. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6642. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6643. continue;
  6644. }
  6645. $seenLogSid[$sid] = true;
  6646. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6647. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6648. }
  6649. if ($seenLogSid === []) {
  6650. foreach ($mergeRows as $mr) {
  6651. if (!is_array($mr)) {
  6652. continue;
  6653. }
  6654. $sid = $this->extractScydgyRowId($mr);
  6655. if ($this->isValidScydgyRowId($sid)) {
  6656. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6657. break;
  6658. }
  6659. }
  6660. }
  6661. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6662. }
  6663. /**
  6664. * 协助下发 — 发送短信(一家供应商)
  6665. *
  6666. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6667. */
  6668. protected function issueSendSupplierSms(array $bundle): void
  6669. {
  6670. $companyName = (string)($bundle['company_name'] ?? '');
  6671. $phone = (string)($bundle['phone'] ?? '');
  6672. $smsContent = (string)($bundle['sms_content'] ?? '');
  6673. $this->logIssueNotifyDebug('短信', [
  6674. 'company' => $companyName,
  6675. 'phone' => $phone,
  6676. 'sms_content' => $smsContent,
  6677. ]);
  6678. if ($this->isProcuremenNotifyDryRun()) {
  6679. $this->recordNotifyDryRunPreview([
  6680. 'scene' => 'issue_sms',
  6681. 'company_name' => $companyName,
  6682. 'phone' => $phone,
  6683. 'sms_content' => $smsContent,
  6684. ]);
  6685. return;
  6686. }
  6687. $this->smsbao($phone, $smsContent);
  6688. }
  6689. /**
  6690. * 协助下发 — 发送邮件(一家供应商)
  6691. *
  6692. * @param array<string, mixed> $bundle
  6693. * @param array<string, mixed> $mailConfig
  6694. */
  6695. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6696. {
  6697. $companyName = (string)($bundle['company_name'] ?? '');
  6698. $toEmail = (string)($bundle['email'] ?? '');
  6699. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6700. $mailBody = (string)($bundle['mail_body'] ?? '');
  6701. $this->logIssueNotifyDebug('邮件', [
  6702. 'company' => $companyName,
  6703. 'email' => $toEmail,
  6704. 'mail_subject' => $mailSubject,
  6705. 'mail_body' => $mailPlain,
  6706. ]);
  6707. if ($this->isProcuremenNotifyDryRun()) {
  6708. $this->recordNotifyDryRunPreview([
  6709. 'scene' => 'issue_email',
  6710. 'company_name' => $companyName,
  6711. 'email' => $toEmail,
  6712. 'mail_subject' => $mailSubject,
  6713. 'mail_body' => $mailPlain,
  6714. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6715. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6716. 'detail_links' => $bundle['detail_links'] ?? [],
  6717. ]);
  6718. return;
  6719. }
  6720. $mail = new PHPMailer(true);
  6721. $mail->isSMTP();
  6722. $mail->Host = $mailConfig['host'];
  6723. $mail->SMTPAuth = true;
  6724. $mail->Username = $mailConfig['addr'];
  6725. $mail->Password = $mailConfig['pass'];
  6726. $mail->SMTPSecure = $mailConfig['security'];
  6727. $mail->Port = $mailConfig['port'];
  6728. $mail->CharSet = $mailConfig['charset'];
  6729. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6730. $mail->addAddress($toEmail, $companyName);
  6731. $mail->isHTML(true);
  6732. $mail->Subject = $mailSubject;
  6733. $mail->Body = $mailBody;
  6734. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6735. $sendOk = true;
  6736. $failReason = '';
  6737. try {
  6738. $mail->send();
  6739. } catch (\Throwable $e) {
  6740. $sendOk = false;
  6741. $failReason = $e->getMessage();
  6742. $this->persistEmailSendLog([
  6743. 'from_email' => $fromEmail,
  6744. 'to_email' => $toEmail,
  6745. 'send_time' => date('Y-m-d H:i:s'),
  6746. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6747. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6748. 'company_name' => $companyName,
  6749. 'mail_subject' => $mailSubject,
  6750. 'status' => 0,
  6751. 'fail_reason' => $failReason,
  6752. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6753. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6754. ]);
  6755. throw $e;
  6756. }
  6757. $this->persistEmailSendLog([
  6758. 'from_email' => $fromEmail,
  6759. 'to_email' => $toEmail,
  6760. 'send_time' => date('Y-m-d H:i:s'),
  6761. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6762. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6763. 'company_name' => $companyName,
  6764. 'mail_subject' => $mailSubject,
  6765. 'status' => 1,
  6766. 'fail_reason' => '',
  6767. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6768. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6769. ]);
  6770. }
  6771. /**
  6772. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6773. *
  6774. * @param array<int, array<string, mixed>> $mergeRows
  6775. * @return array<string, mixed>
  6776. */
  6777. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6778. {
  6779. $head = $mergeRows[0] ?? [];
  6780. $isMerge = count($mergeRows) > 1;
  6781. return [
  6782. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6783. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6784. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6785. 'is_merge' => $isMerge,
  6786. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6787. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6788. 'deadline' => $sysRqNotify,
  6789. ];
  6790. }
  6791. /**
  6792. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6793. *
  6794. * @param array<string, mixed> $data
  6795. */
  6796. protected function logIssueNotifyDebug(string $type, array $data): void
  6797. {
  6798. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6799. return;
  6800. }
  6801. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6802. }
  6803. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6804. {
  6805. try {
  6806. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6807. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6808. return;
  6809. } catch (\Throwable $e) {
  6810. }
  6811. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6812. if (is_file($sqlFile)) {
  6813. $sql = file_get_contents($sqlFile);
  6814. if (is_string($sql) && $sql !== '') {
  6815. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6816. $stmt = trim($stmt);
  6817. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6818. continue;
  6819. }
  6820. try {
  6821. Db::execute($stmt);
  6822. } catch (\Throwable $ignore) {
  6823. }
  6824. }
  6825. }
  6826. }
  6827. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6828. }
  6829. /**
  6830. * @param array<string, mixed> $row
  6831. */
  6832. protected function persistEmailSendLog(array $row): void
  6833. {
  6834. try {
  6835. $this->ensurePurchaseEmailSendLogTableOnce();
  6836. } catch (\Throwable $e) {
  6837. return;
  6838. }
  6839. list($adminId, $adminName) = $this->GetUseName();
  6840. $cut = function ($s, $max) {
  6841. $s = (string)$s;
  6842. if (function_exists('mb_substr')) {
  6843. return mb_substr($s, 0, $max, 'UTF-8');
  6844. }
  6845. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6846. };
  6847. $data = [
  6848. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6849. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6850. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6851. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6852. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6853. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6854. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6855. 'status' => !empty($row['status']) ? 1 : 0,
  6856. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6857. 'admin_id' => (int)$adminId,
  6858. 'admin_name' => $cut($adminName, 64),
  6859. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6860. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6861. 'createtime' => date('Y-m-d H:i:s'),
  6862. ];
  6863. try {
  6864. Db::table('purchase_email_send_log')->insert($data);
  6865. } catch (\Throwable $e) {
  6866. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6867. }
  6868. }
  6869. protected function formatEmailLogSceneText(string $scene): string
  6870. {
  6871. $map = [
  6872. 'pick_issue' => '初选下发',
  6873. 'audit_resend' => '确认页重发',
  6874. ];
  6875. return $map[$scene] ?? $scene;
  6876. }
  6877. /**
  6878. * 邮件发送日志列表
  6879. */
  6880. public function emailLog()
  6881. {
  6882. $this->relationSearch = false;
  6883. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6884. $this->request->filter(['strip_tags', 'trim']);
  6885. $bakModel = $this->model;
  6886. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6887. if ($this->request->isAjax()) {
  6888. $this->ensurePurchaseEmailSendLogTableOnce();
  6889. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6890. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6891. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6892. $list = $this->model
  6893. ->where($where)
  6894. ->order($sortField, $orderDir)
  6895. ->paginate($limit);
  6896. $rows = [];
  6897. foreach ($list->items() as $item) {
  6898. $row = is_array($item) ? $item : $item->toArray();
  6899. $scene = trim((string)($row['scene'] ?? ''));
  6900. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6901. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6902. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6903. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6904. $rows[] = $row;
  6905. }
  6906. $this->model = $bakModel;
  6907. return json(['total' => $list->total(), 'rows' => $rows]);
  6908. }
  6909. $this->model = $bakModel;
  6910. return $this->view->fetch('procuremen/emaillog');
  6911. }
  6912. /**
  6913. * 协助下发弹窗(选多家供应商并通知)
  6914. */
  6915. public function pickReview()
  6916. {
  6917. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6918. $this->error(__('You have no permission'));
  6919. }
  6920. if ($this->request->isPost()) {
  6921. $this->error('请使用弹窗内「确认下发」提交');
  6922. }
  6923. $this->view->assign('pickMode', 1);
  6924. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6925. }
  6926. /**
  6927. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6928. */
  6929. public function add()
  6930. {
  6931. if ($this->request->isPost()) {
  6932. $params = $this->request->post('row/a');
  6933. if (!is_array($params)) {
  6934. $this->error(__('Parameter %s can not be empty', ''));
  6935. }
  6936. [, $adminName] = $this->GetUseName();
  6937. $params['cywyxm'] = $adminName;
  6938. try {
  6939. $sid = $this->saveManualPickOrder($params);
  6940. } catch (\InvalidArgumentException $e) {
  6941. $this->error($e->getMessage());
  6942. } catch (\Throwable $e) {
  6943. $this->error($e->getMessage());
  6944. }
  6945. $this->success('新增成功', '', [
  6946. 'scydgy_id' => $sid,
  6947. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6948. ]);
  6949. }
  6950. [, $adminName] = $this->GetUseName();
  6951. $this->view->assign('adminNickname', $adminName);
  6952. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6953. $this->view->assign('defaultCclbmmc', '营销中心');
  6954. return $this->view->fetch();
  6955. }
  6956. /**
  6957. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6958. */
  6959. public function rfqlist()
  6960. {
  6961. $this->relationSearch = false;
  6962. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6963. $this->request->filter(['strip_tags', 'trim']);
  6964. if ($this->request->isAjax()) {
  6965. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6966. $limit = max(10, min(500, (int)$limit));
  6967. $applyFilters = function ($query) use ($where) {
  6968. $query->where('scydgy_id', '<', 0);
  6969. $query->whereRaw(
  6970. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6971. );
  6972. if (!$this->auth->isSuperAdmin()) {
  6973. [, $adminName] = $this->GetUseName();
  6974. $query->where('cywyxm', $adminName);
  6975. }
  6976. if (!empty($where)) {
  6977. $query->where($where);
  6978. }
  6979. };
  6980. $countQuery = Db::table('purchase_order');
  6981. $applyFilters($countQuery);
  6982. $total = (int)$countQuery->count();
  6983. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6984. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6985. $listQuery = Db::table('purchase_order');
  6986. $applyFilters($listQuery);
  6987. $rows = $listQuery
  6988. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6989. ->order($sortField, $orderDir)
  6990. ->limit($offset, $limit)
  6991. ->select();
  6992. if (!is_array($rows)) {
  6993. $rows = [];
  6994. }
  6995. $out = [];
  6996. foreach ($rows as $r) {
  6997. if (!is_array($r)) {
  6998. continue;
  6999. }
  7000. $sid = (int)($r['scydgy_id'] ?? 0);
  7001. if ($sid >= 0) {
  7002. continue;
  7003. }
  7004. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  7005. if ($createdText === '') {
  7006. $createdText = trim((string)($r['dStamp'] ?? ''));
  7007. }
  7008. $out[] = [
  7009. 'id' => (int)($r['id'] ?? 0),
  7010. 'scydgy_id' => $sid,
  7011. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7012. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7013. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  7014. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7015. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  7016. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  7017. 'createtime' => $r['createtime'] ?? null,
  7018. 'createtime_text' => $createdText,
  7019. ];
  7020. }
  7021. return json(['total' => $total, 'rows' => $out]);
  7022. }
  7023. [, $adminName] = $this->GetUseName();
  7024. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  7025. $this->view->assign('adminNickname', $adminName);
  7026. return $this->view->fetch('procuremen/rfqlist');
  7027. }
  7028. /**
  7029. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  7030. */
  7031. public function rfqlistDetails()
  7032. {
  7033. return $this->details();
  7034. }
  7035. /**
  7036. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  7037. */
  7038. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  7039. {
  7040. if ($scydgyId >= 0) {
  7041. return;
  7042. }
  7043. try {
  7044. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7045. } catch (\Throwable $e) {
  7046. $po = null;
  7047. }
  7048. if (!is_array($po)) {
  7049. $this->error('订单不存在');
  7050. }
  7051. $modRq = trim((string)($po['mod_rq'] ?? ''));
  7052. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  7053. $this->error('订单不存在');
  7054. }
  7055. if ($this->auth->isSuperAdmin()) {
  7056. return;
  7057. }
  7058. [, $adminName] = $this->GetUseName();
  7059. $cywy = trim((string)($po['cywyxm'] ?? ''));
  7060. if ($cywy !== '' && $cywy === $adminName) {
  7061. return;
  7062. }
  7063. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  7064. try {
  7065. if ($this->auth->check($rule)) {
  7066. return;
  7067. }
  7068. } catch (\Throwable $e) {
  7069. }
  7070. }
  7071. $this->error('无权查看该订单');
  7072. }
  7073. /**
  7074. * 手工新增协助工序进度文案
  7075. */
  7076. protected function formatProcuremenRfqProgressText(array $row): string
  7077. {
  7078. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  7079. return ProcuremenStatus::PO_COMPLETED;
  7080. }
  7081. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  7082. return '待采购确认';
  7083. }
  7084. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  7085. return '待确认供应商';
  7086. }
  7087. $sid = (int)($row['scydgy_id'] ?? 0);
  7088. if ($sid < 0) {
  7089. try {
  7090. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  7091. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  7092. $detCnt = (int)$detCntQuery->count();
  7093. if ($detCnt > 0) {
  7094. return '已下发待确认';
  7095. }
  7096. } catch (\Throwable $e) {
  7097. }
  7098. }
  7099. return '待协助下发';
  7100. }
  7101. /**
  7102. * 协助初选列表 — 批量软删除
  7103. */
  7104. public function pickDelete()
  7105. {
  7106. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7107. $this->error(__('Invalid parameters'));
  7108. }
  7109. if (!$this->procuremenCanPickDelete()) {
  7110. $this->error(__('You have no permission'));
  7111. }
  7112. $rowsRaw = $this->request->post('rows_json', '[]');
  7113. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  7114. if (!is_array($rows) || $rows === []) {
  7115. $this->error('请至少勾选一条工序');
  7116. }
  7117. $done = 0;
  7118. Db::startTrans();
  7119. try {
  7120. foreach ($rows as $row) {
  7121. if (!is_array($row)) {
  7122. continue;
  7123. }
  7124. $this->softDeleteProcuremenPickRow($row);
  7125. $done++;
  7126. }
  7127. if ($done < 1) {
  7128. throw new \Exception('没有可删除的工序');
  7129. }
  7130. Db::commit();
  7131. } catch (\InvalidArgumentException $e) {
  7132. Db::rollback();
  7133. $this->error($e->getMessage());
  7134. } catch (\Throwable $e) {
  7135. Db::rollback();
  7136. $this->error($e->getMessage());
  7137. }
  7138. $this->pickHiddenScydgySetCache = null;
  7139. $this->success('已删除 ' . $done . ' 条工序');
  7140. }
  7141. /**
  7142. * 下发 — 手工新增工序(弹窗)
  7143. */
  7144. public function pickAdd()
  7145. {
  7146. if ($this->request->isPost()) {
  7147. $params = $this->request->post('row/a');
  7148. if (!is_array($params)) {
  7149. $this->error(__('Parameter %s can not be empty', ''));
  7150. }
  7151. try {
  7152. $sid = $this->saveManualPickOrder($params);
  7153. } catch (\InvalidArgumentException $e) {
  7154. $this->error($e->getMessage());
  7155. } catch (\Throwable $e) {
  7156. $this->error($e->getMessage());
  7157. }
  7158. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  7159. }
  7160. return $this->view->fetch('procuremen/pick_add');
  7161. }
  7162. /**
  7163. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  7164. */
  7165. public function pickSubmit()
  7166. {
  7167. if (!$this->request->isPost()) {
  7168. $this->error(__('Invalid parameters'));
  7169. }
  7170. // ---------- 接口订单数据 ----------
  7171. $rowJson = $this->request->post('row_json', '');
  7172. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  7173. $companiesJson = $this->request->post('companies_json', '[]');
  7174. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  7175. $companies = json_decode($companiesJson, true);
  7176. if (!is_array($companies)) {
  7177. $this->error('供应商数据无效');
  7178. }
  7179. $issueCompanies = $this->normalizePickCompanies($companies);
  7180. if ($issueCompanies === []) {
  7181. $this->error('请至少选择一家合作供应商');
  7182. }
  7183. $issueNameLabels = [];
  7184. foreach ($issueCompanies as $pc) {
  7185. $issueNameLabels[] = $pc['name'];
  7186. }
  7187. $issueNamesSummary = implode('、', $issueNameLabels);
  7188. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  7189. if ($sysRq === '') {
  7190. $this->error('请选择招标截止日期');
  7191. }
  7192. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  7193. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  7194. (string)$this->request->post('delivery_deadline', ''),
  7195. true
  7196. );
  7197. $isMerge = count($mergeRows) > 1;
  7198. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  7199. $logMsg = '下发' . $procPart
  7200. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  7201. $issueTime = date('Y-m-d H:i:s');
  7202. $logSidList = [];
  7203. foreach ($mergeRows as $row) {
  7204. if (!is_array($row)) {
  7205. continue;
  7206. }
  7207. $sid = $this->extractScydgyRowId($row);
  7208. if ($this->isValidScydgyRowId($sid)) {
  7209. $logSidList[$sid] = true;
  7210. }
  7211. }
  7212. $existingBySid = [];
  7213. if ($logSidList !== []) {
  7214. try {
  7215. $existingRows = Db::table('purchase_order')
  7216. ->where('scydgy_id', 'in', array_keys($logSidList))
  7217. ->select();
  7218. if (is_array($existingRows)) {
  7219. foreach ($existingRows as $poRow) {
  7220. if (!is_array($poRow)) {
  7221. continue;
  7222. }
  7223. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7224. if ($this->isValidScydgyRowId($sid)) {
  7225. $existingBySid[$sid] = $poRow;
  7226. }
  7227. }
  7228. }
  7229. } catch (\Throwable $e) {
  7230. $existingBySid = [];
  7231. }
  7232. }
  7233. Db::startTrans();
  7234. try {
  7235. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  7236. foreach ($mergeRows as $row) {
  7237. if (!is_array($row)) {
  7238. continue;
  7239. }
  7240. $sid = $this->extractScydgyRowId($row);
  7241. $this->upsertPurchaseOrderFromRow(
  7242. $row,
  7243. $sysRqDb,
  7244. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7245. $issueTime,
  7246. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  7247. $deliveryDeadlineDb
  7248. );
  7249. }
  7250. foreach ($issueCompanies as $c) {
  7251. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7252. }
  7253. Db::commit();
  7254. } catch (\Throwable $e) {
  7255. Db::rollback();
  7256. $this->error($e->getMessage());
  7257. }
  7258. $poIdBySid = [];
  7259. if ($logSidList !== []) {
  7260. try {
  7261. $poIdBySid = Db::table('purchase_order')
  7262. ->where('scydgy_id', 'in', array_keys($logSidList))
  7263. ->column('id', 'scydgy_id');
  7264. } catch (\Throwable $e) {
  7265. $poIdBySid = [];
  7266. }
  7267. }
  7268. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  7269. if ($logSidList !== []) {
  7270. list($adminId, $adminName) = $this->GetUseName();
  7271. $logRows = [];
  7272. $seenLogSid = [];
  7273. foreach ($mergeRows as $row) {
  7274. if (!is_array($row)) {
  7275. continue;
  7276. }
  7277. $ids = $this->extractScydgyRowId($row);
  7278. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  7279. continue;
  7280. }
  7281. $seenLogSid[$ids] = true;
  7282. $poIdLog = null;
  7283. if (isset($poIdBySid[$ids])) {
  7284. $tid = (int)$poIdBySid[$ids];
  7285. $poIdLog = $tid > 0 ? $tid : null;
  7286. }
  7287. $logRows[] = ProcuremenOperLog::buildInsertRow(
  7288. $ids,
  7289. 'issue_submit',
  7290. $logMsg,
  7291. $poIdLog,
  7292. (int)$adminId,
  7293. (string)$adminName
  7294. );
  7295. }
  7296. if ($logRows !== []) {
  7297. try {
  7298. Db::table('purchase_order_oper_log')->insertAll($logRows);
  7299. } catch (\Throwable $e) {
  7300. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  7301. }
  7302. }
  7303. }
  7304. $notifyErrors = [];
  7305. $posNotify = [];
  7306. if ($logSidList !== []) {
  7307. try {
  7308. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  7309. } catch (\Throwable $e) {
  7310. $posNotify = [];
  7311. }
  7312. }
  7313. if (!is_array($posNotify)) {
  7314. $posNotify = [];
  7315. }
  7316. foreach ($posNotify as $i => $prow) {
  7317. if (is_array($posNotify[$i])) {
  7318. $posNotify[$i]['sys_rq'] = $sysRqDb;
  7319. }
  7320. }
  7321. $ccydhPick = '';
  7322. foreach ($mergeRows as $row) {
  7323. if (!is_array($row)) {
  7324. continue;
  7325. }
  7326. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  7327. if ($ccydhPick !== '') {
  7328. break;
  7329. }
  7330. }
  7331. $notifyBundleBase = [
  7332. 'ccydh' => $ccydhPick,
  7333. 'pos' => $posNotify,
  7334. 'merge_rows' => $mergeRows,
  7335. ];
  7336. try {
  7337. $this->notifyDryRunPreview = [];
  7338. foreach ($issueCompanies as $c) {
  7339. if (!is_array($c)) {
  7340. continue;
  7341. }
  7342. $cname = trim((string)($c['name'] ?? ''));
  7343. if ($cname === '') {
  7344. continue;
  7345. }
  7346. try {
  7347. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  7348. } catch (\Throwable $e) {
  7349. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7350. }
  7351. }
  7352. } catch (\Throwable $e) {
  7353. $this->error('通知发送失败:' . $e->getMessage());
  7354. }
  7355. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7356. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7357. }
  7358. if ($this->isProcuremenNotifyDryRun()) {
  7359. $this->success('【演练模式】已保存并生成通知预览', '', [
  7360. 'notify_dry_run' => true,
  7361. 'notify_preview' => $this->notifyDryRunPreview,
  7362. ]);
  7363. }
  7364. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  7365. }
  7366. /**
  7367. * 确认供应商弹窗
  7368. */
  7369. public function auditIssue()
  7370. {
  7371. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7372. if (is_array($ids)) {
  7373. $ids = isset($ids[0]) ? $ids[0] : '';
  7374. }
  7375. $ids = trim((string)$ids);
  7376. if ($ids === '') {
  7377. $this->error(__('Invalid parameters'));
  7378. }
  7379. if ($this->request->isPost()) {
  7380. $this->error('请使用弹窗内「确认」提交');
  7381. }
  7382. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7383. $pos = $bundle['pos'];
  7384. if ($pos === []) {
  7385. $this->error('该订单不在待确认供应商状态');
  7386. }
  7387. $po = $pos[0];
  7388. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7389. if ($quoteGroups === []) {
  7390. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  7391. }
  7392. $pickedName = '';
  7393. foreach ($pos as $poRow) {
  7394. if (!is_array($poRow)) {
  7395. continue;
  7396. }
  7397. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7398. if ($pn !== '') {
  7399. $pickedName = $pn;
  7400. break;
  7401. }
  7402. }
  7403. $this->view->assign('po', $po);
  7404. $this->view->assign('scydgyId', $ids);
  7405. $this->view->assign('orderCcydh', $bundle['ccydh']);
  7406. $mergeRows = $bundle['merge_rows'];
  7407. $this->view->assign('processRows', $mergeRows);
  7408. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  7409. $this->view->assign('processCount', count($mergeRows));
  7410. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  7411. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  7412. $this->view->assign('pickedCompanyName', $pickedName);
  7413. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7414. if ($sysRqForView === '') {
  7415. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7416. }
  7417. $this->view->assign('sysRq', $sysRqForView);
  7418. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  7419. if ($deliveryDeadlineForView === '') {
  7420. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7421. }
  7422. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7423. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  7424. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups));
  7425. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups) ? 1 : 0);
  7426. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  7427. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  7428. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  7429. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  7430. return $this->view->fetch('procuremen/audit_issue');
  7431. }
  7432. /**
  7433. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7434. *
  7435. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7436. */
  7437. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7438. {
  7439. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7440. }
  7441. /**
  7442. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7443. *
  7444. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7445. */
  7446. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7447. {
  7448. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7449. return false;
  7450. }
  7451. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7452. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7453. return true;
  7454. }
  7455. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7456. }
  7457. /**
  7458. * 确认页 — 补加供应商弹窗
  7459. */
  7460. public function auditAppend()
  7461. {
  7462. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7463. $this->error(__('You have no permission'));
  7464. }
  7465. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7466. if (is_array($ids)) {
  7467. $ids = isset($ids[0]) ? $ids[0] : '';
  7468. }
  7469. $ids = trim((string)$ids);
  7470. if ($ids === '') {
  7471. $this->error(__('Invalid parameters'));
  7472. }
  7473. if ($this->request->isPost()) {
  7474. $this->error('请使用弹窗内「确认」提交');
  7475. }
  7476. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7477. if (($bundle['pos'] ?? []) === []) {
  7478. $this->error('该订单不在待确认供应商状态');
  7479. }
  7480. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7481. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7482. $this->error('已开标验证,不能再补加供应商');
  7483. }
  7484. $this->error('已经超过了招标截止日期,不可操作');
  7485. }
  7486. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7487. $existingNames = [];
  7488. foreach ($quoteGroups as $g) {
  7489. if (!is_array($g)) {
  7490. continue;
  7491. }
  7492. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7493. if ($n !== '') {
  7494. $existingNames[$n] = true;
  7495. }
  7496. }
  7497. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7498. $mergeRows = $bundle['merge_rows'] ?? [];
  7499. $this->view->assign('scydgyId', $ids);
  7500. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7501. $this->view->assign('po', $po);
  7502. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7503. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7504. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7505. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7506. if ($sysRqForView === '') {
  7507. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7508. }
  7509. $this->view->assign('sysRq', $sysRqForView);
  7510. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7511. if ($deliveryDeadlineForView === '') {
  7512. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7513. }
  7514. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7515. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7516. }
  7517. /**
  7518. * 确认页 — 补加供应商提交
  7519. */
  7520. public function auditAppendSubmit()
  7521. {
  7522. if (!$this->request->isPost()) {
  7523. $this->error(__('Invalid parameters'));
  7524. }
  7525. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7526. $this->error(__('You have no permission'));
  7527. }
  7528. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7529. if ($ids === '') {
  7530. $this->error(__('Invalid parameters'));
  7531. }
  7532. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7533. if (($bundle['pos'] ?? []) === []) {
  7534. $this->error('该订单不在待确认供应商状态');
  7535. }
  7536. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7537. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7538. $this->error('已开标验证,不能再补加供应商');
  7539. }
  7540. $this->error('已经超过了招标截止日期,不可操作');
  7541. }
  7542. $companiesJson = $this->request->post('companies_json', '[]');
  7543. $companies = json_decode((string)$companiesJson, true);
  7544. if (!is_array($companies)) {
  7545. $this->error('供应商数据无效');
  7546. }
  7547. $issueCompanies = $this->normalizePickCompanies($companies);
  7548. if ($issueCompanies === []) {
  7549. $this->error('请至少选择一家合作供应商');
  7550. }
  7551. $mergeRows = $bundle['merge_rows'] ?? [];
  7552. if (!is_array($mergeRows) || $mergeRows === []) {
  7553. $this->error('未找到工序行,无法补加');
  7554. }
  7555. $existingNames = [];
  7556. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7557. if (!is_array($g)) {
  7558. continue;
  7559. }
  7560. $n = trim((string)($g['company_name'] ?? ''));
  7561. if ($n !== '') {
  7562. $existingNames[$n] = true;
  7563. }
  7564. }
  7565. $toAdd = [];
  7566. foreach ($issueCompanies as $c) {
  7567. if (!is_array($c)) {
  7568. continue;
  7569. }
  7570. $n = trim((string)($c['name'] ?? ''));
  7571. if ($n === '' || isset($existingNames[$n])) {
  7572. continue;
  7573. }
  7574. $toAdd[] = $c;
  7575. }
  7576. if ($toAdd === []) {
  7577. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7578. }
  7579. $addedNames = [];
  7580. Db::startTrans();
  7581. try {
  7582. foreach ($toAdd as $c) {
  7583. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7584. $addedNames[] = trim((string)($c['name'] ?? ''));
  7585. }
  7586. Db::commit();
  7587. } catch (\Throwable $e) {
  7588. Db::rollback();
  7589. $this->error($e->getMessage());
  7590. }
  7591. $notifyErrors = [];
  7592. $notifyBundleBase = [
  7593. 'ccydh' => $bundle['ccydh'] ?? '',
  7594. 'pos' => $bundle['pos'] ?? [],
  7595. 'merge_rows' => $mergeRows,
  7596. ];
  7597. foreach ($toAdd as $c) {
  7598. if (!is_array($c)) {
  7599. continue;
  7600. }
  7601. $cname = trim((string)($c['name'] ?? ''));
  7602. if ($cname === '') {
  7603. continue;
  7604. }
  7605. try {
  7606. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7607. } catch (\Throwable $e) {
  7608. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7609. }
  7610. }
  7611. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7612. $seenLogSid = [];
  7613. foreach ($bundle['pos'] ?? [] as $poRow) {
  7614. if (!is_array($poRow)) {
  7615. continue;
  7616. }
  7617. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7618. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7619. continue;
  7620. }
  7621. $seenLogSid[$sid] = true;
  7622. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7623. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7624. }
  7625. if ($seenLogSid === []) {
  7626. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7627. if ($this->isValidScydgyRowId($logSid)) {
  7628. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7629. }
  7630. }
  7631. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7632. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7633. }
  7634. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7635. }
  7636. /**
  7637. * 开标双重验证 — 可选验证人列表
  7638. */
  7639. public function bidOpenUsers()
  7640. {
  7641. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7642. $this->error('无权限');
  7643. }
  7644. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7645. if ($scydgyId !== '') {
  7646. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7647. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7648. $this->success('已完成开标验证', null, [
  7649. 'verified' => 1,
  7650. 'users' => [],
  7651. ]);
  7652. }
  7653. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7654. }
  7655. $this->success('', null, [
  7656. 'verified' => 0,
  7657. 'users' => $this->listBidOpenVerifierCandidates(),
  7658. ]);
  7659. }
  7660. /**
  7661. * 开标双重验证 — 向指定管理员发送短信验证码
  7662. */
  7663. public function bidOpenSendCode()
  7664. {
  7665. if (!$this->request->isPost()) {
  7666. $this->error(__('Invalid parameters'));
  7667. }
  7668. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7669. $this->error('无权限');
  7670. }
  7671. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7672. $adminId = (int)$this->request->post('admin_id', 0);
  7673. if ($scydgyId === '' || $adminId <= 0) {
  7674. $this->error('参数无效');
  7675. }
  7676. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7677. if ($bundle['pos'] === []) {
  7678. $this->error('该订单不在待确认供应商状态');
  7679. }
  7680. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7681. $this->success('已完成开标验证,无需重复发送');
  7682. }
  7683. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7684. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7685. if ($ccydh === '') {
  7686. $this->error('订单号无效');
  7687. }
  7688. $admin = $this->loadBidOpenAdminUser($adminId);
  7689. if ($admin === null) {
  7690. $this->error('验证人无效或未绑定手机号');
  7691. }
  7692. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7693. $cd = max(30, min(120, $cd));
  7694. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7695. $this->error('发送过于频繁,请稍后再试');
  7696. }
  7697. $code = (string)random_int(100000, 999999);
  7698. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7699. $ttl = max(60, min(600, $ttl));
  7700. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7701. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7702. try {
  7703. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7704. } catch (\Throwable $e) {
  7705. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7706. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7707. $this->error($e->getMessage());
  7708. }
  7709. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7710. }
  7711. /**
  7712. * 开标双重验证 — 两人验证码校验并记录
  7713. */
  7714. public function bidOpenVerify()
  7715. {
  7716. if (!$this->request->isPost()) {
  7717. $this->error(__('Invalid parameters'));
  7718. }
  7719. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7720. $this->error('无权限');
  7721. }
  7722. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7723. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7724. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7725. $code1 = trim((string)$this->request->post('code1', ''));
  7726. $code2 = trim((string)$this->request->post('code2', ''));
  7727. if ($scydgyId === '') {
  7728. $this->error('参数无效');
  7729. }
  7730. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7731. $this->error('请选择两位验证人');
  7732. }
  7733. if ($verifier1Id === $verifier2Id) {
  7734. $this->error('两位验证人不能相同');
  7735. }
  7736. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7737. $this->error('请输入6位短信验证码');
  7738. }
  7739. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7740. if ($bundle['pos'] === []) {
  7741. $this->error('该订单不在待确认供应商状态');
  7742. }
  7743. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7744. if ($ccydh === '') {
  7745. $this->error('订单号无效');
  7746. }
  7747. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7748. $this->success('已完成开标验证');
  7749. }
  7750. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7751. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7752. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7753. if ($verifier1 === null || $verifier2 === null) {
  7754. $this->error('验证人无效或未绑定手机号');
  7755. }
  7756. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7757. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7758. }
  7759. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7760. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7761. }
  7762. try {
  7763. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7764. } catch (\Throwable $e) {
  7765. $this->error($e->getMessage());
  7766. }
  7767. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7768. }
  7769. /**
  7770. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7771. */
  7772. public function auditSubmit()
  7773. {
  7774. if (!$this->request->isPost()) {
  7775. $this->error(__('Invalid parameters'));
  7776. }
  7777. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7778. if ($scydgyId === '') {
  7779. $this->error('参数无效');
  7780. }
  7781. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7782. $pos = $bundle['pos'];
  7783. $mergeRows = $bundle['merge_rows'];
  7784. if ($pos === [] || $mergeRows === []) {
  7785. $this->error('该订单不在待确认供应商状态');
  7786. }
  7787. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7788. if ($quoteGroups === []) {
  7789. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7790. }
  7791. $companyName = trim((string)$this->request->post('selected_company', ''));
  7792. if ($companyName === '') {
  7793. $this->error('请选择一家供应商');
  7794. }
  7795. $matched = null;
  7796. foreach ($quoteGroups as $g) {
  7797. if (!is_array($g)) {
  7798. continue;
  7799. }
  7800. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7801. $matched = $g;
  7802. break;
  7803. }
  7804. }
  7805. if ($matched === null) {
  7806. $this->error('所选供应商不在本单报价列表中');
  7807. }
  7808. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7809. if ($sysRqDb === '') {
  7810. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  7811. } else {
  7812. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  7813. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  7814. }
  7815. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  7816. $this->error('未到招标截止日期,暂不可确认');
  7817. }
  7818. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7819. $this->error('请先完成开标双重验证后再确认供应商');
  7820. }
  7821. $procCnt = count($mergeRows);
  7822. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7823. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  7824. Db::startTrans();
  7825. try {
  7826. foreach ($pos as $poRow) {
  7827. if (!is_array($poRow)) {
  7828. continue;
  7829. }
  7830. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7831. if (!$this->isValidScydgyRowId($sid)) {
  7832. continue;
  7833. }
  7834. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7835. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7836. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7837. 'pick_company_name' => $companyName,
  7838. 'sys_rq' => $sysRqDb,
  7839. ]);
  7840. }
  7841. Db::commit();
  7842. } catch (\Throwable $e) {
  7843. Db::rollback();
  7844. $this->error($e->getMessage());
  7845. }
  7846. foreach ($pos as $poRow) {
  7847. if (!is_array($poRow)) {
  7848. continue;
  7849. }
  7850. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7851. if (!$this->isValidScydgyRowId($sid)) {
  7852. continue;
  7853. }
  7854. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7855. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7856. }
  7857. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7858. }
  7859. /**
  7860. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7861. */
  7862. public function auditResendSms()
  7863. {
  7864. if (!$this->request->isPost()) {
  7865. $this->error(__('Invalid parameters'));
  7866. }
  7867. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7868. if ($scydgyId === '') {
  7869. $this->error('参数无效');
  7870. }
  7871. $loaded = $this->loadAuditResendBundle($scydgyId);
  7872. $mergeRows = $loaded['merge_rows'];
  7873. $bundle = $loaded['bundle'];
  7874. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7875. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7876. if ($quoteGroups === []) {
  7877. $this->error('暂无可通知的供应商');
  7878. }
  7879. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7880. $companiesJson = (string)$this->request->post('companies_json', '');
  7881. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7882. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7883. }
  7884. /**
  7885. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7886. */
  7887. public function auditResendEmail()
  7888. {
  7889. if (!$this->request->isPost()) {
  7890. $this->error(__('Invalid parameters'));
  7891. }
  7892. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7893. if ($scydgyId === '') {
  7894. $this->error('参数无效');
  7895. }
  7896. $loaded = $this->loadAuditResendBundle($scydgyId);
  7897. $mergeRows = $loaded['merge_rows'];
  7898. $bundle = $loaded['bundle'];
  7899. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7900. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7901. if ($quoteGroups === []) {
  7902. $this->error('暂无可通知的供应商');
  7903. }
  7904. $companiesJson = (string)$this->request->post('companies_json', '');
  7905. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7906. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7907. if ($companiesJson === '' && $selectedCompany === '') {
  7908. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7909. }
  7910. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7911. }
  7912. /**
  7913. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7914. *
  7915. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7916. * @return array<int, true> 已处理的 scydgy_id 集合
  7917. */
  7918. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7919. {
  7920. $pos = $bundle['pos'] ?? [];
  7921. if (!is_array($pos) || $pos === []) {
  7922. return [];
  7923. }
  7924. $sids = [];
  7925. $poIdBySid = [];
  7926. foreach ($pos as $poRow) {
  7927. if (!is_array($poRow)) {
  7928. continue;
  7929. }
  7930. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7931. if ($this->isValidScydgyRowId($sid)) {
  7932. $sids[$sid] = true;
  7933. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7934. if ($poId > 0) {
  7935. $poIdBySid[$sid] = $poId;
  7936. }
  7937. }
  7938. }
  7939. if ($sids === []) {
  7940. return [];
  7941. }
  7942. $logMsg = '重新下发';
  7943. $suffix = trim((string)$logSuffix, ',, ');
  7944. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7945. $logMsg .= ':从历史存证退回协助初选';
  7946. } else {
  7947. $logMsg .= ':退回协助初选';
  7948. }
  7949. Db::table('purchase_order')
  7950. ->where('scydgy_id', 'in', array_keys($sids))
  7951. ->update([
  7952. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7953. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7954. 'pick_company_name' => '',
  7955. 'pick_time' => null,
  7956. 'sys_rq' => null,
  7957. 'mod_rq' => null,
  7958. ]);
  7959. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7960. foreach (array_keys($sids) as $sid) {
  7961. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  7962. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7963. }
  7964. return $sids;
  7965. }
  7966. /**
  7967. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7968. *
  7969. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7970. */
  7971. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7972. {
  7973. $scydgyId = trim($scydgyId);
  7974. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7975. if ($scydgyId === '') {
  7976. return $empty;
  7977. }
  7978. try {
  7979. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7980. } catch (\Throwable $e) {
  7981. $anchor = null;
  7982. }
  7983. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7984. return $empty;
  7985. }
  7986. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7987. if ($ccydh === '') {
  7988. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7989. }
  7990. try {
  7991. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7992. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7993. $pos = $query->order('scydgy_id', 'asc')->select();
  7994. } catch (\Throwable $e) {
  7995. $pos = [$anchor];
  7996. }
  7997. if (!is_array($pos) || $pos === []) {
  7998. $pos = [$anchor];
  7999. }
  8000. return [
  8001. 'ccydh' => $ccydh,
  8002. 'pos' => $pos,
  8003. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  8004. ];
  8005. }
  8006. protected function purchaseOrderRowIsCompleted(array $po): bool
  8007. {
  8008. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  8009. }
  8010. /**
  8011. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  8012. *
  8013. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  8014. */
  8015. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  8016. {
  8017. $scydgyId = trim($scydgyId);
  8018. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  8019. if ($scydgyId === '') {
  8020. return $empty;
  8021. }
  8022. try {
  8023. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  8024. } catch (\Throwable $e) {
  8025. $anchor = null;
  8026. }
  8027. if (!is_array($anchor)) {
  8028. return $empty;
  8029. }
  8030. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  8031. if ($ccydh === '') {
  8032. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  8033. }
  8034. try {
  8035. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  8036. } catch (\Throwable $e) {
  8037. $pos = [$anchor];
  8038. }
  8039. if (!is_array($pos) || $pos === []) {
  8040. $pos = [$anchor];
  8041. }
  8042. return [
  8043. 'ccydh' => $ccydh,
  8044. 'pos' => $pos,
  8045. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  8046. ];
  8047. }
  8048. /**
  8049. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  8050. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  8051. */
  8052. public function auditAbandon()
  8053. {
  8054. if (!$this->request->isPost()) {
  8055. $this->error(__('Invalid parameters'));
  8056. }
  8057. $anchorIds = [];
  8058. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  8059. if ($batchRaw !== '') {
  8060. $decoded = json_decode($batchRaw, true);
  8061. if (is_array($decoded)) {
  8062. foreach ($decoded as $id) {
  8063. $s = trim((string)$id);
  8064. if ($s !== '') {
  8065. $anchorIds[] = $s;
  8066. }
  8067. }
  8068. }
  8069. }
  8070. if ($anchorIds === []) {
  8071. $single = trim((string)$this->request->post('scydgy_id', ''));
  8072. if ($single !== '') {
  8073. $anchorIds[] = $single;
  8074. }
  8075. }
  8076. if ($anchorIds === []) {
  8077. $this->error('请至少选择一条订单');
  8078. }
  8079. $processedCcydh = [];
  8080. $doneOrders = 0;
  8081. $allSids = [];
  8082. Db::startTrans();
  8083. try {
  8084. foreach ($anchorIds as $anchorId) {
  8085. $fromArchive = false;
  8086. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  8087. if (($bundle['pos'] ?? []) === []) {
  8088. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  8089. $fromArchive = ($bundle['pos'] ?? []) !== [];
  8090. }
  8091. if (($bundle['pos'] ?? []) === []) {
  8092. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  8093. $fromArchive = ($bundle['pos'] ?? []) !== [];
  8094. }
  8095. if (($bundle['pos'] ?? []) === []) {
  8096. continue;
  8097. }
  8098. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  8099. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  8100. if (isset($processedCcydh[$dedupeKey])) {
  8101. continue;
  8102. }
  8103. $processedCcydh[$dedupeKey] = true;
  8104. $sids = $fromArchive
  8105. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  8106. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  8107. if ($sids === []) {
  8108. continue;
  8109. }
  8110. $doneOrders++;
  8111. foreach (array_keys($sids) as $sid) {
  8112. $allSids[(int)$sid] = true;
  8113. }
  8114. }
  8115. if ($doneOrders < 1) {
  8116. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  8117. }
  8118. Db::commit();
  8119. } catch (\Throwable $e) {
  8120. Db::rollback();
  8121. $this->error($e->getMessage());
  8122. }
  8123. $this->pickHiddenScydgySetCache = null;
  8124. $msg = $doneOrders > 1
  8125. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  8126. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  8127. $this->success($msg);
  8128. }
  8129. /**
  8130. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  8131. */
  8132. public function archiveAbandon()
  8133. {
  8134. return $this->auditAbandon();
  8135. }
  8136. /**
  8137. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  8138. */
  8139. public function purchaseApprovalReject()
  8140. {
  8141. if (!$this->request->isPost() || !$this->request->isAjax()) {
  8142. $this->error(__('Invalid parameters'));
  8143. }
  8144. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  8145. $this->error(__('You have no permission'));
  8146. }
  8147. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  8148. $decoded = json_decode($batchRaw, true);
  8149. if (!is_array($decoded) || $decoded === []) {
  8150. $this->error('提交数据无效');
  8151. }
  8152. $done = 0;
  8153. Db::startTrans();
  8154. try {
  8155. foreach ($decoded as $item) {
  8156. if (!is_array($item)) {
  8157. continue;
  8158. }
  8159. $sid = (int)($item['scydgy_id'] ?? 0);
  8160. if (!$this->isValidScydgyRowId($sid)) {
  8161. continue;
  8162. }
  8163. $this->runPurchaseApprovalRejectForSid($sid);
  8164. $done++;
  8165. }
  8166. if ($done < 1) {
  8167. throw new \Exception('所选订单均不在待审批状态');
  8168. }
  8169. Db::commit();
  8170. } catch (\Throwable $e) {
  8171. Db::rollback();
  8172. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  8173. }
  8174. $this->pickHiddenScydgySetCache = null;
  8175. $this->success('已驳回并退回「协助审批下发」');
  8176. }
  8177. /**
  8178. * @throws \Exception
  8179. */
  8180. protected function runPurchaseApprovalRejectForSid(int $sid): void
  8181. {
  8182. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  8183. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  8184. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  8185. $allIds = $this->purchaseOrderDetail($sid);
  8186. if ($allIds === []) {
  8187. throw new \Exception('未找到下发明细');
  8188. }
  8189. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8190. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  8191. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8192. 'pick_company_name' => '',
  8193. ]);
  8194. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  8195. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  8196. $poId = 0;
  8197. try {
  8198. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  8199. if (is_array($po)) {
  8200. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8201. }
  8202. } catch (\Throwable $e) {
  8203. }
  8204. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  8205. }
  8206. /**
  8207. * 审核弹窗(旧入口,POST 已关闭)
  8208. */
  8209. public function review()
  8210. {
  8211. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  8212. $this->error(__('You have no permission'));
  8213. }
  8214. if ($this->request->isPost()) {
  8215. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  8216. }
  8217. $this->view->assign('pickMode', 0);
  8218. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  8219. }
  8220. /**
  8221. * 审核弹窗获取公司列表
  8222. */
  8223. public function reviewCompanies()
  8224. {
  8225. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  8226. $this->error(__('You have no permission'));
  8227. }
  8228. if (!$this->request->isAjax()) {
  8229. $this->error(__('Invalid parameters'));
  8230. }
  8231. $list = [];
  8232. try {
  8233. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  8234. $rows = Db::table('customer')
  8235. ->where(function ($q) {
  8236. $q->where('status', 1)
  8237. ->whereOr('status', '1')
  8238. ->whereOr('status', '')
  8239. ->whereNull('status');
  8240. })
  8241. ->order('id', 'desc')
  8242. ->select();
  8243. } catch (\Throwable $e) {
  8244. $this->success('', '', []);
  8245. return;
  8246. }
  8247. if (!is_array($rows)) {
  8248. $this->success('', '', []);
  8249. return;
  8250. }
  8251. $detailColCandidates = [
  8252. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  8253. 'company_detail', 'company_desc', 'address',
  8254. ];
  8255. foreach ($rows as $row) {
  8256. if (!is_array($row)) {
  8257. continue;
  8258. }
  8259. $norm = [];
  8260. foreach ($row as $k => $v) {
  8261. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  8262. }
  8263. $row = $norm;
  8264. $st = $row['status'] ?? '';
  8265. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  8266. continue;
  8267. }
  8268. $payload = $this->buildCustomerContactPayloadFromRow($row);
  8269. if ($payload === null) {
  8270. continue;
  8271. }
  8272. $detail = '';
  8273. foreach ($detailColCandidates as $dk) {
  8274. if (!isset($row[$dk])) {
  8275. continue;
  8276. }
  8277. $dv = trim((string)$row[$dk]);
  8278. if ($dv !== '') {
  8279. $detail = $dv;
  8280. break;
  8281. }
  8282. }
  8283. $payload['detail'] = $detail;
  8284. $list[] = $this->maskSupplierContactFields($payload);
  8285. }
  8286. $this->success('', '', $list);
  8287. }
  8288. /**
  8289. * 采购确认-下发明细弹窗:
  8290. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  8291. */
  8292. public function outward_detail()
  8293. {
  8294. $ids = $this->request->param('ids', $this->request->param('id', ''));
  8295. if (is_array($ids)) {
  8296. $ids = isset($ids[0]) ? $ids[0] : '';
  8297. }
  8298. $ids = trim((string)$ids);
  8299. if ($ids === '') {
  8300. $this->error(__('Invalid parameters'));
  8301. }
  8302. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  8303. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  8304. $wffTab = 'all';
  8305. }
  8306. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  8307. $purchaseOrderId = 0;
  8308. $po = null;
  8309. try {
  8310. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8311. if (is_array($po)) {
  8312. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8313. }
  8314. } catch (\Throwable $e) {
  8315. $purchaseOrderId = 0;
  8316. $po = null;
  8317. }
  8318. if (!$isPurchaseConfirm && is_array($po)) {
  8319. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  8320. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  8321. $isPurchaseConfirm = true;
  8322. }
  8323. }
  8324. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  8325. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  8326. $confirmProcessCount = 1;
  8327. $confirmPickGroups = [];
  8328. $processDisplayRows = [];
  8329. $allDetailsBySid = [];
  8330. $requiredSidList = [];
  8331. $sidList = [$ids];
  8332. if ($isPurchaseConfirm) {
  8333. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  8334. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  8335. if ($mergeRows !== []) {
  8336. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  8337. }
  8338. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  8339. if ($confirmBundle['pos'] !== []) {
  8340. $sidList = [];
  8341. foreach ($confirmBundle['pos'] as $poRow) {
  8342. if (!is_array($poRow)) {
  8343. continue;
  8344. }
  8345. $sid = (int)($poRow['scydgy_id'] ?? 0);
  8346. if (!$this->isValidScydgyRowId($sid)) {
  8347. continue;
  8348. }
  8349. $sidList[] = (string)$sid;
  8350. $requiredSidList[] = $sid;
  8351. }
  8352. }
  8353. if ($sidList === []) {
  8354. $sidList = [$ids];
  8355. $requiredSidList = [(int)$ids];
  8356. }
  8357. $confirmProcessCount = max(1, count($requiredSidList));
  8358. if (is_array($po) && $purchaseOrderId <= 0) {
  8359. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8360. }
  8361. }
  8362. $rows = [];
  8363. try {
  8364. if (count($sidList) === 1) {
  8365. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  8366. } else {
  8367. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  8368. }
  8369. } catch (\Throwable $e) {
  8370. $rows = [];
  8371. }
  8372. if ($isPurchaseConfirm) {
  8373. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  8374. }
  8375. foreach ($rows as &$r) {
  8376. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  8377. $r['id'] = $r['ID'];
  8378. }
  8379. if (isset($r['createtime'])) {
  8380. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  8381. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  8382. } else {
  8383. $r['createtime_text'] = (string)$r['createtime'];
  8384. }
  8385. } else {
  8386. $r['createtime_text'] = '';
  8387. }
  8388. if (is_array($r)) {
  8389. $r = $this->maskSupplierContactFields($r);
  8390. }
  8391. }
  8392. unset($r);
  8393. $pickedCompanyName = '';
  8394. if ($isPurchaseConfirm) {
  8395. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  8396. if (!is_array($poRow)) {
  8397. continue;
  8398. }
  8399. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  8400. if ($pn !== '') {
  8401. $pickedCompanyName = $pn;
  8402. break;
  8403. }
  8404. }
  8405. }
  8406. $this->view->assign('rows', $rows ?: []);
  8407. $this->view->assign('rowCount', count($rows ?: []));
  8408. $this->view->assign('scydgyId', $ids);
  8409. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  8410. $this->view->assign('headTitle', $headTitle);
  8411. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  8412. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  8413. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  8414. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  8415. $this->view->assign('processDisplayRows', $processDisplayRows);
  8416. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8417. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8418. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8419. $this->view->assign('bidOpenVerified', ($isPurchaseConfirm && $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle)) ? 1 : 0);
  8420. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups));
  8421. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups) ? 1 : 0);
  8422. $sysRqDisplay = '—';
  8423. if ($isPurchaseConfirm) {
  8424. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8425. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8426. );
  8427. }
  8428. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8429. $this->view->assign('sysRq', $isPurchaseConfirm
  8430. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8431. : '');
  8432. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8433. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8434. : '');
  8435. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8436. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8437. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8438. if ($isPurchaseConfirm) {
  8439. return $this->view->fetch();
  8440. }
  8441. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8442. $this->view->engine->layout(false);
  8443. try {
  8444. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8445. $this->view->assign('dialogBody', $bodyHtml);
  8446. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8447. } finally {
  8448. if ($restoreLayout) {
  8449. $this->view->engine->layout($restoreLayout);
  8450. }
  8451. }
  8452. }
  8453. /**
  8454. * 月度导出记录表(不存在时自动创建)
  8455. */
  8456. protected function ensurePurchaseMonthExportLogTable(): void
  8457. {
  8458. try {
  8459. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8460. } catch (\Throwable $e) {
  8461. Db::execute(
  8462. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8463. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8464. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8465. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8466. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8467. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8468. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8469. `createtime` int(10) unsigned DEFAULT NULL,
  8470. PRIMARY KEY (`id`),
  8471. KEY `idx_ym` (`ym`),
  8472. KEY `idx_ct` (`createtime`)
  8473. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8474. );
  8475. }
  8476. }
  8477. /**
  8478. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8479. *
  8480. * @param array<int, mixed> $dbRows
  8481. * @return array<int, array<string, mixed>>
  8482. */
  8483. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8484. {
  8485. $keyword = trim((string)$this->request->get('search', ''));
  8486. if ($keyword === '') {
  8487. $keyword = trim((string)$this->request->request('search', ''));
  8488. }
  8489. $filter = $this->request->get('filter', '');
  8490. $op = $this->request->get('op', '');
  8491. if (is_string($filter) && $filter !== '') {
  8492. $filterArr = (array)json_decode($filter, true);
  8493. } else {
  8494. $filterArr = is_array($filter) ? $filter : [];
  8495. }
  8496. if (is_string($op) && $op !== '') {
  8497. $opArr = (array)json_decode($op, true);
  8498. } else {
  8499. $opArr = is_array($op) ? $op : [];
  8500. }
  8501. if ($keyword === '' && $filterArr === []) {
  8502. return array_values(array_filter($dbRows, 'is_array'));
  8503. }
  8504. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8505. $out = [];
  8506. foreach ($dbRows as $row) {
  8507. if (!is_array($row)) {
  8508. continue;
  8509. }
  8510. if ($keyword !== '') {
  8511. $hit = false;
  8512. foreach ($searchFields as $f) {
  8513. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8514. $hit = true;
  8515. break;
  8516. }
  8517. }
  8518. if (!$hit) {
  8519. continue;
  8520. }
  8521. }
  8522. $passFilter = true;
  8523. foreach ($filterArr as $field => $val) {
  8524. $field = (string)$field;
  8525. $val = trim((string)$val);
  8526. if ($field === '' || $val === '') {
  8527. continue;
  8528. }
  8529. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8530. continue;
  8531. }
  8532. $cell = (string)($row[$field] ?? '');
  8533. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8534. if ($mode === '=' || $mode === 'EQUAL') {
  8535. if (strcasecmp($cell, $val) !== 0) {
  8536. $passFilter = false;
  8537. break;
  8538. }
  8539. } elseif (mb_stripos($cell, $val) === false) {
  8540. $passFilter = false;
  8541. break;
  8542. }
  8543. }
  8544. if (!$passFilter) {
  8545. continue;
  8546. }
  8547. $out[] = $row;
  8548. }
  8549. return $out;
  8550. }
  8551. /**
  8552. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8553. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8554. */
  8555. public function export_month_outward()
  8556. {
  8557. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8558. $this->error(__('You have no permission'));
  8559. }
  8560. $bundle = $this->prepareMonthOutwardExportBundle();
  8561. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8562. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  8563. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  8564. $spreadsheet = new Spreadsheet();
  8565. $sheet = $spreadsheet->getActiveSheet();
  8566. $sheet->setTitle('外协加工明细');
  8567. $mon = (int)substr($ym, 5, 2);
  8568. $sheet->mergeCells('A1:H1');
  8569. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8570. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8571. $sheet->getStyle('A1')->getAlignment()
  8572. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8573. ->setVertical(Alignment::VERTICAL_CENTER);
  8574. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8575. $col = 'A';
  8576. foreach ($headers as $h) {
  8577. $sheet->setCellValue($col . '2', $h);
  8578. $col++;
  8579. }
  8580. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8581. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8582. $rowNum = 3;
  8583. $sumSubtotalCounts = 0;
  8584. $grandAmount = 0.0;
  8585. $globalSeq = 0;
  8586. if ($groups === []) {
  8587. $sheet->mergeCells('A3:H3');
  8588. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8589. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8590. $rowNum = 4;
  8591. } else {
  8592. foreach ($groups as $items) {
  8593. if ($items === []) {
  8594. continue;
  8595. }
  8596. $groupLineCount = count($items);
  8597. $subAmount = 0.0;
  8598. foreach ($items as $line) {
  8599. $globalSeq++;
  8600. $dr = $line['detail'];
  8601. $amt = $this->procuremenExportAmount($dr);
  8602. $subAmount += $amt;
  8603. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8604. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8605. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8606. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8607. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8608. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8609. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8610. $sheet->setCellValue('H' . $rowNum, $amt);
  8611. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8612. $rowNum++;
  8613. }
  8614. $sumSubtotalCounts += $groupLineCount;
  8615. $grandAmount += $subAmount;
  8616. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8617. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8618. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8619. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8620. ->setVertical(Alignment::VERTICAL_CENTER);
  8621. $rowNum++;
  8622. }
  8623. }
  8624. $sheet->setCellValue('A' . $rowNum, '总计');
  8625. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8626. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8627. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8628. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8629. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8630. $lastRow = $rowNum;
  8631. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8632. 'borders' => [
  8633. 'allBorders' => [
  8634. 'borderStyle' => Border::BORDER_THIN,
  8635. 'color' => ['rgb' => '000000'],
  8636. ],
  8637. ],
  8638. ]);
  8639. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8640. if ($lastRow >= 3) {
  8641. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8642. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8643. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8644. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8645. }
  8646. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8647. $sheet->getColumnDimension('A')->setWidth(7);
  8648. $sheet->getColumnDimension('B')->setWidth(16);
  8649. $sheet->getColumnDimension('C')->setWidth(52);
  8650. $sheet->getColumnDimension('D')->setWidth(32);
  8651. $sheet->getColumnDimension('E')->setWidth(12);
  8652. $sheet->getColumnDimension('F')->setWidth(44);
  8653. $sheet->getColumnDimension('G')->setWidth(26);
  8654. $sheet->getColumnDimension('H')->setWidth(13);
  8655. $sheet->getRowDimension(1)->setRowHeight(28);
  8656. $ymCompact = str_replace('-', '', $ym);
  8657. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8658. $filename = $fileBase . '.xlsx';
  8659. try {
  8660. $this->ensurePurchaseMonthExportLogTable();
  8661. list($adminId, $adminName) = $this->GetUseName();
  8662. Db::table('purchase_month_export_log')->insert([
  8663. 'ym' => $ym,
  8664. 'admin_id' => (int)$adminId,
  8665. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8666. 'row_count' => count($exportLines),
  8667. 'total_amount' => round($grandAmount, 2),
  8668. 'createtime' => time(),
  8669. ]);
  8670. } catch (\Throwable $e) {
  8671. Log::write('month export log: ' . $e->getMessage(), 'error');
  8672. }
  8673. if (ob_get_length()) {
  8674. ob_end_clean();
  8675. }
  8676. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8677. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8678. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8679. header('Cache-Control: max-age=0');
  8680. $writer = new Xlsx($spreadsheet);
  8681. $writer->save('php://output');
  8682. $spreadsheet->disconnectWorksheets();
  8683. unset($spreadsheet);
  8684. exit;
  8685. }
  8686. /**
  8687. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  8688. */
  8689. public function export_month_quote()
  8690. {
  8691. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  8692. $this->error(__('You have no permission'));
  8693. }
  8694. $bundle = $this->prepareMonthOutwardExportBundle();
  8695. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8696. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  8697. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  8698. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8699. $spreadsheet = new Spreadsheet();
  8700. $sheet = $spreadsheet->getActiveSheet();
  8701. $sheet->setTitle('供应商报价明细');
  8702. $mon = (int)substr($ym, 5, 2);
  8703. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  8704. $sheet->getColumnDimension('A')->setWidth(7);
  8705. $sheet->getColumnDimension('B')->setWidth(16);
  8706. $sheet->getColumnDimension('C')->setWidth(52);
  8707. $sheet->getColumnDimension('D')->setWidth(26);
  8708. $sheet->getColumnDimension('E')->setWidth(32);
  8709. $sheet->getColumnDimension('F')->setWidth(12);
  8710. $sheet->getColumnDimension('G')->setWidth(14);
  8711. $sheet->getColumnDimension('H')->setWidth(12);
  8712. if ($quoteLastRow < 1) {
  8713. $quoteLastRow = 3;
  8714. }
  8715. $ymCompact = str_replace('-', '', $ym);
  8716. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  8717. if (ob_get_length()) {
  8718. ob_end_clean();
  8719. }
  8720. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  8721. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8722. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8723. header('Cache-Control: max-age=0');
  8724. $writer = new Xlsx($spreadsheet);
  8725. $writer->save('php://output');
  8726. $spreadsheet->disconnectWorksheets();
  8727. unset($spreadsheet);
  8728. exit;
  8729. }
  8730. /**
  8731. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  8732. *
  8733. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  8734. */
  8735. protected function prepareMonthOutwardExportBundle(): array
  8736. {
  8737. $this->request->filter(['strip_tags', 'trim']);
  8738. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8739. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8740. $ym = date('Y-m');
  8741. }
  8742. $dbRows = [];
  8743. try {
  8744. $query = Db::table('purchase_order');
  8745. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8746. $dbRows = $query->select();
  8747. } catch (\Throwable $e) {
  8748. $dbRows = [];
  8749. }
  8750. if (!is_array($dbRows)) {
  8751. $dbRows = [];
  8752. }
  8753. $completeTsMap = [];
  8754. $sidList = [];
  8755. foreach ($dbRows as $dbRow) {
  8756. if (!is_array($dbRow)) {
  8757. continue;
  8758. }
  8759. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8760. if ($sid > 0) {
  8761. $sidList[$sid] = true;
  8762. }
  8763. }
  8764. if ($sidList !== []) {
  8765. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8766. }
  8767. $searchKw = trim((string)$this->request->get('search', ''));
  8768. if ($searchKw === '') {
  8769. $searchKw = trim((string)$this->request->request('search', ''));
  8770. }
  8771. $filterRaw = $this->request->get('filter', '');
  8772. $filterArrTmp = [];
  8773. if (is_string($filterRaw) && $filterRaw !== '') {
  8774. $filterArrTmp = (array)json_decode($filterRaw, true);
  8775. } elseif (is_array($filterRaw)) {
  8776. $filterArrTmp = $filterRaw;
  8777. }
  8778. $hasSearch = ($searchKw !== '');
  8779. if (!$hasSearch) {
  8780. foreach ($filterArrTmp as $fv) {
  8781. if (trim((string)$fv) !== '') {
  8782. $hasSearch = true;
  8783. break;
  8784. }
  8785. }
  8786. }
  8787. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8788. if (!is_array($dbRow)) {
  8789. return false;
  8790. }
  8791. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8792. if ($done['ts'] <= 0) {
  8793. return false;
  8794. }
  8795. if ($hasSearch) {
  8796. return true;
  8797. }
  8798. return date('Y-m', $done['ts']) === $ym;
  8799. }));
  8800. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8801. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8802. $mainBySid = [];
  8803. foreach ($pool as $rw) {
  8804. if (!is_array($rw)) {
  8805. continue;
  8806. }
  8807. $rid = (int)($rw['ID'] ?? 0);
  8808. if ($rid > 0) {
  8809. $mainBySid[$rid] = $rw;
  8810. }
  8811. }
  8812. if ($mainBySid === []) {
  8813. $detailRows = [];
  8814. } else {
  8815. try {
  8816. $detailRows = Db::table('purchase_order_detail')
  8817. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8818. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8819. ->order('status', 'desc')
  8820. ->order('CCYDH', 'asc')
  8821. ->order('company_name', 'asc')
  8822. ->order('id', 'asc')
  8823. ->select();
  8824. } catch (\Throwable $e) {
  8825. try {
  8826. $detailRows = Db::table('purchase_order_detail')
  8827. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8828. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8829. ->order('status', 'desc')
  8830. ->order('CCYDH', 'asc')
  8831. ->order('company_name', 'asc')
  8832. ->order('ID', 'asc')
  8833. ->select();
  8834. } catch (\Throwable $e2) {
  8835. $detailRows = [];
  8836. }
  8837. }
  8838. }
  8839. if (!is_array($detailRows)) {
  8840. $detailRows = [];
  8841. }
  8842. $exportLines = [];
  8843. $detailSidSeen = [];
  8844. foreach ($detailRows as $dr) {
  8845. if (!is_array($dr)) {
  8846. continue;
  8847. }
  8848. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8849. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8850. continue;
  8851. }
  8852. if (isset($detailSidSeen[$sid])) {
  8853. continue;
  8854. }
  8855. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8856. continue;
  8857. }
  8858. $detailSidSeen[$sid] = true;
  8859. $m = $mainBySid[$sid];
  8860. $exportLines[] = [
  8861. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8862. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8863. 'company_name' => (string)($dr['company_name'] ?? ''),
  8864. 'CDF' => (string)($m['CDF'] ?? ''),
  8865. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8866. 'gx' => $this->procuremenExportGxText($m),
  8867. 'detail' => $dr,
  8868. ];
  8869. }
  8870. foreach ($detailRows as $dr) {
  8871. if (!is_array($dr)) {
  8872. continue;
  8873. }
  8874. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8875. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8876. continue;
  8877. }
  8878. $detailSidSeen[$sid] = true;
  8879. $m = $mainBySid[$sid];
  8880. $exportLines[] = [
  8881. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8882. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8883. 'company_name' => (string)($dr['company_name'] ?? ''),
  8884. 'CDF' => (string)($m['CDF'] ?? ''),
  8885. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8886. 'gx' => $this->procuremenExportGxText($m),
  8887. 'detail' => $dr,
  8888. ];
  8889. }
  8890. foreach ($mainBySid as $sid => $m) {
  8891. if (isset($detailSidSeen[$sid])) {
  8892. continue;
  8893. }
  8894. $company = trim((string)($m['pick_company_name'] ?? ''));
  8895. $exportLines[] = [
  8896. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8897. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8898. 'company_name' => $company,
  8899. 'CDF' => (string)($m['CDF'] ?? ''),
  8900. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8901. 'gx' => $this->procuremenExportGxText($m),
  8902. 'detail' => [],
  8903. ];
  8904. }
  8905. $groups = [];
  8906. foreach ($exportLines as $line) {
  8907. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8908. if (!isset($groups[$k])) {
  8909. $groups[$k] = [];
  8910. }
  8911. $groups[$k][] = $line;
  8912. }
  8913. ksort($groups, SORT_STRING);
  8914. return [
  8915. 'ym' => $ym,
  8916. 'mainBySid' => $mainBySid,
  8917. 'detailRows' => $detailRows,
  8918. 'exportLines' => $exportLines,
  8919. 'groups' => $groups,
  8920. ];
  8921. }
  8922. /**
  8923. * 导出用:工序列文案
  8924. */
  8925. protected function procuremenExportGxText(array $r)
  8926. {
  8927. $a = trim((string)($r['CDXMC'] ?? ''));
  8928. $b = trim((string)($r['CGYMC'] ?? ''));
  8929. if ($a !== '' && $b !== '') {
  8930. return $a . ':' . $b;
  8931. }
  8932. return $a !== '' ? $a : $b;
  8933. }
  8934. /**
  8935. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8936. */
  8937. protected function procuremenExportAmount(array $r)
  8938. {
  8939. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8940. if (!array_key_exists($k, $r)) {
  8941. continue;
  8942. }
  8943. $v = $r[$k];
  8944. if ($v === null || $v === '') {
  8945. continue;
  8946. }
  8947. if (is_numeric($v)) {
  8948. return (float)$v;
  8949. }
  8950. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8951. if ($v !== '' && is_numeric($v)) {
  8952. return (float)$v;
  8953. }
  8954. }
  8955. return 0.0;
  8956. }
  8957. /**
  8958. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8959. *
  8960. * @param array<int, array<string, mixed>> $detailRows
  8961. * @param array<int, array<string, mixed>> $mainBySid
  8962. * @return array<int, array<string, mixed>>
  8963. */
  8964. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8965. {
  8966. $lines = [];
  8967. foreach ($detailRows as $dr) {
  8968. if (!is_array($dr)) {
  8969. continue;
  8970. }
  8971. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8972. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8973. continue;
  8974. }
  8975. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8976. continue;
  8977. }
  8978. $cn = trim((string)($dr['company_name'] ?? ''));
  8979. if ($cn === '') {
  8980. continue;
  8981. }
  8982. $m = $mainBySid[$sid];
  8983. $am = trim((string)($dr['amount'] ?? ''));
  8984. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8985. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8986. $amountText = $amountFilled
  8987. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8988. : '未填写';
  8989. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8990. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8991. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8992. $deliveryShow = $deliveryRaw;
  8993. }
  8994. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8995. ? $deliveryShow
  8996. : '未填写';
  8997. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8998. $lines[] = [
  8999. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  9000. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  9001. 'gx' => $this->procuremenExportGxText($m),
  9002. 'company_name' => $cn,
  9003. 'amount_text' => $amountText,
  9004. 'amount_num' => $amountFilled ? $amountNum : null,
  9005. 'delivery_text' => $deliveryText,
  9006. 'picked_text' => $picked ? '中标' : '未中标',
  9007. 'picked' => $picked,
  9008. ];
  9009. }
  9010. $winnerSupplierByOrder = [];
  9011. foreach ($lines as $line) {
  9012. $dh = trim((string)($line['CCYDH'] ?? ''));
  9013. $cn = trim((string)($line['company_name'] ?? ''));
  9014. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  9015. $winnerSupplierByOrder[$dh][$cn] = true;
  9016. }
  9017. }
  9018. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  9019. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  9020. if ($c !== 0) {
  9021. return $c;
  9022. }
  9023. $dh = trim((string)($a['CCYDH'] ?? ''));
  9024. $aCn = trim((string)($a['company_name'] ?? ''));
  9025. $bCn = trim((string)($b['company_name'] ?? ''));
  9026. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  9027. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  9028. if ($aSupplierWin !== $bSupplierWin) {
  9029. return $aSupplierWin ? -1 : 1;
  9030. }
  9031. $c = strcmp($aCn, $bCn);
  9032. if ($c !== 0) {
  9033. return $c;
  9034. }
  9035. if (!empty($a['picked']) !== !empty($b['picked'])) {
  9036. return !empty($a['picked']) ? -1 : 1;
  9037. }
  9038. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  9039. if ($c !== 0) {
  9040. return $c;
  9041. }
  9042. return 0;
  9043. });
  9044. return $lines;
  9045. }
  9046. /**
  9047. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  9048. *
  9049. * @param array<int, array<string, mixed>> $quoteLines
  9050. */
  9051. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  9052. {
  9053. $mon = (int)substr($ym, 5, 2);
  9054. $titleRow = $startRow;
  9055. $headerRow = $startRow + 1;
  9056. $dataStartRow = $startRow + 2;
  9057. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  9058. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  9059. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  9060. $sheet->getStyle('A' . $titleRow)->getAlignment()
  9061. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9062. ->setVertical(Alignment::VERTICAL_CENTER);
  9063. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  9064. $col = 'A';
  9065. foreach ($headers as $h) {
  9066. $sheet->setCellValue($col . $headerRow, $h);
  9067. $col++;
  9068. }
  9069. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  9070. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  9071. $rowNum = $dataStartRow;
  9072. if ($quoteLines === []) {
  9073. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  9074. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  9075. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  9076. $rowNum = $dataStartRow + 1;
  9077. } else {
  9078. $i = 0;
  9079. foreach ($quoteLines as $line) {
  9080. $i++;
  9081. $sheet->setCellValue('A' . $rowNum, $i);
  9082. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  9083. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  9084. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  9085. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  9086. if ($line['amount_num'] !== null) {
  9087. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  9088. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  9089. } else {
  9090. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  9091. }
  9092. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  9093. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  9094. if (!empty($line['picked'])) {
  9095. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  9096. }
  9097. $rowNum++;
  9098. }
  9099. }
  9100. $lastRow = $rowNum - 1;
  9101. if ($lastRow >= $headerRow) {
  9102. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  9103. 'borders' => [
  9104. 'allBorders' => [
  9105. 'borderStyle' => Border::BORDER_THIN,
  9106. 'color' => ['rgb' => '000000'],
  9107. ],
  9108. ],
  9109. ]);
  9110. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  9111. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  9112. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  9113. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  9114. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  9115. if ($lastRow >= $dataStartRow) {
  9116. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  9117. }
  9118. }
  9119. return $lastRow;
  9120. }
  9121. /**
  9122. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  9123. */
  9124. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  9125. {
  9126. if ($lastRow < $dataStartRow || $headerRow < 1) {
  9127. return;
  9128. }
  9129. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  9130. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9131. ->setVertical(Alignment::VERTICAL_CENTER);
  9132. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  9133. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9134. ->setVertical(Alignment::VERTICAL_CENTER);
  9135. if ($lastCol > 'B') {
  9136. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  9137. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  9138. ->setVertical(Alignment::VERTICAL_CENTER);
  9139. }
  9140. }
  9141. /**
  9142. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  9143. */
  9144. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  9145. {
  9146. $s = trim($ccydh);
  9147. if ($s === '') {
  9148. return 'ORDER';
  9149. }
  9150. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  9151. $s = trim($s, '._-');
  9152. if ($s === '') {
  9153. return 'ORDER';
  9154. }
  9155. if (function_exists('mb_substr')) {
  9156. return mb_substr($s, 0, 80, 'UTF-8');
  9157. }
  9158. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  9159. }
  9160. /**
  9161. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  9162. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  9163. *
  9164. * @return array{objectKey: string, webPath: string}
  9165. */
  9166. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  9167. {
  9168. $sid = (int)$scydgyId;
  9169. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  9170. $y = date('Y');
  9171. $m = date('m');
  9172. $d = date('d');
  9173. $basename = $safeOrder . '_' . $sid . '.pdf';
  9174. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  9175. return [
  9176. 'objectKey' => $objectKey,
  9177. 'webPath' => '/' . $objectKey,
  9178. ];
  9179. }
  9180. /**
  9181. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  9182. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  9183. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  9184. *
  9185. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  9186. */
  9187. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  9188. {
  9189. if (!$this->isValidScydgyRowId($scydgyId)) {
  9190. return '';
  9191. }
  9192. $ids = trim((string)$scydgyId);
  9193. $prep = $this->prepareProcuremenDetailsView($ids);
  9194. if (!$prep['ok']) {
  9195. return '';
  9196. }
  9197. $ccydh = $prep['ccydh'];
  9198. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  9199. $objectKey = $paths['objectKey'];
  9200. $webPath = $paths['webPath'];
  9201. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  9202. $this->view->assign([
  9203. 'pdf_export' => 1,
  9204. 'pdfMetaLine' => $meta,
  9205. ]);
  9206. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  9207. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  9208. $this->view->engine->layout(false);
  9209. try {
  9210. $html = $this->view->fetch('procuremen/details_pdf_shell');
  9211. } catch (\Throwable $e) {
  9212. if ($restoreLayout) {
  9213. $this->view->engine->layout($restoreLayout);
  9214. }
  9215. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  9216. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  9217. return '';
  9218. }
  9219. if ($restoreLayout) {
  9220. $this->view->engine->layout($restoreLayout);
  9221. }
  9222. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  9223. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  9224. if (!is_dir($tempDir)) {
  9225. @mkdir($tempDir, 0755, true);
  9226. }
  9227. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  9228. try {
  9229. $mpdf = new \Mpdf\Mpdf([
  9230. 'mode' => 'utf-8',
  9231. 'format' => 'A4',
  9232. 'margin_left' => 12,
  9233. 'margin_right' => 12,
  9234. 'margin_top' => 14,
  9235. 'margin_bottom' => 14,
  9236. 'tempDir' => $tempDir,
  9237. 'autoScriptToLang' => true,
  9238. 'autoLangToFont' => true,
  9239. ]);
  9240. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  9241. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  9242. $mpdf->SetBasePath('http://127.0.0.1/');
  9243. $mpdf->WriteHTML($html);
  9244. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  9245. } catch (\Throwable $e) {
  9246. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  9247. if (is_file($tempPdf)) {
  9248. @unlink($tempPdf);
  9249. }
  9250. return '';
  9251. }
  9252. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  9253. if ($ossUrl !== '') {
  9254. @unlink($tempPdf);
  9255. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  9256. return $ossUrl;
  9257. }
  9258. $pi = pathinfo($objectKey);
  9259. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  9260. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  9261. if ($baseFile === '') {
  9262. @unlink($tempPdf);
  9263. return '';
  9264. }
  9265. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  9266. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  9267. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  9268. @unlink($tempPdf);
  9269. return '';
  9270. }
  9271. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  9272. if (!@copy($tempPdf, $fullPath)) {
  9273. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  9274. @unlink($tempPdf);
  9275. return '';
  9276. }
  9277. @unlink($tempPdf);
  9278. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  9279. return $webPath;
  9280. }
  9281. /**
  9282. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  9283. */
  9284. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  9285. {
  9286. if ($scydgyId <= 0 || $webPath === '') {
  9287. return;
  9288. }
  9289. try {
  9290. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  9291. } catch (\Throwable $e) {
  9292. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  9293. }
  9294. }
  9295. /**
  9296. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  9297. *
  9298. * @param array<string, string> $vars
  9299. * @return array<string, string>
  9300. */
  9301. protected function normalizeSmsTemplateVars(array $vars): array
  9302. {
  9303. $out = [];
  9304. foreach ($vars as $k => $v) {
  9305. $out[(string)$k] = trim((string)$v);
  9306. }
  9307. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  9308. $out['contact_name'] = $out['company_name'];
  9309. }
  9310. return $out;
  9311. }
  9312. /**
  9313. * 按手机号或公司名称查 customer 表联系人姓名
  9314. */
  9315. protected function resolveCustomerContactName(string $phone, string $companyName): string
  9316. {
  9317. $phone = trim($phone);
  9318. $companyName = trim($companyName);
  9319. try {
  9320. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  9321. $row = Db::table('customer')
  9322. ->where(function ($q) use ($phone) {
  9323. $q->where('phone', $phone)->whereOr('account', $phone);
  9324. })
  9325. ->order('id', 'asc')
  9326. ->find();
  9327. if (is_array($row)) {
  9328. $nm = trim((string)($row['username'] ?? ''));
  9329. if ($nm !== '') {
  9330. return $nm;
  9331. }
  9332. }
  9333. }
  9334. if ($companyName !== '') {
  9335. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  9336. if (is_array($row)) {
  9337. return trim((string)($row['username'] ?? ''));
  9338. }
  9339. }
  9340. } catch (\Throwable $e) {
  9341. }
  9342. return '';
  9343. }
  9344. /**
  9345. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  9346. */
  9347. protected function plainTextToHtmlEmailBody(string $text): string
  9348. {
  9349. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  9350. $parts = explode("\n", $text);
  9351. $out = [];
  9352. foreach ($parts as $line) {
  9353. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  9354. $out[] = $line;
  9355. } else {
  9356. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  9357. }
  9358. }
  9359. return implode("<br>\n", $out);
  9360. }
  9361. /**
  9362. * 短信场景:去掉链接类变量,避免误填 URL
  9363. *
  9364. * @param array<string, string> $vars
  9365. * @return array<string, string>
  9366. */
  9367. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  9368. {
  9369. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  9370. return $vars;
  9371. }
  9372. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  9373. $vars[$k] = '';
  9374. }
  9375. return $vars;
  9376. }
  9377. /**
  9378. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  9379. *
  9380. * @param array<string, string> $vars
  9381. */
  9382. protected function renderNotifyTemplate(string $scene, array $vars): string
  9383. {
  9384. $vars = $this->normalizeSmsTemplateVars($vars);
  9385. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  9386. $row = $this->loadNotifyTemplateRow($scene);
  9387. if ($row === null) {
  9388. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9389. }
  9390. $tpl = trim((string)($row['content'] ?? ''));
  9391. if ($tpl === '') {
  9392. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9393. }
  9394. foreach ($vars as $k => $v) {
  9395. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  9396. }
  9397. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  9398. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  9399. return $tpl;
  9400. }
  9401. protected function resolveProcuremenEmailSubject(string $scene): string
  9402. {
  9403. $map = [
  9404. 'review_email' => '您有新的协助加工订单',
  9405. ];
  9406. $subject = trim((string)($map[$scene] ?? ''));
  9407. if ($subject === '') {
  9408. $this->error('未配置邮件主题:' . $scene);
  9409. }
  9410. return $subject;
  9411. }
  9412. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  9413. {
  9414. $map = [
  9415. 'review_email' => '协助下发-邮箱',
  9416. 'review_sms' => '协助下发-短信',
  9417. 'confirm_ok' => '采购确认-通过',
  9418. 'confirm_fail' => '采购确认-未通过',
  9419. 'bid_open' => '开标双重验证',
  9420. ];
  9421. $label = $map[$scene] ?? $scene;
  9422. if ($titleRequired) {
  9423. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  9424. }
  9425. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  9426. }
  9427. /**
  9428. * 是否开启协助通知演练(不发真实短信/邮件)
  9429. */
  9430. protected function isProcuremenNotifyDryRun(): bool
  9431. {
  9432. return (bool)Config::get('procuremen_notify_dry_run');
  9433. }
  9434. /**
  9435. * @param array<string, mixed> $payload
  9436. */
  9437. protected function recordNotifyDryRunPreview(array $payload): void
  9438. {
  9439. $this->notifyDryRunPreview[] = $payload;
  9440. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9441. }
  9442. /**
  9443. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  9444. * @throws \Exception
  9445. */
  9446. protected function smsbao($phone, $content)
  9447. {
  9448. if ($this->isProcuremenNotifyDryRun()) {
  9449. $this->recordNotifyDryRunPreview([
  9450. 'scene' => 'sms_only',
  9451. 'phone' => $phone,
  9452. 'sms_content' => $content,
  9453. ]);
  9454. return;
  9455. }
  9456. $statusStr = [
  9457. '0' => '短信发送成功',
  9458. '-1' => '参数不全',
  9459. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  9460. '30' => '密码错误',
  9461. '40' => '账号不存在',
  9462. '41' => '余额不足',
  9463. '42' => '帐户已过期',
  9464. '43' => 'IP地址限制',
  9465. '50' => '内容含有敏感词',
  9466. ];
  9467. $smsapi = 'http://api.smsbao.com/';
  9468. $user = 'zhuwei123';
  9469. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  9470. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  9471. $result = @file_get_contents($sendurl);
  9472. if ($result === false) {
  9473. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9474. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9475. }
  9476. $result = trim((string)$result);
  9477. if ($result !== '0') {
  9478. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9479. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9480. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9481. }
  9482. }
  9483. }