Procuremen.php 362 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669
  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\ProcuremenTime;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use think\Config;
  11. use think\Cache;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Style\Border;
  15. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  17. use think\Db;
  18. use think\Log;
  19. class Procuremen extends Backend
  20. {
  21. /**
  22. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  23. */
  24. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  25. /**
  26. * Procuremen模型对象
  27. * @var \app\admin\model\Procuremen
  28. */
  29. protected $model = null;
  30. /**
  31. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  32. */
  33. protected $notifyDryRunPreview = [];
  34. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  35. protected $procuremenRedisCache = null;
  36. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  37. protected $pickHiddenScydgySetCache = null;
  38. /** 邮件发送日志表结构已就绪缓存键 */
  39. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  40. /**
  41. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  42. * @var array
  43. */
  44. protected $noNeedRight = [
  45. 'pickreview', 'review', 'reviewcompanies',
  46. ];
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \app\admin\model\Procuremen;
  51. $this->maybeMigrateLegacyWflowStatusText();
  52. $this->assignProcuremenAuthConfig();
  53. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  54. $this->ensurePurchaseEmailSendLogTableOnce();
  55. }
  56. }
  57. /**
  58. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  59. */
  60. protected function maybeMigrateLegacyWflowStatusText(): void
  61. {
  62. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  63. if (is_file($flagFile)) {
  64. return;
  65. }
  66. $map = [
  67. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  68. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  69. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  70. '3' => ProcuremenStatus::WFLOW_APPROVED,
  71. ];
  72. try {
  73. foreach ($map as $num => $text) {
  74. Db::table('purchase_order')
  75. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  76. ->update(['wflow_status' => $text]);
  77. }
  78. @file_put_contents($flagFile, date('c'));
  79. } catch (\Throwable $e) {
  80. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  81. }
  82. }
  83. /**
  84. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  85. *
  86. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  87. */
  88. protected function hasProcuremenPerm(array $actions): bool
  89. {
  90. foreach ($actions as $action) {
  91. $action = strtolower(trim((string)$action));
  92. if ($action === '') {
  93. continue;
  94. }
  95. if (strpos($action, 'procuremen/') !== 0) {
  96. $action = 'procuremen/' . $action;
  97. }
  98. if ($this->auth->check($action)) {
  99. return true;
  100. }
  101. }
  102. $suffixes = [];
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. $action = preg_replace('#^procuremen/#', '', $action);
  106. if ($action !== '') {
  107. $suffixes[$action] = true;
  108. }
  109. }
  110. if ($suffixes === []) {
  111. return false;
  112. }
  113. try {
  114. foreach ($this->auth->getRuleList() as $rule) {
  115. $rule = strtolower((string)$rule);
  116. if (strpos($rule, 'procuremen/') !== 0) {
  117. continue;
  118. }
  119. foreach (array_keys($suffixes) as $suffix) {
  120. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  121. return true;
  122. }
  123. }
  124. }
  125. } catch (\Throwable $e) {
  126. }
  127. return false;
  128. }
  129. /**
  130. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  131. *
  132. * @param string[] $actions
  133. */
  134. protected function hasProcuremenPermStrict(array $actions): bool
  135. {
  136. foreach ($actions as $action) {
  137. $action = strtolower(trim((string)$action));
  138. if ($action === '') {
  139. continue;
  140. }
  141. if (strpos($action, 'procuremen/') !== 0) {
  142. $action = 'procuremen/' . $action;
  143. }
  144. if ($this->auth->check($action)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. /**
  151. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  152. *
  153. * @param string[] $titles
  154. */
  155. protected function authHasAssignedRuleTitle(array $titles): bool
  156. {
  157. $titles = array_values(array_filter(array_map('trim', $titles)));
  158. if ($titles === []) {
  159. return false;
  160. }
  161. try {
  162. $ids = $this->auth->getRuleIds();
  163. if (in_array('*', $ids, true)) {
  164. return true;
  165. }
  166. if ($ids === []) {
  167. return false;
  168. }
  169. $rows = Db::name('auth_rule')
  170. ->where('status', 'normal')
  171. ->whereIn('id', $ids)
  172. ->column('title');
  173. foreach ($rows as $title) {
  174. $t = trim((string)$title);
  175. if ($t !== '' && in_array($t, $titles, true)) {
  176. return true;
  177. }
  178. }
  179. } catch (\Throwable $e) {
  180. }
  181. return false;
  182. }
  183. protected function procuremenCanPickDelete(): bool
  184. {
  185. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  186. return true;
  187. }
  188. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  189. }
  190. protected function procuremenCanComplete(): bool
  191. {
  192. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  193. return true;
  194. }
  195. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  196. }
  197. protected function procuremenCanDispatch(): bool
  198. {
  199. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  200. }
  201. /**
  202. * 前端按钮显隐(Config.procuremenAuth)
  203. */
  204. protected function assignProcuremenAuthConfig(): void
  205. {
  206. $authMap = [
  207. 'pickreview' => $this->procuremenCanDispatch(),
  208. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  209. 'pickdelete' => $this->procuremenCanPickDelete(),
  210. 'completedirectly' => $this->procuremenCanComplete(),
  211. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  212. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  213. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  214. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  215. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  216. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  217. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  218. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  219. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  220. 'details' => $this->hasProcuremenPerm(['details']),
  221. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  222. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  223. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  224. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  225. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  228. 'add' => $this->hasProcuremenPerm(['add']),
  229. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  230. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  231. ];
  232. $this->assignconfig('procuremenAuth', $authMap);
  233. }
  234. /**
  235. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  236. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  237. *
  238. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  239. */
  240. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  241. {
  242. static $mprocCfgLoaded = false;
  243. if (!$mprocCfgLoaded) {
  244. $mprocCfgLoaded = true;
  245. if (is_file(APP_PATH . 'extra/mproc.php')) {
  246. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  247. }
  248. }
  249. $eid = (int)$purchaseOrderDetailId;
  250. $base = $this->resolveMprocMobilePublicBaseUrl();
  251. if ($base === '') {
  252. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  253. }
  254. $path = trim((string)Config::get('mproc.mobile_index_path'));
  255. if ($path === '') {
  256. $path = '/index.php/index/index/index';
  257. } else {
  258. $path = '/' . ltrim($path, '/');
  259. }
  260. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  261. if ($eid > 0) {
  262. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  263. }
  264. return $base . $path . '?main_tab=orders';
  265. }
  266. /**
  267. * 邮件/短信外链:须为带点的公网域名
  268. */
  269. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  270. {
  271. $u = trim((string)$baseUrl);
  272. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  273. return false;
  274. }
  275. $host = parse_url($u, PHP_URL_HOST);
  276. if (!is_string($host) || $host === '') {
  277. return false;
  278. }
  279. if (strcasecmp($host, 'localhost') === 0) {
  280. return false;
  281. }
  282. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  283. return false;
  284. }
  285. if (strpos($host, '.') === false) {
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * 解析用于协助邮件/短信的手机端站点根
  292. */
  293. protected function resolveMprocMobilePublicBaseUrl()
  294. {
  295. $candidates = [];
  296. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  297. $candidates[] = trim((string)Config::get('site.indexurl'));
  298. $cdn = trim((string)Config::get('site.cdnurl'));
  299. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  300. $candidates[] = rtrim($cdn, '/');
  301. }
  302. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  303. $candidates[] = $reqBase;
  304. foreach ($candidates as $c) {
  305. if ($c === '') {
  306. continue;
  307. }
  308. $c = rtrim($c, '/');
  309. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  310. return $c;
  311. }
  312. }
  313. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  314. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  315. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  316. return $reqBase;
  317. }
  318. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  319. return '';
  320. }
  321. /**
  322. * 获取 Redis 中 procuremen_redis
  323. */
  324. protected function ProcuremenRedis(): array
  325. {
  326. if ($this->procuremenRedisCache !== null) {
  327. return $this->procuremenRedisCache;
  328. }
  329. try {
  330. $redis = redis();
  331. $raw = $redis->get('procuremen_redis');
  332. if ($raw === false || $raw === '') {
  333. $this->procuremenRedisCache = [];
  334. return $this->procuremenRedisCache;
  335. }
  336. $decoded = json_decode($raw, true);
  337. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  338. $this->procuremenRedisCache = [];
  339. return $this->procuremenRedisCache;
  340. }
  341. $this->procuremenRedisCache = $decoded['data'];
  342. return $this->procuremenRedisCache;
  343. } catch (\Throwable $e) {
  344. $this->procuremenRedisCache = [];
  345. return $this->procuremenRedisCache;
  346. }
  347. }
  348. /**
  349. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  350. *
  351. * @return array<int, array<string, mixed>>
  352. */
  353. protected function procuremenFetchErpPoolFromDb(): array
  354. {
  355. try {
  356. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  357. $endTime = date('Y-m-d 23:59:59');
  358. $list = Db::table('scydgy')
  359. ->alias('a')
  360. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  361. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  362. ->where([
  363. 'a.bwjg' => 1,
  364. 'a.iEndBz' => 0,
  365. 'a.iType' => 0,
  366. 'a.iStatus' => 10,
  367. ])
  368. ->where('a.dStamp', '>=', $startTime)
  369. ->where('a.dStamp', '<=', $endTime)
  370. ->order('a.dStamp', 'desc')
  371. ->select();
  372. if (!is_array($list)) {
  373. return [];
  374. }
  375. try {
  376. $redis = redis();
  377. $payload = [
  378. 'code' => 200,
  379. 'msg' => 'success',
  380. 'data' => $list,
  381. ];
  382. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  383. $this->procuremenRedisCache = $list;
  384. } catch (\Throwable $e) {
  385. }
  386. return $list;
  387. } catch (\Throwable $e) {
  388. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  389. return [];
  390. }
  391. }
  392. /**
  393. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  394. *
  395. * @return array<int, array<string, mixed>>
  396. */
  397. protected function procuremenEnsureRedisPool(): array
  398. {
  399. $pool = $this->ProcuremenRedis();
  400. if (is_array($pool) && $pool !== []) {
  401. return $pool;
  402. }
  403. static $warmed = false;
  404. if ($warmed) {
  405. return is_array($pool) ? $pool : [];
  406. }
  407. $warmed = true;
  408. return $this->procuremenFetchErpPoolFromDb();
  409. }
  410. /**
  411. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  412. *
  413. * @param array<string, mixed> $row
  414. */
  415. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  416. {
  417. $t = $this->procuremenRowListSortTime($row, $primary);
  418. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  419. return null;
  420. }
  421. $mo = (int)$m[2];
  422. if ($mo < 1 || $mo > 12) {
  423. return null;
  424. }
  425. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  426. }
  427. /**
  428. * @param array<int, array{year:string, months:array}> $sidebar
  429. * @return array<int, array{year:string, months:array}>
  430. */
  431. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return $sidebar;
  436. }
  437. foreach ($sidebar as $block) {
  438. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  439. continue;
  440. }
  441. foreach ($block['months'] as $item) {
  442. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  443. return $sidebar;
  444. }
  445. }
  446. }
  447. $y = substr($ym, 0, 4);
  448. $mo = (int)substr($ym, 5, 2);
  449. $sidebar[] = [
  450. 'year' => $y,
  451. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  452. ];
  453. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  454. }
  455. /**
  456. * @param array<int, array{year:string, months:array}> $sidebar
  457. * @return string[]
  458. */
  459. protected function flattenProcuremenSidebarYms(array $sidebar): array
  460. {
  461. $yms = [];
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (!is_array($item)) {
  468. continue;
  469. }
  470. $ym = trim((string)($item['ym'] ?? ''));
  471. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  472. $yms[$ym] = true;
  473. }
  474. }
  475. }
  476. return array_keys($yms);
  477. }
  478. /**
  479. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  480. */
  481. protected function GetIndexYearMonths()
  482. {
  483. $ymSet = [];
  484. $pool = $this->procuremenEnsureRedisPool();
  485. foreach ($pool as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. foreach ($this->loadPickManualOrderRows() as $r) {
  495. if (!is_array($r)) {
  496. continue;
  497. }
  498. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  499. if ($ym !== null) {
  500. $ymSet[$ym] = true;
  501. }
  502. }
  503. $ymList = array_keys($ymSet);
  504. if ($ymList === []) {
  505. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  506. }
  507. return $this->buildYearMonthSidebar($ymList);
  508. }
  509. /**
  510. * @param string[] $ymList 形如 2026-06
  511. * @return array<int, array{year:string, months:array}>
  512. */
  513. protected function buildYearMonthSidebar(array $ymList): array
  514. {
  515. rsort($ymList, SORT_STRING);
  516. $byYear = [];
  517. foreach ($ymList as $ym) {
  518. $y = substr($ym, 0, 4);
  519. $mo = (int)substr($ym, 5, 2);
  520. if (!isset($byYear[$y])) {
  521. $byYear[$y] = [];
  522. }
  523. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  524. }
  525. krsort($byYear, SORT_NUMERIC);
  526. foreach ($byYear as $y => $items) {
  527. usort($byYear[$y], function ($a, $b) {
  528. return strcmp($b['ym'], $a['ym']);
  529. });
  530. }
  531. $sidebar = [];
  532. foreach ($byYear as $y => $months) {
  533. $sidebar[] = ['year' => $y, 'months' => $months];
  534. }
  535. return $sidebar;
  536. }
  537. /**
  538. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  539. */
  540. protected function GetIssuedOrderYearMonths(string $stage): array
  541. {
  542. $ymSet = [];
  543. try {
  544. $query = Db::table('purchase_order');
  545. $this->applyPurchaseOrderNotDeletedWhere($query);
  546. if ($stage === 'audit') {
  547. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  548. } elseif ($stage === 'confirm') {
  549. $this->applyPurchaseOrderConfirmStageWhere($query);
  550. } else {
  551. return $this->GetIndexYearMonths();
  552. }
  553. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  554. if (is_array($rows)) {
  555. foreach ($rows as $r) {
  556. if (!is_array($r)) {
  557. continue;
  558. }
  559. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  560. if ($ym !== null) {
  561. $ymSet[$ym] = true;
  562. }
  563. }
  564. }
  565. } catch (\Throwable $e) {
  566. $ymSet = [];
  567. }
  568. $ymList = array_keys($ymSet);
  569. if ($ymList === []) {
  570. $def = $this->resolveProcuremenDefaultYm($stage);
  571. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  577. */
  578. protected function resolveProcuremenDefaultYm(string $stage): string
  579. {
  580. if ($stage === 'pick') {
  581. return date('Y-m');
  582. }
  583. try {
  584. $query = Db::table('purchase_order');
  585. $this->applyPurchaseOrderNotDeletedWhere($query);
  586. if ($stage === 'audit') {
  587. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  588. } elseif ($stage === 'confirm') {
  589. $this->applyPurchaseOrderConfirmStageWhere($query);
  590. } else {
  591. return date('Y-m');
  592. }
  593. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  594. if ($latest === null || $latest === '') {
  595. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  596. }
  597. $t = $this->formatProcuremenDetailTime($latest);
  598. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  599. return $m[1] . '-' . $m[2];
  600. }
  601. } catch (\Throwable $e) {
  602. }
  603. return date('Y-m');
  604. }
  605. protected function applyPurchaseOrderNotDeletedWhere($query): void
  606. {
  607. $query->whereRaw(
  608. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  609. );
  610. }
  611. /**
  612. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  613. */
  614. protected function applyPurchaseOrderConfirmStageWhere($query): void
  615. {
  616. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  617. $quoted = [];
  618. foreach ($vals as $v) {
  619. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  620. }
  621. if ($quoted === []) {
  622. $query->whereRaw('1 = 0');
  623. return;
  624. }
  625. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  626. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  627. }
  628. /**
  629. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  630. *
  631. * @param array<string, mixed> $row
  632. * @return array<string, mixed>
  633. */
  634. protected function normalizePurchaseOrderListTimeRow(array $row): array
  635. {
  636. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  637. $pick = trim((string)($row['pick_time'] ?? ''));
  638. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  639. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  640. $t = trim((string)($row[$key] ?? ''));
  641. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  642. $row['pick_time'] = $t;
  643. break;
  644. }
  645. }
  646. }
  647. return $row;
  648. }
  649. /**
  650. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  651. */
  652. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  653. {
  654. if (!in_array($stage, ['audit', 'confirm'], true)) {
  655. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  656. }
  657. if ($pool === []) {
  658. $def = $this->resolveProcuremenDefaultYm($stage);
  659. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  660. }
  661. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  662. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  663. return false;
  664. }
  665. $monthStart = $ym . '-01 00:00:00';
  666. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  667. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  668. return $probe !== [];
  669. };
  670. if ($tryYm($requestedYm)) {
  671. return $requestedYm;
  672. }
  673. $fallback = $this->resolveProcuremenDefaultYm($stage);
  674. if ($tryYm($fallback)) {
  675. return $fallback;
  676. }
  677. $bestYm = '';
  678. $bestTime = '';
  679. foreach ($pool as $row) {
  680. if (!is_array($row)) {
  681. continue;
  682. }
  683. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  684. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  685. continue;
  686. }
  687. $ymRow = $m[1];
  688. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  689. $bestTime = $t;
  690. $bestYm = $ymRow;
  691. }
  692. }
  693. if ($bestYm !== '') {
  694. return $bestYm;
  695. }
  696. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  697. }
  698. protected function isPurchaseOrderDetailVoid(array $row): bool
  699. {
  700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  701. return true;
  702. }
  703. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  704. }
  705. /**
  706. * 仅当前有效下发明细(排除废弃归档)
  707. */
  708. protected function applyActivePurchaseOrderDetailWhere($query): void
  709. {
  710. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  711. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  712. }
  713. /**
  714. * @param array<string, mixed> $detailRow
  715. */
  716. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  717. {
  718. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  719. return false;
  720. }
  721. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  722. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  723. }
  724. /**
  725. * 废弃退回初选:下发明细标记归档,不物理删除
  726. *
  727. * @param array<int, int|string> $scydgyIds
  728. */
  729. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  730. {
  731. $ids = [];
  732. foreach ($scydgyIds as $sid) {
  733. $n = (int)$sid;
  734. if ($this->isValidScydgyRowId($n) || $n < 0) {
  735. $ids[$n] = true;
  736. }
  737. }
  738. if ($ids === []) {
  739. return;
  740. }
  741. $void = ProcuremenStatus::POD_VOID;
  742. Db::table('purchase_order_detail')
  743. ->where('scydgy_id', 'in', array_keys($ids))
  744. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  745. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  746. ->update([
  747. 'status' => $void,
  748. 'status_name' => $void,
  749. ]);
  750. }
  751. /**
  752. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  753. */
  754. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  755. {
  756. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  757. $norm = function (string $col) use ($p): string {
  758. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  759. };
  760. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  761. $parts = [];
  762. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  763. if ($key === 'createtime') {
  764. $parts[] = $createtime;
  765. } else {
  766. $parts[] = $norm($key);
  767. }
  768. }
  769. return 'COALESCE(' . implode(', ', $parts) . ')';
  770. }
  771. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  772. {
  773. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  774. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  775. }
  776. /**
  777. * @return array<int, array<string, mixed>>
  778. */
  779. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  780. {
  781. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  782. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  783. try {
  784. $query = Db::table('purchase_order')->field($fields);
  785. $this->applyPurchaseOrderNotDeletedWhere($query);
  786. if ($stage === 'audit') {
  787. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  788. } elseif ($stage === 'confirm') {
  789. $this->applyPurchaseOrderConfirmStageWhere($query);
  790. } else {
  791. return [];
  792. }
  793. $query->order('pick_time', 'desc')->order('id', 'desc');
  794. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  795. $monthStart = $ym . '-01 00:00:00';
  796. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  797. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  798. }
  799. $rows = $query->select();
  800. } catch (\Throwable $e) {
  801. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  802. $rows = [];
  803. }
  804. return is_array($rows) ? $rows : [];
  805. }
  806. /**
  807. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  808. */
  809. protected function resolveProcuremenListStage(): string
  810. {
  811. $tab = trim((string)$this->request->request('wff_tab', ''));
  812. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  813. return $tab;
  814. }
  815. $action = strtolower((string)$this->request->action());
  816. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  817. return $action;
  818. }
  819. return 'pick';
  820. }
  821. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  822. {
  823. $rootTrue = rtrim((string)$this->request->root(true), '/');
  824. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  825. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  826. $indexPhpRoot = $rootTrue . '/index.php';
  827. }
  828. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  829. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  830. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  831. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  832. $this->view->assign('defaultYm', $defaultYm);
  833. $this->view->assign('sidebarYearMonths', $sidebar);
  834. $this->view->assign('procuremenStage', $stage);
  835. $this->view->assign('procuremenPageTitle', $pageTitle);
  836. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  837. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  838. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  839. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  840. }
  841. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  842. public function pick()
  843. {
  844. $this->request->filter(['strip_tags', 'trim']);
  845. if (!$this->request->isAjax()) {
  846. $this->assignProcuremenListPage('pick', '协助下发');
  847. return $this->view->fetch('procuremen/index');
  848. }
  849. return $this->index();
  850. }
  851. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  852. public function audit()
  853. {
  854. $this->request->filter(['strip_tags', 'trim']);
  855. if (!$this->request->isAjax()) {
  856. $this->assignProcuremenListPage('audit', '确认供应商');
  857. return $this->view->fetch('procuremen/index');
  858. }
  859. return $this->index();
  860. }
  861. /** 采购确认(定标) */
  862. public function confirm()
  863. {
  864. $this->request->filter(['strip_tags', 'trim']);
  865. if (!$this->request->isAjax()) {
  866. $this->assignProcuremenListPage('confirm', '采购确认');
  867. return $this->view->fetch('procuremen/index');
  868. }
  869. return $this->index();
  870. }
  871. /**
  872. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  873. */
  874. public function index()
  875. {
  876. $this->request->filter(['strip_tags', 'trim']);
  877. if (!$this->request->isAjax()) {
  878. $this->assignProcuremenListPage('pick', '协助下发');
  879. return $this->view->fetch('procuremen/index');
  880. }
  881. if ($this->request->request('keyField')) {
  882. return $this->selectpage();
  883. }
  884. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  885. $limit = max(10, min(500, (int)$limit));
  886. $ym = $this->request->request('ym', '');
  887. $ym = is_string($ym) ? trim($ym) : '';
  888. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  889. $wffTab = $this->resolveProcuremenListStage();
  890. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  891. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  892. ? $this->resolveProcuremenDefaultYm($wffTab)
  893. : date('Y-m');
  894. }
  895. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  896. $ym = date('Y-m');
  897. }
  898. $monthStart = $ym . '-01 00:00:00';
  899. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  900. $search = trim((string)$this->request->get('search', ''));
  901. $hasActiveSearch = ($search !== '');
  902. if (!$hasActiveSearch) {
  903. $filterStr = $this->request->get('filter', '');
  904. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  905. $arr = json_decode($filterStr, true);
  906. if (is_array($arr) && count($arr) > 0) {
  907. foreach ($arr as $v) {
  908. if (is_array($v)) {
  909. if (array_filter($v, function ($x) {
  910. return $x !== '' && $x !== null;
  911. })) {
  912. $hasActiveSearch = true;
  913. break;
  914. }
  915. } elseif ($v !== '' && $v !== null) {
  916. $hasActiveSearch = true;
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. }
  923. $applyMonthRange = !$hasActiveSearch;
  924. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  925. $opArr = (array)json_decode($this->request->get('op', ''), true);
  926. try {
  927. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  928. if ($wffTab === 'audit') {
  929. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  930. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  931. );
  932. } elseif ($wffTab === 'confirm') {
  933. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  934. if ($dbRows === []) {
  935. try {
  936. $dbRows = Db::table('purchase_order')
  937. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  938. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  939. ->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%\')')
  940. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  941. ->order('pick_time', 'desc')->order('id', 'desc')
  942. ->select();
  943. } catch (\Throwable $e) {
  944. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  945. $dbRows = [];
  946. }
  947. }
  948. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  949. if ($pool === []) {
  950. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  951. }
  952. } else {
  953. $pool = $this->procuremenEnsureRedisPool();
  954. if (!is_array($pool)) {
  955. $pool = [];
  956. }
  957. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  958. $hideSet = $this->loadPickHiddenScydgySet();
  959. if ($pool !== [] && $hideSet !== []) {
  960. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  961. if (!is_array($r)) {
  962. return false;
  963. }
  964. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  965. return $id <= 0 || !isset($hideSet[$id]);
  966. }));
  967. }
  968. $manualPool = $this->loadPickManualOrderRows();
  969. if ($manualPool !== []) {
  970. $pool = array_merge($pool, $manualPool);
  971. }
  972. if ($pool === []) {
  973. return json([
  974. 'total' => 0,
  975. 'rows' => [],
  976. ]);
  977. }
  978. }
  979. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  980. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  981. $monthStart = $ym . '-01 00:00:00';
  982. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  983. }
  984. $filtered = $this->filterProcuremenIndexPool(
  985. $pool,
  986. $monthStart,
  987. $monthEnd,
  988. $applyMonthRange,
  989. $search,
  990. $filterArr,
  991. $opArr,
  992. $listTimePrimary
  993. );
  994. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  995. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  996. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  997. }
  998. $sortField = 'ID';
  999. if (is_string($sort) && $sort !== '') {
  1000. $parts = explode(',', $sort);
  1001. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1002. if ($sortField === '') {
  1003. $sortField = 'ID';
  1004. }
  1005. }
  1006. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1007. $nFiltered = count($filtered);
  1008. if ($nFiltered > 1) {
  1009. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1010. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1011. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1012. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1013. if ($ta === $tb) {
  1014. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1015. }
  1016. if ($ta === '') {
  1017. return 1;
  1018. }
  1019. if ($tb === '') {
  1020. return -1;
  1021. }
  1022. return strcmp($ta, $tb) * $ord;
  1023. });
  1024. } elseif ($sortField === 'ID') {
  1025. $sortKeys = [];
  1026. foreach ($filtered as $i => $row) {
  1027. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1028. }
  1029. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1030. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1031. } elseif ($sortField === 'CCYDH') {
  1032. usort($filtered, function ($a, $b) use ($ord) {
  1033. $sa = trim((string)($a['CCYDH'] ?? ''));
  1034. $sb = trim((string)($b['CCYDH'] ?? ''));
  1035. if ($sa === $sb) {
  1036. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1037. }
  1038. if ($sa === '') {
  1039. return 1;
  1040. }
  1041. if ($sb === '') {
  1042. return -1;
  1043. }
  1044. return strcmp($sa, $sb) * $ord;
  1045. });
  1046. } else {
  1047. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1048. $va = $a[$sortField] ?? null;
  1049. $vb = $b[$sortField] ?? null;
  1050. $sa = (string)$va;
  1051. $sb = (string)$vb;
  1052. if ($sa === $sb) {
  1053. return 0;
  1054. }
  1055. return strcmp($sa, $sb) * $ord;
  1056. });
  1057. }
  1058. }
  1059. $offset = max(0, (int)$offset);
  1060. $limit = max(1, (int)$limit);
  1061. $rows = array_slice($filtered, $offset, $limit);
  1062. foreach ($rows as &$rw) {
  1063. if (!is_array($rw)) {
  1064. continue;
  1065. }
  1066. $rid = (int)($rw['ID'] ?? 0);
  1067. $rw['_iss_out'] = ($wffTab !== 'pick');
  1068. }
  1069. unset($rw);
  1070. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1071. $idList = [];
  1072. foreach ($rows as $rw) {
  1073. if (!is_array($rw)) {
  1074. continue;
  1075. }
  1076. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1077. foreach ($rw['_order_merge_rows'] as $mr) {
  1078. $mid = (int)($mr['ID'] ?? 0);
  1079. if ($this->isValidScydgyRowId($mid)) {
  1080. $idList[$mid] = true;
  1081. }
  1082. }
  1083. }
  1084. $id = (int)($rw['ID'] ?? 0);
  1085. if ($this->isValidScydgyRowId($id)) {
  1086. $idList[$id] = true;
  1087. }
  1088. }
  1089. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1090. foreach ($rows as &$rw) {
  1091. if (!is_array($rw)) {
  1092. continue;
  1093. }
  1094. $mergeIds = [];
  1095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1096. foreach ($rw['_order_merge_rows'] as $mr) {
  1097. $mid = (int)($mr['ID'] ?? 0);
  1098. if ($this->isValidScydgyRowId($mid)) {
  1099. $mergeIds[$mid] = true;
  1100. }
  1101. }
  1102. }
  1103. $rid = (int)($rw['ID'] ?? 0);
  1104. if ($this->isValidScydgyRowId($rid)) {
  1105. $mergeIds[$rid] = true;
  1106. }
  1107. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1108. $rw['po_detail_count'] = $s['cnt'];
  1109. $rw['po_amount_fill_cnt'] = $s['amt'];
  1110. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1111. }
  1112. unset($rw);
  1113. }
  1114. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1115. $idList = [];
  1116. foreach ($rows as $rw) {
  1117. if (!is_array($rw)) {
  1118. continue;
  1119. }
  1120. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1121. foreach ($rw['_order_merge_rows'] as $mr) {
  1122. $mid = (int)($mr['ID'] ?? 0);
  1123. if ($this->isValidScydgyRowId($mid)) {
  1124. $idList[$mid] = true;
  1125. }
  1126. }
  1127. }
  1128. $id = (int)($rw['ID'] ?? 0);
  1129. if ($this->isValidScydgyRowId($id)) {
  1130. $idList[$id] = true;
  1131. }
  1132. }
  1133. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1134. $bidOpenSet = [];
  1135. if ($wffTab === 'audit') {
  1136. $ccydhList = [];
  1137. foreach ($rows as $rw0) {
  1138. if (!is_array($rw0)) {
  1139. continue;
  1140. }
  1141. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1142. if ($c0 !== '') {
  1143. $ccydhList[] = $c0;
  1144. }
  1145. }
  1146. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1147. }
  1148. foreach ($rows as &$rw) {
  1149. if (!is_array($rw)) {
  1150. continue;
  1151. }
  1152. $mergeIds = [];
  1153. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1154. foreach ($rw['_order_merge_rows'] as $mr) {
  1155. $mid = (int)($mr['ID'] ?? 0);
  1156. if ($this->isValidScydgyRowId($mid)) {
  1157. $mergeIds[$mid] = true;
  1158. }
  1159. }
  1160. }
  1161. $rid = (int)($rw['ID'] ?? 0);
  1162. if ($this->isValidScydgyRowId($rid)) {
  1163. $mergeIds[$rid] = true;
  1164. }
  1165. $buckets = [];
  1166. foreach (array_keys($mergeIds) as $mid) {
  1167. if (isset($quoteBucket[$mid])) {
  1168. $buckets[] = $quoteBucket[$mid];
  1169. }
  1170. }
  1171. $supplierText = $buckets !== []
  1172. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1173. : '';
  1174. if ($wffTab === 'confirm') {
  1175. $rw['picked_supplier_name'] = $supplierText;
  1176. } else {
  1177. $rw['notify_supplier_text'] = $supplierText;
  1178. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1179. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1180. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1181. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1182. }
  1183. }
  1184. unset($rw);
  1185. }
  1186. if ($wffTab === 'all' && count($rows) > 0) {
  1187. $this->mergePurchaseOrder($rows);
  1188. }
  1189. if ($wffTab === 'pick' && count($rows) > 0) {
  1190. $this->mergePurchaseOrder($rows);
  1191. }
  1192. foreach ($rows as &$rwClean) {
  1193. if (is_array($rwClean)) {
  1194. unset($rwClean['_order_merge_rows']);
  1195. if (array_key_exists('NGZL', $rwClean)) {
  1196. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1197. }
  1198. }
  1199. }
  1200. unset($rwClean);
  1201. return json([
  1202. 'total' => count($filtered),
  1203. 'rows' => $rows,
  1204. 'activeYm' => $ym,
  1205. ]);
  1206. } catch (\Throwable $e) {
  1207. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1208. return json([
  1209. 'total' => 0,
  1210. 'rows' => [],
  1211. ]);
  1212. }
  1213. }
  1214. /**
  1215. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1216. *
  1217. * @return array<int, true>
  1218. */
  1219. protected function loadPickHiddenScydgySet(): array
  1220. {
  1221. if ($this->pickHiddenScydgySetCache !== null) {
  1222. return $this->pickHiddenScydgySetCache;
  1223. }
  1224. $hideSet = [];
  1225. try {
  1226. $poIds = Db::table('purchase_order')
  1227. ->where(function ($q) {
  1228. $q->whereIn('wflow_status', array_merge(
  1229. ProcuremenStatus::wflowPendingConfirmValues(),
  1230. ProcuremenStatus::wflowPendingApprovalValues()
  1231. ))
  1232. ->whereOr(function ($q1) {
  1233. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1234. })
  1235. ->whereOr(function ($q2) {
  1236. $q2->whereNotNull('pick_time')
  1237. ->where('pick_time', '<>', '')
  1238. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1239. })
  1240. ->whereOr(function ($q3) {
  1241. $q3->whereNotNull('mod_rq')
  1242. ->where('mod_rq', '<>', '')
  1243. ->where('mod_rq', 'not like', '0000-00-00%');
  1244. });
  1245. })
  1246. ->column('scydgy_id');
  1247. if (is_array($poIds)) {
  1248. foreach ($poIds as $pid) {
  1249. $k = (int)$pid;
  1250. if ($k !== 0) {
  1251. $hideSet[$k] = true;
  1252. }
  1253. }
  1254. }
  1255. } catch (\Throwable $e) {
  1256. }
  1257. try {
  1258. $detIdsQuery = Db::table('purchase_order_detail');
  1259. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1260. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1261. if (is_array($detIds)) {
  1262. foreach ($detIds as $pid) {
  1263. $k = (int)$pid;
  1264. if ($this->isValidScydgyRowId($k)) {
  1265. $hideSet[$k] = true;
  1266. }
  1267. }
  1268. }
  1269. } catch (\Throwable $e) {
  1270. }
  1271. $this->pickHiddenScydgySetCache = $hideSet;
  1272. return $hideSet;
  1273. }
  1274. /**
  1275. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1276. *
  1277. * @return array<int, array<string, mixed>>
  1278. */
  1279. protected function loadPickManualOrderRows(): array
  1280. {
  1281. try {
  1282. $dbRows = Db::table('purchase_order')
  1283. ->where('scydgy_id', '<', 0)
  1284. ->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%\')')
  1285. ->order('scydgy_id', 'asc')
  1286. ->select();
  1287. } catch (\Throwable $e) {
  1288. try {
  1289. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1290. } catch (\Throwable $e2) {
  1291. return [];
  1292. }
  1293. }
  1294. if (!is_array($dbRows) || $dbRows === []) {
  1295. return [];
  1296. }
  1297. $detailSidSet = [];
  1298. try {
  1299. $negIds = [];
  1300. foreach ($dbRows as $dbRow) {
  1301. if (!is_array($dbRow)) {
  1302. continue;
  1303. }
  1304. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1305. if ($sid < 0) {
  1306. $negIds[$sid] = true;
  1307. }
  1308. }
  1309. if ($negIds !== []) {
  1310. $detQuery = Db::table('purchase_order_detail')
  1311. ->where('scydgy_id', 'in', array_keys($negIds));
  1312. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1313. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1314. if (is_array($detRows)) {
  1315. foreach ($detRows as $did) {
  1316. $detailSidSet[(int)$did] = true;
  1317. }
  1318. }
  1319. }
  1320. } catch (\Throwable $e) {
  1321. }
  1322. $pool = [];
  1323. foreach ($dbRows as $dbRow) {
  1324. if (!is_array($dbRow)) {
  1325. continue;
  1326. }
  1327. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1328. if ($sid >= 0) {
  1329. continue;
  1330. }
  1331. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1332. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1333. continue;
  1334. }
  1335. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1336. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1337. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1338. continue;
  1339. }
  1340. if (isset($detailSidSet[$sid])) {
  1341. continue;
  1342. }
  1343. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1344. $r['_is_manual'] = 1;
  1345. $pool[] = $r;
  1346. }
  1347. return $pool;
  1348. }
  1349. /**
  1350. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1351. */
  1352. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1353. {
  1354. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1355. foreach ($keys as $k) {
  1356. $t = trim((string)($row[$k] ?? ''));
  1357. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1358. return $t;
  1359. }
  1360. }
  1361. return '';
  1362. }
  1363. /**
  1364. * 分配手工新增工序行 ID(负数递减)
  1365. */
  1366. protected function allocateManualScydgyId(): int
  1367. {
  1368. try {
  1369. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1370. $min = (int)$min;
  1371. return $min < 0 ? $min - 1 : -1;
  1372. } catch (\Throwable $e) {
  1373. return -1;
  1374. }
  1375. }
  1376. /**
  1377. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1378. */
  1379. protected function allocateManualOrderCcydh(): string
  1380. {
  1381. $prefix = 'YW' . date('Ymd');
  1382. $maxSeq = 0;
  1383. try {
  1384. $rows = Db::table('purchase_order')
  1385. ->where('CCYDH', 'like', $prefix . '%')
  1386. ->column('CCYDH');
  1387. if (is_array($rows)) {
  1388. foreach ($rows as $ccydh) {
  1389. $ccydh = trim((string)$ccydh);
  1390. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1391. $maxSeq = max($maxSeq, (int)$m[1]);
  1392. }
  1393. }
  1394. }
  1395. } catch (\Throwable $e) {
  1396. }
  1397. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1398. }
  1399. /**
  1400. * purchase_order.mod_rq 是否有有效软删除时间
  1401. */
  1402. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1403. {
  1404. $t = trim((string)$modRq);
  1405. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1406. }
  1407. /**
  1408. * 列表行 → purchase_order 写入字段
  1409. *
  1410. * @return array<string, mixed>
  1411. */
  1412. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1413. {
  1414. return [
  1415. 'scydgy_id' => $scydgyId,
  1416. 'CCYDH' => $row['CCYDH'] ?? null,
  1417. 'CYJMC' => $row['CYJMC'] ?? null,
  1418. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1419. 'CDXMC' => $row['CDXMC'] ?? null,
  1420. 'CGYBH' => $row['CGYBH'] ?? null,
  1421. 'CGYMC' => $row['CGYMC'] ?? null,
  1422. 'CDW' => $row['CDW'] ?? null,
  1423. 'NGZL' => $row['NGZL'] ?? null,
  1424. 'CDF' => $row['CDF'] ?? null,
  1425. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1426. 'MBZ' => $row['MBZ'] ?? null,
  1427. 'bwjg' => $row['bwjg'] ?? null,
  1428. 'iStatus' => $row['iStatus'] ?? null,
  1429. 'dStamp' => $row['dStamp'] ?? null,
  1430. 'dputrecord' => $row['dputrecord'] ?? null,
  1431. 'cywyxm' => $row['cywyxm'] ?? null,
  1432. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1433. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1434. ];
  1435. }
  1436. /**
  1437. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1438. *
  1439. * @return array{po:?array<string,mixed>, hidden:bool}
  1440. */
  1441. protected function resolvePickRowPoContext(int $sid): array
  1442. {
  1443. $po = null;
  1444. try {
  1445. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1446. if (is_array($found)) {
  1447. $po = $found;
  1448. }
  1449. } catch (\Throwable $e) {
  1450. }
  1451. $hideSet = $this->loadPickHiddenScydgySet();
  1452. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1453. }
  1454. /**
  1455. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1456. */
  1457. protected function assertPickRowCanDelete(int $sid, array $row): void
  1458. {
  1459. $ctx = $this->resolvePickRowPoContext($sid);
  1460. $po = $ctx['po'];
  1461. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1462. return;
  1463. }
  1464. if (is_array($po)) {
  1465. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1466. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1467. }
  1468. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1469. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1470. }
  1471. }
  1472. if ($ctx['hidden']) {
  1473. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1474. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1475. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1476. }
  1477. }
  1478. /**
  1479. * 初选直接完结前校验
  1480. */
  1481. protected function assertPickRowCanComplete(int $sid, array $row): void
  1482. {
  1483. $ctx = $this->resolvePickRowPoContext($sid);
  1484. $po = $ctx['po'];
  1485. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1486. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1487. }
  1488. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1489. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1490. }
  1491. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1492. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1493. }
  1494. }
  1495. /**
  1496. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1497. */
  1498. protected function softDeleteProcuremenPickRow(array $row): void
  1499. {
  1500. $sid = $this->extractScydgyRowId($row);
  1501. if (!$this->isValidScydgyRowId($sid)) {
  1502. throw new \InvalidArgumentException('无效的行主键');
  1503. }
  1504. $this->assertPickRowCanDelete($sid, $row);
  1505. $po = $this->resolvePickRowPoContext($sid)['po'];
  1506. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1507. return;
  1508. }
  1509. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1510. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1511. }
  1512. $now = date('Y-m-d H:i:s');
  1513. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1514. if (is_array($exists)) {
  1515. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1516. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1517. } else {
  1518. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1519. $data['mod_rq'] = $now;
  1520. $data['createtime'] = $now;
  1521. Db::table('purchase_order')->insert($data);
  1522. $poIdLog = (int)Db::getLastInsID();
  1523. }
  1524. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1525. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1526. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1527. if ($gymcLog !== '') {
  1528. $logTail .= ' / ' . $gymcLog;
  1529. }
  1530. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1531. }
  1532. /**
  1533. * 手工新增协助工序(写入 purchase_order)
  1534. *
  1535. * @param array<string, mixed> $params
  1536. * @return int scydgy_id
  1537. */
  1538. protected function saveManualPickOrder(array $params): int
  1539. {
  1540. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1541. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1542. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1543. if ($ccydh === '') {
  1544. $ccydh = $this->allocateManualOrderCcydh();
  1545. }
  1546. $now = date('Y-m-d H:i:s');
  1547. $sid = $this->allocateManualScydgyId();
  1548. $data = [
  1549. 'scydgy_id' => $sid,
  1550. 'CCYDH' => $ccydh,
  1551. 'CYJMC' => $cyjmc,
  1552. 'CGYMC' => $cgymc,
  1553. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1554. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1555. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1556. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1557. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1558. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1559. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1560. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1561. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1562. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1563. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1564. 'createtime' => $now,
  1565. 'dStamp' => $now,
  1566. 'dputrecord' => $now,
  1567. ];
  1568. Db::table('purchase_order')->insert($data);
  1569. $poId = (int)Db::getLastInsID();
  1570. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1571. return $sid;
  1572. }
  1573. protected function formatProcuremenRowLabel(array $row): string
  1574. {
  1575. $dh = trim((string)($row['CCYDH'] ?? ''));
  1576. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1577. if ($dh !== '' && $gymc !== '') {
  1578. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1579. }
  1580. if ($dh !== '') {
  1581. return '订单「' . $dh . '」';
  1582. }
  1583. if ($gymc !== '') {
  1584. return '工序「' . $gymc . '」';
  1585. }
  1586. $id = $this->extractScydgyRowId($row);
  1587. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1588. }
  1589. /**
  1590. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1591. */
  1592. protected function extractScydgyRowId(array $row): int
  1593. {
  1594. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1595. }
  1596. protected function isValidScydgyRowId(int $id): bool
  1597. {
  1598. return ProcuremenGuard::isValidScydgyId($id);
  1599. }
  1600. protected function isManualScydgyRowId(int $id): bool
  1601. {
  1602. return $id < 0;
  1603. }
  1604. /**
  1605. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1606. *
  1607. * @param int[] $scydgyIds
  1608. * @return array<int, string[]>
  1609. */
  1610. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1611. {
  1612. $out = [];
  1613. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1614. if ($scydgyIds === []) {
  1615. return $out;
  1616. }
  1617. try {
  1618. $rows = Db::table('purchase_order_detail')
  1619. ->where('scydgy_id', 'in', $scydgyIds)
  1620. ->field('scydgy_id,company_name')
  1621. ->order('company_name', 'asc')
  1622. ->select();
  1623. } catch (\Throwable $e) {
  1624. $rows = [];
  1625. }
  1626. if (!is_array($rows)) {
  1627. return $out;
  1628. }
  1629. foreach ($rows as $r) {
  1630. if (!is_array($r)) {
  1631. continue;
  1632. }
  1633. $sid = (int)($r['scydgy_id'] ?? 0);
  1634. $cn = trim((string)($r['company_name'] ?? ''));
  1635. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1636. continue;
  1637. }
  1638. if (!isset($out[$sid])) {
  1639. $out[$sid] = [];
  1640. }
  1641. if (!in_array($cn, $out[$sid], true)) {
  1642. $out[$sid][] = $cn;
  1643. }
  1644. }
  1645. return $out;
  1646. }
  1647. /**
  1648. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1649. *
  1650. * @param string[] $names
  1651. */
  1652. protected function formatNotifySupplierDisplay(array $names): string
  1653. {
  1654. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1655. return trim((string)$n);
  1656. }, $names))));
  1657. if ($names === []) {
  1658. return '';
  1659. }
  1660. sort($names, SORT_STRING);
  1661. return implode("\n", $names);
  1662. }
  1663. /**
  1664. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1665. *
  1666. * @param int[] $scydgyIds
  1667. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1668. */
  1669. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1670. {
  1671. $out = [];
  1672. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1673. if ($scydgyIds === []) {
  1674. return $out;
  1675. }
  1676. try {
  1677. $rows = Db::table('purchase_order_detail')
  1678. ->where('scydgy_id', 'in', $scydgyIds)
  1679. ->field('scydgy_id,company_name,amount')
  1680. ->select();
  1681. } catch (\Throwable $e) {
  1682. $rows = [];
  1683. }
  1684. if (!is_array($rows)) {
  1685. return $out;
  1686. }
  1687. foreach ($rows as $r) {
  1688. if (!is_array($r)) {
  1689. continue;
  1690. }
  1691. $sid = (int)($r['scydgy_id'] ?? 0);
  1692. $cn = trim((string)($r['company_name'] ?? ''));
  1693. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1694. continue;
  1695. }
  1696. if (!isset($out[$sid])) {
  1697. $out[$sid] = ['all' => [], 'quoted' => []];
  1698. }
  1699. $out[$sid]['all'][$cn] = true;
  1700. $am = trim((string)($r['amount'] ?? ''));
  1701. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1702. $out[$sid]['quoted'][$cn] = true;
  1703. }
  1704. }
  1705. return $out;
  1706. }
  1707. /**
  1708. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1709. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1710. */
  1711. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1712. {
  1713. $merged = ['all' => [], 'quoted' => []];
  1714. foreach ($buckets as $b) {
  1715. if (!is_array($b)) {
  1716. continue;
  1717. }
  1718. foreach ($b['all'] ?? [] as $cn => $_) {
  1719. $merged['all'][$cn] = true;
  1720. }
  1721. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1722. $merged['quoted'][$cn] = true;
  1723. }
  1724. }
  1725. return $merged;
  1726. }
  1727. /**
  1728. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1729. */
  1730. protected function formatQuotedSupplierLines(array $bucket): string
  1731. {
  1732. $all = array_keys($bucket['all'] ?? []);
  1733. if ($all === []) {
  1734. return '';
  1735. }
  1736. sort($all, SORT_STRING);
  1737. $lines = [];
  1738. foreach ($all as $cn) {
  1739. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1740. $lines[] = $cn . '(' . $status . ')';
  1741. }
  1742. return implode("\n", $lines);
  1743. }
  1744. /**
  1745. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1746. */
  1747. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1748. {
  1749. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1750. $this->view->engine->layout(false);
  1751. try {
  1752. $bodyHtml = $this->view->fetch($view);
  1753. $this->view->assign('dialogBody', $bodyHtml);
  1754. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1755. return $this->view->fetch('procuremen/dialog_lite_shell');
  1756. } finally {
  1757. if ($restoreLayout) {
  1758. $this->view->engine->layout($restoreLayout);
  1759. }
  1760. }
  1761. }
  1762. /**
  1763. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1764. */
  1765. protected function resolveBundleSysRq(array $bundle): string
  1766. {
  1767. foreach ($bundle['pos'] ?? [] as $po) {
  1768. if (!is_array($po)) {
  1769. continue;
  1770. }
  1771. $sr = trim((string)($po['sys_rq'] ?? ''));
  1772. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1773. return $sr;
  1774. }
  1775. }
  1776. return '';
  1777. }
  1778. /**
  1779. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1780. */
  1781. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1782. {
  1783. $raw = trim((string)$sysRq);
  1784. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1785. return true;
  1786. }
  1787. $ts = strtotime(str_replace('T', ' ', $raw));
  1788. if ($ts === false || $ts <= 0) {
  1789. return true;
  1790. }
  1791. return time() >= $ts;
  1792. }
  1793. /**
  1794. * 开标前校验:必须已过报价截止时间
  1795. *
  1796. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1797. */
  1798. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1799. {
  1800. $sysRq = $this->resolveBundleSysRq($bundle);
  1801. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1802. $this->error('未到截止时间');
  1803. }
  1804. }
  1805. /**
  1806. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1807. *
  1808. * @param array<string, mixed> $d
  1809. * @param string $deliveryYmd
  1810. */
  1811. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1812. {
  1813. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1814. return max(0, (int)$d['lead_days']);
  1815. }
  1816. if ($deliveryYmd === '') {
  1817. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1818. }
  1819. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1820. return null;
  1821. }
  1822. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1823. $t2 = strtotime($m[1] . ' 00:00:00');
  1824. if ($t1 === false || $t2 === false) {
  1825. return null;
  1826. }
  1827. return max(0, (int)round(($t2 - $t1) / 86400));
  1828. }
  1829. /**
  1830. * @param int|null $days
  1831. */
  1832. protected function formatProcuremenLeadDaysText($days): string
  1833. {
  1834. if ($days === null || $days === '') {
  1835. return '未填写';
  1836. }
  1837. if (!is_numeric($days)) {
  1838. return '未填写';
  1839. }
  1840. return ((int)$days) . '天';
  1841. }
  1842. /**
  1843. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  1844. *
  1845. * @param array<string, mixed> $line
  1846. */
  1847. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1848. {
  1849. $amountFilled = !empty($line['amount_filled']);
  1850. $deliveryFilled = !empty($line['delivery_filled']);
  1851. $leadFilled = !empty($line['lead_days_filled']);
  1852. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  1853. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1854. $line['amount_show'] = '';
  1855. if (array_key_exists('amount_text', $line)) {
  1856. $line['amount_text'] = $line['unit_price_text'];
  1857. }
  1858. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1859. $line['delivery_show'] = $deliveryText;
  1860. if (array_key_exists('delivery_text', $line)) {
  1861. $line['delivery_text'] = $deliveryText;
  1862. }
  1863. $line['delivery_ymd'] = '';
  1864. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  1865. $line['lead_days_show'] = $leadText;
  1866. $line['lead_days_text'] = $leadText;
  1867. $line['lead_days'] = '';
  1868. // 小计、操作时间与单价等同属报价信息,开标前不可见
  1869. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  1870. $line['subtotal_num'] = null;
  1871. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  1872. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1873. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1874. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  1875. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  1876. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  1877. $line['amount_filled'] = false;
  1878. $line['delivery_filled'] = false;
  1879. $line['lead_days_filled'] = false;
  1880. $line['is_quoted'] = false;
  1881. if (array_key_exists('quote_label', $line)) {
  1882. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  1883. }
  1884. }
  1885. protected function ensurePurchaseOrderBidOpenTable(): void
  1886. {
  1887. try {
  1888. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1889. } catch (\Throwable $e) {
  1890. Db::execute(
  1891. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1892. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1893. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1894. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1895. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1896. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1897. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1898. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1899. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1900. `createtime` datetime DEFAULT NULL,
  1901. PRIMARY KEY (`id`),
  1902. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1903. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1904. );
  1905. }
  1906. }
  1907. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1908. {
  1909. $ccydh = trim($ccydh);
  1910. if ($ccydh === '') {
  1911. return false;
  1912. }
  1913. $this->ensurePurchaseOrderBidOpenTable();
  1914. try {
  1915. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1916. return is_array($row);
  1917. } catch (\Throwable $e) {
  1918. return false;
  1919. }
  1920. }
  1921. /**
  1922. * 批量查询订单是否已开标验证
  1923. *
  1924. * @param array<int, string> $ccydhs
  1925. * @return array<string, bool> ccydh => true
  1926. */
  1927. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  1928. {
  1929. $set = [];
  1930. $list = [];
  1931. foreach ($ccydhs as $c) {
  1932. $c = trim((string)$c);
  1933. if ($c !== '') {
  1934. $list[$c] = true;
  1935. }
  1936. }
  1937. if ($list === []) {
  1938. return $set;
  1939. }
  1940. $this->ensurePurchaseOrderBidOpenTable();
  1941. try {
  1942. $rows = Db::table('purchase_order_bid_open')
  1943. ->where('ccydh', 'in', array_keys($list))
  1944. ->field('ccydh')
  1945. ->select();
  1946. foreach ($rows as $row) {
  1947. if (!is_array($row)) {
  1948. continue;
  1949. }
  1950. $c = trim((string)($row['ccydh'] ?? ''));
  1951. if ($c !== '') {
  1952. $set[$c] = true;
  1953. }
  1954. }
  1955. } catch (\Throwable $e) {
  1956. return [];
  1957. }
  1958. return $set;
  1959. }
  1960. /**
  1961. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  1962. *
  1963. * @param array<string, mixed> $group
  1964. */
  1965. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  1966. {
  1967. if ($quoteVisible) {
  1968. $group['remark_quote_pending'] = 0;
  1969. return;
  1970. }
  1971. $group['remark'] = '';
  1972. $group['remark_quote_pending'] = 0;
  1973. }
  1974. /**
  1975. * @param array{ccydh?:string} $bundle
  1976. */
  1977. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1978. {
  1979. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1980. }
  1981. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1982. {
  1983. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1984. }
  1985. protected function loadBidOpenAdminUser(int $adminId): ?array
  1986. {
  1987. if ($adminId <= 0) {
  1988. return null;
  1989. }
  1990. try {
  1991. $row = Db::name('admin')->where('id', $adminId)->find();
  1992. } catch (\Throwable $e) {
  1993. return null;
  1994. }
  1995. if (!is_array($row)) {
  1996. return null;
  1997. }
  1998. $status = strtolower(trim((string)($row['status'] ?? '')));
  1999. if ($status !== '' && $status !== 'normal') {
  2000. return null;
  2001. }
  2002. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2003. return null;
  2004. }
  2005. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2006. if (!preg_match('/^1\d{10}$/', $phone)) {
  2007. return null;
  2008. }
  2009. $name = trim((string)($row['nickname'] ?? ''));
  2010. if ($name === '') {
  2011. $name = trim((string)($row['username'] ?? ''));
  2012. }
  2013. return [
  2014. 'id' => (int)$row['id'],
  2015. 'username' => trim((string)($row['username'] ?? '')),
  2016. 'nickname' => $name,
  2017. 'mobile' => $phone,
  2018. ];
  2019. }
  2020. /**
  2021. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2022. */
  2023. protected function bidOpenVerifierAuthGroupRootId(): int
  2024. {
  2025. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2026. return $id > 0 ? $id : 10;
  2027. }
  2028. /**
  2029. * @return int[]
  2030. */
  2031. protected function loadBidOpenVerifierAuthGroupIds(): array
  2032. {
  2033. static $memo = [];
  2034. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2035. if (isset($memo[$rootId])) {
  2036. return $memo[$rootId];
  2037. }
  2038. try {
  2039. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2040. } catch (\Throwable $e) {
  2041. $memo[$rootId] = [$rootId];
  2042. return $memo[$rootId];
  2043. }
  2044. if (!is_array($groups) || $groups === []) {
  2045. $memo[$rootId] = [$rootId];
  2046. return $memo[$rootId];
  2047. }
  2048. $groupList = [];
  2049. foreach ($groups as $g) {
  2050. if (is_array($g)) {
  2051. $groupList[] = $g;
  2052. }
  2053. }
  2054. if ($groupList === []) {
  2055. $memo[$rootId] = [$rootId];
  2056. return $memo[$rootId];
  2057. }
  2058. $tree = \fast\Tree::instance();
  2059. $tree->init($groupList);
  2060. $ids = $tree->getChildrenIds($rootId, true);
  2061. if (!is_array($ids) || $ids === []) {
  2062. $memo[$rootId] = [$rootId];
  2063. return $memo[$rootId];
  2064. }
  2065. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2066. return $memo[$rootId];
  2067. }
  2068. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2069. {
  2070. if ($adminId <= 0) {
  2071. return false;
  2072. }
  2073. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2074. if ($groupIds === []) {
  2075. return false;
  2076. }
  2077. try {
  2078. return (bool)Db::name('auth_group_access')
  2079. ->where('uid', $adminId)
  2080. ->where('group_id', 'in', $groupIds)
  2081. ->count();
  2082. } catch (\Throwable $e) {
  2083. return false;
  2084. }
  2085. }
  2086. /**
  2087. * @return array<int, array<string, mixed>>
  2088. */
  2089. protected function listBidOpenVerifierCandidates(): array
  2090. {
  2091. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2092. if ($groupIds === []) {
  2093. return [];
  2094. }
  2095. try {
  2096. $adminIds = Db::name('auth_group_access')
  2097. ->where('group_id', 'in', $groupIds)
  2098. ->column('uid');
  2099. } catch (\Throwable $e) {
  2100. $adminIds = [];
  2101. }
  2102. $adminIds = is_array($adminIds)
  2103. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2104. : [];
  2105. if ($adminIds === []) {
  2106. return [];
  2107. }
  2108. try {
  2109. $rows = Db::name('admin')
  2110. ->where('status', 'normal')
  2111. ->where('id', 'in', $adminIds)
  2112. ->where('mobile', '<>', '')
  2113. ->order('id', 'asc')
  2114. ->select();
  2115. } catch (\Throwable $e) {
  2116. return [];
  2117. }
  2118. if (!is_array($rows)) {
  2119. return [];
  2120. }
  2121. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2122. $out = [];
  2123. foreach ($rows as $row) {
  2124. if (!is_array($row)) {
  2125. continue;
  2126. }
  2127. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2128. if ($one === null) {
  2129. continue;
  2130. }
  2131. $out[] = [
  2132. 'id' => $one['id'],
  2133. 'username' => $one['username'],
  2134. 'nickname' => $one['nickname'],
  2135. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2136. 'mobile' => mask_phone($one['mobile']),
  2137. ];
  2138. }
  2139. return $out;
  2140. }
  2141. /**
  2142. * @param int[] $adminIds
  2143. * @return array<int, string>
  2144. */
  2145. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2146. {
  2147. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2148. if ($adminIds === []) {
  2149. return [];
  2150. }
  2151. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2152. try {
  2153. $rows = Db::name('auth_group_access')
  2154. ->alias('aga')
  2155. ->join('auth_group ag', 'aga.group_id = ag.id')
  2156. ->where('aga.uid', 'in', $adminIds)
  2157. ->where('aga.group_id', 'in', $groupIds)
  2158. ->field('aga.uid,ag.name')
  2159. ->order('aga.uid', 'asc')
  2160. ->order('aga.group_id', 'asc')
  2161. ->select();
  2162. } catch (\Throwable $e) {
  2163. return [];
  2164. }
  2165. if (!is_array($rows)) {
  2166. return [];
  2167. }
  2168. $out = [];
  2169. foreach ($rows as $row) {
  2170. if (!is_array($row)) {
  2171. continue;
  2172. }
  2173. $uid = (int)($row['uid'] ?? 0);
  2174. $name = trim((string)($row['name'] ?? ''));
  2175. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2176. continue;
  2177. }
  2178. $out[$uid] = $name;
  2179. }
  2180. return $out;
  2181. }
  2182. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2183. {
  2184. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2185. }
  2186. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2187. {
  2188. return 'procuremen_bidopen_wait_' . $adminId;
  2189. }
  2190. protected function renderBidOpenVerifySms(string $code): string
  2191. {
  2192. $tpl = '';
  2193. try {
  2194. $row = $this->loadNotifyTemplateRow('bid_open');
  2195. if (is_array($row)) {
  2196. $tpl = trim((string)($row['content'] ?? ''));
  2197. }
  2198. } catch (\Throwable $e) {
  2199. $tpl = '';
  2200. }
  2201. if ($tpl === '') {
  2202. $tpl = '【可集达】您的短信验证码是{code}';
  2203. }
  2204. return str_replace('{code}', $code, $tpl);
  2205. }
  2206. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2207. {
  2208. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2209. }
  2210. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2211. {
  2212. $code = trim($code);
  2213. if (!preg_match('/^\d{6}$/', $code)) {
  2214. return false;
  2215. }
  2216. $mock = Config::get('mproc.mock_sms_code');
  2217. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2218. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2219. return true;
  2220. }
  2221. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2222. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2223. return false;
  2224. }
  2225. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2226. return true;
  2227. }
  2228. /**
  2229. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2230. */
  2231. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2232. {
  2233. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2234. if ($ccydh === '') {
  2235. throw new \InvalidArgumentException('订单号无效');
  2236. }
  2237. $this->ensurePurchaseOrderBidOpenTable();
  2238. list($operatorId, $operatorName) = $this->GetUseName();
  2239. $now = date('Y-m-d H:i:s');
  2240. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2241. $payload = [
  2242. 'ccydh' => $ccydh,
  2243. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2244. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2245. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2246. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2247. 'operator_id' => (int)$operatorId,
  2248. 'operator_name' => trim((string)$operatorName),
  2249. 'createtime' => $now,
  2250. ];
  2251. if (is_array($exists)) {
  2252. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2253. } else {
  2254. Db::table('purchase_order_bid_open')->insert($payload);
  2255. }
  2256. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2257. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2258. $orderPart = '(订单' . $ccydh . ')';
  2259. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2260. $seenSid = [];
  2261. foreach ($bundle['pos'] ?? [] as $poRow) {
  2262. if (!is_array($poRow)) {
  2263. continue;
  2264. }
  2265. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2266. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2267. continue;
  2268. }
  2269. $seenSid[$sid] = true;
  2270. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2271. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2272. }
  2273. if ($seenSid === []) {
  2274. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2275. if ($this->isValidScydgyRowId($anchor)) {
  2276. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2277. }
  2278. }
  2279. }
  2280. /**
  2281. * 报价行展示字段默认值(模板安全访问)
  2282. *
  2283. * @param array<string, mixed> $line
  2284. * @return array<string, mixed>
  2285. */
  2286. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2287. {
  2288. if (!array_key_exists('amount_quote_pending', $line)) {
  2289. $line['amount_quote_pending'] = 0;
  2290. }
  2291. if (!array_key_exists('delivery_quote_pending', $line)) {
  2292. $line['delivery_quote_pending'] = 0;
  2293. }
  2294. if (!array_key_exists('quote_before_deadline', $line)) {
  2295. $line['quote_before_deadline'] = 0;
  2296. }
  2297. if (!array_key_exists('amount_filled', $line)) {
  2298. $line['amount_filled'] = 0;
  2299. }
  2300. if (!array_key_exists('delivery_filled', $line)) {
  2301. $line['delivery_filled'] = 0;
  2302. }
  2303. if (!array_key_exists('lead_days_filled', $line)) {
  2304. $line['lead_days_filled'] = 0;
  2305. }
  2306. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2307. $line['lead_days_quote_pending'] = 0;
  2308. }
  2309. if (!array_key_exists('lead_days_show', $line)) {
  2310. $line['lead_days_show'] = '未填写';
  2311. }
  2312. if (!array_key_exists('lead_days_text', $line)) {
  2313. $line['lead_days_text'] = $line['lead_days_show'];
  2314. }
  2315. return $line;
  2316. }
  2317. /**
  2318. * 审核弹窗:按供应商汇总报价明细
  2319. *
  2320. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2321. * @return array<int, array<string, mixed>>
  2322. */
  2323. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2324. {
  2325. $sids = [];
  2326. foreach ($bundle['pos'] ?? [] as $po) {
  2327. if (!is_array($po)) {
  2328. continue;
  2329. }
  2330. $sid = (int)($po['scydgy_id'] ?? 0);
  2331. if ($this->isValidScydgyRowId($sid)) {
  2332. $sids[$sid] = true;
  2333. }
  2334. }
  2335. if ($sids === []) {
  2336. return [];
  2337. }
  2338. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2339. $gymcMap = [];
  2340. $qtyBySid = [];
  2341. $orderedSids = [];
  2342. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2343. if (!is_array($mr)) {
  2344. continue;
  2345. }
  2346. $gid = $this->extractScydgyRowId($mr);
  2347. if ($this->isValidScydgyRowId($gid)) {
  2348. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2349. $orderedSids[] = $gid;
  2350. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2351. if ($qty === '') {
  2352. $qty = trim((string)($mr['NGZL'] ?? ''));
  2353. }
  2354. $qtyBySid[$gid] = $qty;
  2355. }
  2356. }
  2357. foreach ($bundle['pos'] ?? [] as $po) {
  2358. if (!is_array($po)) {
  2359. continue;
  2360. }
  2361. $gid = (int)($po['scydgy_id'] ?? 0);
  2362. if ($this->isValidScydgyRowId($gid)) {
  2363. $nm = trim((string)($po['CGYMC'] ?? ''));
  2364. if ($nm !== '') {
  2365. $gymcMap[$gid] = $nm;
  2366. }
  2367. if (!in_array($gid, $orderedSids, true)) {
  2368. $orderedSids[] = $gid;
  2369. }
  2370. }
  2371. }
  2372. try {
  2373. $detailsQuery = Db::table('purchase_order_detail')
  2374. ->where('scydgy_id', 'in', array_keys($sids));
  2375. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2376. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2377. } catch (\Throwable $e) {
  2378. try {
  2379. $detailsQuery = Db::table('purchase_order_detail')
  2380. ->where('scydgy_id', 'in', array_keys($sids));
  2381. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2382. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2383. } catch (\Throwable $e2) {
  2384. $details = [];
  2385. }
  2386. }
  2387. if (!is_array($details)) {
  2388. $details = [];
  2389. }
  2390. $byCompany = [];
  2391. foreach ($details as $d) {
  2392. if (!is_array($d)) {
  2393. continue;
  2394. }
  2395. $cn = trim((string)($d['company_name'] ?? ''));
  2396. if ($cn === '') {
  2397. continue;
  2398. }
  2399. if (!isset($byCompany[$cn])) {
  2400. $ph = trim((string)($d['phone'] ?? ''));
  2401. $username = trim((string)($d['username'] ?? ''));
  2402. if ($username === '') {
  2403. $username = $this->resolveCustomerContactName($ph, $cn);
  2404. }
  2405. $byCompany[$cn] = [
  2406. 'name' => $cn,
  2407. 'email' => trim((string)($d['email'] ?? '')),
  2408. 'phone' => $ph,
  2409. 'username' => $username,
  2410. 'remark' => '',
  2411. 'has_quote' => false,
  2412. 'lines_map' => [],
  2413. ];
  2414. }
  2415. if ($byCompany[$cn]['remark'] === '') {
  2416. $rm = '';
  2417. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2418. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2419. $rm = trim((string)$d[$rk]);
  2420. break;
  2421. }
  2422. }
  2423. if ($rm !== '') {
  2424. $byCompany[$cn]['remark'] = $rm;
  2425. }
  2426. }
  2427. $sid = (int)($d['scydgy_id'] ?? 0);
  2428. $am = trim((string)($d['amount'] ?? ''));
  2429. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2430. if ($gymc === '') {
  2431. $gymc = '工序';
  2432. }
  2433. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2434. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2435. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2436. $deliveryShow = $deliveryRaw;
  2437. }
  2438. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2439. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2440. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2441. $subtotal = null;
  2442. if ($amountNum !== null) {
  2443. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2444. }
  2445. $unitPriceText = $amountFilled
  2446. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2447. : '未填写';
  2448. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2449. $leadFilled = ($leadDays !== null);
  2450. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2451. $lineRow = [
  2452. 'cgymc' => $gymc,
  2453. 'amount' => $am,
  2454. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2455. 'amount_filled' => $amountFilled,
  2456. 'unit_price_text' => $unitPriceText,
  2457. 'delivery' => $deliveryRaw,
  2458. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2459. 'delivery_filled' => $deliveryFilled,
  2460. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2461. 'lead_days' => $leadFilled ? $leadDays : '',
  2462. 'lead_days_filled'=> $leadFilled,
  2463. 'lead_days_show' => $leadText,
  2464. 'lead_days_text' => $leadText,
  2465. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2466. 'subtotal_num' => $subtotal,
  2467. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2468. 'is_quoted' => $amountFilled,
  2469. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2470. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2471. ];
  2472. if (!$quoteVisible) {
  2473. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2474. }
  2475. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2476. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2477. }
  2478. foreach ($byCompany as $cn => $g) {
  2479. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2480. $lines = [];
  2481. $usedSids = [];
  2482. foreach ($orderedSids as $sid) {
  2483. if (!isset($linesMap[$sid])) {
  2484. continue;
  2485. }
  2486. $lines[] = $linesMap[$sid];
  2487. $usedSids[$sid] = true;
  2488. }
  2489. foreach ($linesMap as $sid => $ln) {
  2490. if (isset($usedSids[$sid])) {
  2491. continue;
  2492. }
  2493. $lines[] = $ln;
  2494. }
  2495. $total = count($lines);
  2496. $quoted = 0;
  2497. $groupTotal = 0.0;
  2498. $groupHasTotal = false;
  2499. if ($quoteVisible) {
  2500. foreach ($lines as $ln) {
  2501. $am = trim((string)($ln['amount'] ?? ''));
  2502. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2503. $quoted++;
  2504. }
  2505. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2506. $groupTotal += (float)$ln['subtotal_num'];
  2507. $groupHasTotal = true;
  2508. }
  2509. }
  2510. }
  2511. unset($byCompany[$cn]['lines_map']);
  2512. $byCompany[$cn]['lines'] = $lines;
  2513. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2514. $byCompany[$cn]['line_count'] = $total;
  2515. $byCompany[$cn]['has_total'] = $total > 0;
  2516. $byCompany[$cn]['has_remark'] = $total > 0;
  2517. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2518. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2519. // 工序行 + 备注行 + 总计行
  2520. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2521. }
  2522. return array_values($byCompany);
  2523. }
  2524. /**
  2525. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2526. *
  2527. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2528. * @return array<int, array<string, mixed>>
  2529. */
  2530. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2531. {
  2532. $sids = [];
  2533. $poIdMap = [];
  2534. foreach ($bundle['pos'] ?? [] as $po) {
  2535. if (!is_array($po)) {
  2536. continue;
  2537. }
  2538. $sid = (int)($po['scydgy_id'] ?? 0);
  2539. if ($this->isValidScydgyRowId($sid)) {
  2540. $sids[$sid] = true;
  2541. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2542. }
  2543. }
  2544. if ($sids === []) {
  2545. return [];
  2546. }
  2547. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2548. $gymcMap = [];
  2549. $qtyBySid = [];
  2550. $orderedSids = [];
  2551. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2552. if (!is_array($mr)) {
  2553. continue;
  2554. }
  2555. $gid = $this->extractScydgyRowId($mr);
  2556. if ($this->isValidScydgyRowId($gid)) {
  2557. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2558. $orderedSids[] = $gid;
  2559. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2560. if ($qty === '') {
  2561. $qty = trim((string)($mr['NGZL'] ?? ''));
  2562. }
  2563. $qtyBySid[$gid] = $qty;
  2564. }
  2565. }
  2566. foreach ($bundle['pos'] ?? [] as $po) {
  2567. if (!is_array($po)) {
  2568. continue;
  2569. }
  2570. $gid = (int)($po['scydgy_id'] ?? 0);
  2571. if ($this->isValidScydgyRowId($gid)) {
  2572. $nm = trim((string)($po['CGYMC'] ?? ''));
  2573. if ($nm !== '') {
  2574. $gymcMap[$gid] = $nm;
  2575. }
  2576. }
  2577. }
  2578. try {
  2579. $details = Db::table('purchase_order_detail')
  2580. ->where('scydgy_id', 'in', array_keys($sids))
  2581. ->order('company_name', 'asc')
  2582. ->order('id', 'asc')
  2583. ->select();
  2584. } catch (\Throwable $e) {
  2585. try {
  2586. $details = Db::table('purchase_order_detail')
  2587. ->where('scydgy_id', 'in', array_keys($sids))
  2588. ->order('company_name', 'asc')
  2589. ->order('ID', 'asc')
  2590. ->select();
  2591. } catch (\Throwable $e2) {
  2592. $details = [];
  2593. }
  2594. }
  2595. if (!is_array($details)) {
  2596. $details = [];
  2597. }
  2598. $byCompany = [];
  2599. foreach ($details as $d) {
  2600. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2601. continue;
  2602. }
  2603. $cn = trim((string)($d['company_name'] ?? ''));
  2604. if ($cn === '') {
  2605. continue;
  2606. }
  2607. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2608. $sid = (int)($d['scydgy_id'] ?? 0);
  2609. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2610. continue;
  2611. }
  2612. if (!isset($byCompany[$cn])) {
  2613. $ph = trim((string)($d['phone'] ?? ''));
  2614. $username = trim((string)($d['username'] ?? ''));
  2615. if ($username === '') {
  2616. $username = $this->resolveCustomerContactName($ph, $cn);
  2617. }
  2618. $byCompany[$cn] = [
  2619. 'name' => $cn,
  2620. 'email' => trim((string)($d['email'] ?? '')),
  2621. 'phone' => $ph,
  2622. 'username' => $username,
  2623. 'remark' => '',
  2624. 'pick_lines' => [],
  2625. 'detail_picks' => [],
  2626. ];
  2627. }
  2628. if ($byCompany[$cn]['remark'] === '') {
  2629. $rm = '';
  2630. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2631. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2632. $rm = trim((string)$d[$rk]);
  2633. break;
  2634. }
  2635. }
  2636. if ($rm !== '') {
  2637. $byCompany[$cn]['remark'] = $rm;
  2638. }
  2639. }
  2640. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2641. if ($gymc === '') {
  2642. $gymc = '工序';
  2643. }
  2644. $am = trim((string)($d['amount'] ?? ''));
  2645. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2646. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2647. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2648. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2649. $deliveryShow = $deliveryRaw;
  2650. }
  2651. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2652. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2653. $subtotal = null;
  2654. if ($amountNum !== null) {
  2655. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2656. }
  2657. $unitPriceText = $amountFilled
  2658. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2659. : '未填写';
  2660. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2661. $leadFilled = ($leadDays !== null);
  2662. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2663. $pickLine = [
  2664. 'cgymc' => $gymc,
  2665. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2666. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2667. 'amount_filled' => $amountFilled,
  2668. 'delivery_filled' => $deliveryFilled,
  2669. 'unit_price_text' => $unitPriceText,
  2670. 'lead_days' => $leadFilled ? $leadDays : '',
  2671. 'lead_days_filled'=> $leadFilled,
  2672. 'lead_days_show' => $leadText,
  2673. 'lead_days_text' => $leadText,
  2674. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2675. 'subtotal_num' => $subtotal,
  2676. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2677. 'is_quoted' => $amountFilled,
  2678. ];
  2679. if (!$quoteVisible) {
  2680. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2681. }
  2682. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2683. $byCompany[$cn]['detail_picks'][$sid] = [
  2684. 'scydgy_id' => $sid,
  2685. 'detail_id' => $detailId,
  2686. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2687. 'cgymc' => $gymc,
  2688. ];
  2689. }
  2690. $out = [];
  2691. foreach ($byCompany as $g) {
  2692. $pickLinesMap = $g['pick_lines'] ?? [];
  2693. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2694. continue;
  2695. }
  2696. $pickLines = [];
  2697. $usedLineSids = [];
  2698. foreach ($orderedSids as $sid) {
  2699. if (!isset($pickLinesMap[$sid])) {
  2700. continue;
  2701. }
  2702. $pickLines[] = $pickLinesMap[$sid];
  2703. $usedLineSids[$sid] = true;
  2704. }
  2705. foreach ($pickLinesMap as $sid => $ln) {
  2706. if (isset($usedLineSids[$sid])) {
  2707. continue;
  2708. }
  2709. $pickLines[] = $ln;
  2710. }
  2711. $groupTotal = 0.0;
  2712. $groupHasTotal = false;
  2713. if ($quoteVisible) {
  2714. foreach ($pickLines as $ln) {
  2715. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2716. $groupTotal += (float)$ln['subtotal_num'];
  2717. $groupHasTotal = true;
  2718. }
  2719. }
  2720. }
  2721. $lineCount = count($pickLines);
  2722. $g['pick_lines'] = $pickLines;
  2723. $g['line_count'] = $lineCount;
  2724. $g['has_total'] = $lineCount > 0;
  2725. $g['has_remark'] = $lineCount > 0;
  2726. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2727. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2728. // 工序行 + 备注行 + 总计行
  2729. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2730. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2731. $detailPicks = [];
  2732. $usedPickSids = [];
  2733. foreach ($orderedSids as $sid) {
  2734. if (!isset($detailPicksMap[$sid])) {
  2735. continue;
  2736. }
  2737. $detailPicks[] = $detailPicksMap[$sid];
  2738. $usedPickSids[$sid] = true;
  2739. }
  2740. foreach ($detailPicksMap as $sid => $dp) {
  2741. if (isset($usedPickSids[$sid])) {
  2742. continue;
  2743. }
  2744. $detailPicks[] = $dp;
  2745. }
  2746. $g['detail_picks'] = $detailPicks;
  2747. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2748. unset($g['detail_picks']);
  2749. $out[] = $g;
  2750. }
  2751. return $out;
  2752. }
  2753. /**
  2754. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2755. * @return array<int, int[]> scydgy_id => detail_id[]
  2756. */
  2757. protected function mapDetailIdsByScydgyId(array $details): array
  2758. {
  2759. $out = [];
  2760. foreach ($details as $d) {
  2761. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2762. continue;
  2763. }
  2764. $sid = (int)($d['scydgy_id'] ?? 0);
  2765. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2766. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2767. continue;
  2768. }
  2769. if (!isset($out[$sid])) {
  2770. $out[$sid] = [];
  2771. }
  2772. $out[$sid][] = $pk;
  2773. }
  2774. foreach ($out as $sid => $ids) {
  2775. $out[$sid] = array_values(array_unique($ids));
  2776. }
  2777. return $out;
  2778. }
  2779. /**
  2780. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2781. *
  2782. * @param array<string, mixed> $dbRow
  2783. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2784. */
  2785. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2786. {
  2787. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2788. $r = [
  2789. 'ID' => $sid,
  2790. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2791. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2792. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2793. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2794. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2795. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2796. 'CDW' => $dbRow['CDW'] ?? '',
  2797. 'NGZL' => $dbRow['NGZL'] ?? '',
  2798. 'CDF' => $dbRow['CDF'] ?? '',
  2799. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2800. 'MBZ' => $dbRow['MBZ'] ?? '',
  2801. 'bwjg' => $dbRow['bwjg'] ?? '',
  2802. 'iStatus' => $dbRow['iStatus'] ?? '',
  2803. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2804. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2805. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2806. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2807. 'dStamp' => $dbRow['dStamp'] ?? '',
  2808. 'pick_time' => $dbRow['pick_time'] ?? '',
  2809. ];
  2810. if ($sid > 0 && isset($dStampMap[$sid])) {
  2811. $t = trim((string)$dStampMap[$sid]);
  2812. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2813. $r['dStamp'] = $dStampMap[$sid];
  2814. }
  2815. }
  2816. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2817. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2818. $ct = $dbRow['createtime'];
  2819. if (is_numeric($ct) && (int)$ct > 946684800) {
  2820. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2821. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2822. $r['dStamp'] = trim($ct);
  2823. }
  2824. }
  2825. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2826. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2827. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2828. $fallback = trim((string)($r['dStamp'] ?? ''));
  2829. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2830. $r['dputrecord'] = $fallback;
  2831. }
  2832. }
  2833. if (array_key_exists('id', $dbRow)) {
  2834. $r['purchase_order_id'] = (int)$dbRow['id'];
  2835. }
  2836. if ($sid < 0) {
  2837. $r['_is_manual'] = 1;
  2838. }
  2839. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2840. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2841. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2842. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2843. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2844. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2845. $r['pick_time'] = $pickFallback;
  2846. break;
  2847. }
  2848. }
  2849. }
  2850. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2851. if ($pickNm !== '') {
  2852. $r['pick_company_name'] = $pickNm;
  2853. $r['picked_supplier_name'] = $pickNm;
  2854. }
  2855. return $r;
  2856. }
  2857. /**
  2858. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2859. *
  2860. * @return array<int, array<string, mixed>>
  2861. */
  2862. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2863. {
  2864. $pool = [];
  2865. if (!is_array($dbRows) || $dbRows === []) {
  2866. return $pool;
  2867. }
  2868. $dStampMap = [];
  2869. $sidList = [];
  2870. foreach ($dbRows as $tmpRow) {
  2871. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2872. $sid = (int)$tmpRow['scydgy_id'];
  2873. if ($sid > 0) {
  2874. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2875. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2876. $sidList[$sid] = true;
  2877. }
  2878. }
  2879. }
  2880. }
  2881. if ($sidList !== []) {
  2882. try {
  2883. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2884. } catch (\Throwable $e) {
  2885. $dStampMap = [];
  2886. }
  2887. }
  2888. foreach ($dbRows as $dbRow) {
  2889. if (!is_array($dbRow)) {
  2890. continue;
  2891. }
  2892. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2893. }
  2894. return $pool;
  2895. }
  2896. /**
  2897. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2898. *
  2899. * @param int[] $scydgyIds
  2900. * @return array<int, array<string, mixed>>
  2901. */
  2902. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2903. {
  2904. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2905. if ($scydgyIds === []) {
  2906. return [];
  2907. }
  2908. try {
  2909. $list = Db::table('purchase_order_detail')
  2910. ->where('scydgy_id', 'in', $scydgyIds)
  2911. ->field('scydgy_id,company_name,amount,delivery')
  2912. ->select();
  2913. } catch (\Throwable $e) {
  2914. $list = [];
  2915. }
  2916. return is_array($list) ? $list : [];
  2917. }
  2918. /**
  2919. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2920. *
  2921. * @param int[] $scydgyIds
  2922. * @param array<int, array<string, mixed>> $allRows
  2923. * @return array{cnt:int, amt:int, deliv:int}
  2924. */
  2925. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2926. {
  2927. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2928. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2929. if ($scydgyIds === [] || $allRows === []) {
  2930. return $out;
  2931. }
  2932. $idSet = array_flip($scydgyIds);
  2933. $all = [];
  2934. $withAmt = [];
  2935. $withDeliv = [];
  2936. foreach ($allRows as $r) {
  2937. if (!is_array($r)) {
  2938. continue;
  2939. }
  2940. $sid = (int)($r['scydgy_id'] ?? 0);
  2941. if (!isset($idSet[$sid])) {
  2942. continue;
  2943. }
  2944. $cn = trim((string)($r['company_name'] ?? ''));
  2945. if ($cn === '') {
  2946. continue;
  2947. }
  2948. $all[$cn] = true;
  2949. $am = $r['amount'] ?? null;
  2950. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2951. $withAmt[$cn] = true;
  2952. }
  2953. $dv = $r['delivery'] ?? null;
  2954. if ($dv !== null && trim((string)$dv) !== '') {
  2955. $withDeliv[$cn] = true;
  2956. }
  2957. }
  2958. return [
  2959. 'cnt' => count($all),
  2960. 'amt' => count($withAmt),
  2961. 'deliv' => count($withDeliv),
  2962. ];
  2963. }
  2964. /**
  2965. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2966. *
  2967. * @param int[] $scydgyIds
  2968. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2969. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2970. */
  2971. protected function OrderDetailSummary(array $scydgyIds)
  2972. {
  2973. $out = [];
  2974. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2975. if ($scydgyIds === []) {
  2976. return $out;
  2977. }
  2978. $list = [];
  2979. try {
  2980. $list = Db::table('purchase_order_detail')
  2981. ->where('scydgy_id', 'in', $scydgyIds)
  2982. ->field('id,scydgy_id,amount,delivery')
  2983. ->select();
  2984. } catch (\Throwable $e) {
  2985. $list = [];
  2986. }
  2987. if (!is_array($list)) {
  2988. return $out;
  2989. }
  2990. foreach ($list as $r) {
  2991. if (!is_array($r)) {
  2992. continue;
  2993. }
  2994. $ids = (int)($r['scydgy_id'] ?? 0);
  2995. if (!$this->isValidScydgyRowId($ids)) {
  2996. continue;
  2997. }
  2998. if (!isset($out[$ids])) {
  2999. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3000. }
  3001. $out[$ids]['cnt']++;
  3002. $am = $r['amount'] ?? null;
  3003. if ($am !== null && $am !== '') {
  3004. if (!(is_string($am) && trim($am) === '')) {
  3005. $out[$ids]['amt']++;
  3006. }
  3007. }
  3008. $dv = $r['delivery'] ?? null;
  3009. if ($dv !== null && trim((string)$dv) !== '') {
  3010. $out[$ids]['deliv']++;
  3011. }
  3012. }
  3013. return $out;
  3014. }
  3015. /**
  3016. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3017. *
  3018. * @return array
  3019. */
  3020. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3021. {
  3022. $strContains = function ($haystack, $needle) {
  3023. if ($needle === '') {
  3024. return false;
  3025. }
  3026. $haystack = (string)$haystack;
  3027. if (function_exists('mb_stripos')) {
  3028. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3029. }
  3030. return stripos($haystack, $needle) !== false;
  3031. };
  3032. $stripAlias = function ($f) {
  3033. return preg_replace('/^[ab]\./i', '', (string)$f);
  3034. };
  3035. $searchColNames = [];
  3036. foreach (explode(',', $this->searchFields) as $colRaw) {
  3037. $c = $stripAlias(trim($colRaw));
  3038. if ($c !== '') {
  3039. $searchColNames[] = $c;
  3040. }
  3041. }
  3042. $filtered = [];
  3043. foreach ($pool as $r) {
  3044. if (!is_array($r)) {
  3045. continue;
  3046. }
  3047. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3048. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3049. if (!$isManual) {
  3050. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3051. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3052. continue;
  3053. }
  3054. if ($applyMonthRange) {
  3055. $mo = (int)$m[2];
  3056. if ($mo < 1 || $mo > 12) {
  3057. continue;
  3058. }
  3059. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3060. $rowMonthStart = $ymRow . '-01 00:00:00';
  3061. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3062. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3063. continue;
  3064. }
  3065. }
  3066. } elseif ($applyMonthRange) {
  3067. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3068. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3069. $ds = $listTime;
  3070. }
  3071. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3072. continue;
  3073. }
  3074. $mo = (int)$m[2];
  3075. if ($mo < 1 || $mo > 12) {
  3076. continue;
  3077. }
  3078. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3079. $rowMonthStart = $ymRow . '-01 00:00:00';
  3080. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3081. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3082. continue;
  3083. }
  3084. }
  3085. if ($search !== '') {
  3086. $hitSearch = false;
  3087. foreach ($searchColNames as $c) {
  3088. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3089. if ($cell !== '' && $strContains($cell, $search)) {
  3090. $hitSearch = true;
  3091. break;
  3092. }
  3093. }
  3094. if (!$hitSearch) {
  3095. continue;
  3096. }
  3097. }
  3098. foreach ($filterArr as $fk => $fv) {
  3099. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3100. continue;
  3101. }
  3102. if (is_array($fv)) {
  3103. continue;
  3104. }
  3105. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3106. continue;
  3107. }
  3108. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3109. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3110. $field = $stripAlias($fk);
  3111. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3112. $cellStr = trim((string)$cell);
  3113. switch ($sym) {
  3114. case '=':
  3115. if ((string)$cell !== (string)$fv) {
  3116. continue 3;
  3117. }
  3118. break;
  3119. case '<>':
  3120. if ((string)$cell === (string)$fv) {
  3121. continue 3;
  3122. }
  3123. break;
  3124. case 'LIKE':
  3125. case 'NOT LIKE':
  3126. $needle = trim((string)$fv);
  3127. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3128. if ($sym === 'LIKE' && !$hit) {
  3129. continue 3;
  3130. }
  3131. if ($sym === 'NOT LIKE' && $hit) {
  3132. continue 3;
  3133. }
  3134. break;
  3135. case '>':
  3136. case '>=':
  3137. case '<':
  3138. case '<=':
  3139. if (!is_numeric($cell) && $cellStr === '') {
  3140. continue 3;
  3141. }
  3142. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  3143. $vv = (float)$fv;
  3144. if ($sym === '>' && !($cv > $vv)) {
  3145. continue 3;
  3146. }
  3147. if ($sym === '>=' && !($cv >= $vv)) {
  3148. continue 3;
  3149. }
  3150. if ($sym === '<' && !($cv < $vv)) {
  3151. continue 3;
  3152. }
  3153. if ($sym === '<=' && !($cv <= $vv)) {
  3154. continue 3;
  3155. }
  3156. break;
  3157. case 'RANGE':
  3158. case 'NOT RANGE':
  3159. case 'BETWEEN':
  3160. case 'NOT BETWEEN':
  3161. case 'BETWEEN TIME':
  3162. case 'NOT BETWEEN TIME':
  3163. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  3164. $rawR = str_replace(' - ', ',', $rawR);
  3165. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  3166. if (count($arr) < 2) {
  3167. break;
  3168. }
  3169. $lo = $arr[0];
  3170. $hi = $arr[1];
  3171. if ($lo === '' && $hi === '') {
  3172. break;
  3173. }
  3174. $isNot = (strpos($sym, 'NOT') !== false);
  3175. if ($lo === '') {
  3176. $in = ($cellStr !== '' && $cellStr <= $hi);
  3177. if ($isNot ? $in : !$in) {
  3178. continue 3;
  3179. }
  3180. break;
  3181. }
  3182. if ($hi === '') {
  3183. $in = ($cellStr !== '' && $cellStr >= $lo);
  3184. if ($isNot ? $in : !$in) {
  3185. continue 3;
  3186. }
  3187. break;
  3188. }
  3189. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3190. if ($isNot ? $in : !$in) {
  3191. continue 3;
  3192. }
  3193. break;
  3194. case 'NULL':
  3195. case 'IS NULL':
  3196. if ($cell !== null && $cell !== '') {
  3197. continue 3;
  3198. }
  3199. break;
  3200. case 'NOT NULL':
  3201. case 'IS NOT NULL':
  3202. if ($cell === null || $cell === '') {
  3203. continue 3;
  3204. }
  3205. break;
  3206. default:
  3207. break;
  3208. }
  3209. }
  3210. $filtered[] = $r;
  3211. }
  3212. return $filtered;
  3213. }
  3214. /**
  3215. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3216. */
  3217. public function snapshotToProcure()
  3218. {
  3219. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3220. $this->error(__('Invalid parameters'));
  3221. }
  3222. $row = json_decode($this->request->post('row_json', ''), true);
  3223. if (!is_array($row)) {
  3224. $this->error(__('Invalid parameters'));
  3225. }
  3226. try {
  3227. $ids = $this->extractScydgyRowId($row);
  3228. if (!$this->isValidScydgyRowId($ids)) {
  3229. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3230. }
  3231. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3232. $data = [
  3233. 'scydgy_id' => $ids,
  3234. 'CCYDH' => $row['CCYDH'] ?? null,
  3235. 'CYJMC' => $row['CYJMC'] ?? null,
  3236. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3237. 'CDXMC' => $row['CDXMC'] ?? null,
  3238. 'CGYBH' => $row['CGYBH'] ?? null,
  3239. 'CGYMC' => $row['CGYMC'] ?? null,
  3240. 'CDW' => $row['CDW'] ?? null,
  3241. 'NGZL' => $row['NGZL'] ?? null,
  3242. 'CDF' => $row['CDF'] ?? null,
  3243. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3244. 'MBZ' => $row['MBZ'] ?? null,
  3245. 'bwjg' => $row['bwjg'] ?? null,
  3246. 'iStatus' => $row['iStatus'] ?? null,
  3247. 'dStamp' => $row['dStamp'] ?? null,
  3248. 'dputrecord' => $row['dputrecord'] ?? null,
  3249. 'cywyxm' => $row['cywyxm'] ?? null,
  3250. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3251. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3252. ];
  3253. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3254. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3255. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3256. $this->success('操作成功');
  3257. return;
  3258. }
  3259. if ($exists) {
  3260. $upd = $data;
  3261. unset($upd['scydgy_id'], $upd['status']);
  3262. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3263. } else {
  3264. // 新增:不写 status(空/走库默认);仅写创建时间
  3265. $data['createtime'] = date('Y-m-d H:i:s');
  3266. Db::table('purchase_order')->insert($data);
  3267. }
  3268. } catch (\Throwable $e) {
  3269. $this->error($e->getMessage());
  3270. }
  3271. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3272. $this->success('操作成功');
  3273. }
  3274. /**
  3275. * 未发列表
  3276. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3277. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3278. */
  3279. public function completeDirectly()
  3280. {
  3281. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3282. $this->error(__('参数错误'));
  3283. }
  3284. if (!$this->procuremenCanComplete()) {
  3285. $this->error(__('You have no permission'));
  3286. }
  3287. $row = json_decode($this->request->post('row_json', ''), true);
  3288. if (!is_array($row)) {
  3289. $this->error(__('Invalid parameters'));
  3290. }
  3291. $finishRaw = $this->request->post('finish', '1');
  3292. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3293. $poIdLog = null;
  3294. try {
  3295. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3296. $ids = $this->extractScydgyRowId($row);
  3297. if (!$this->isValidScydgyRowId($ids)) {
  3298. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3299. }
  3300. if ($asComplete) {
  3301. $this->assertPickRowCanComplete($ids, $row);
  3302. }
  3303. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3304. $data = [
  3305. 'scydgy_id' => $ids,
  3306. 'CCYDH' => $row['CCYDH'] ?? null,
  3307. 'CYJMC' => $row['CYJMC'] ?? null,
  3308. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3309. 'CDXMC' => $row['CDXMC'] ?? null,
  3310. 'CGYBH' => $row['CGYBH'] ?? null,
  3311. 'CGYMC' => $row['CGYMC'] ?? null,
  3312. 'CDW' => $row['CDW'] ?? null,
  3313. 'NGZL' => $row['NGZL'] ?? null,
  3314. 'CDF' => $row['CDF'] ?? null,
  3315. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3316. 'MBZ' => $row['MBZ'] ?? null,
  3317. 'bwjg' => $row['bwjg'] ?? null,
  3318. 'iStatus' => $row['iStatus'] ?? null,
  3319. 'dStamp' => $row['dStamp'] ?? null,
  3320. 'dputrecord' => $row['dputrecord'] ?? null,
  3321. 'cywyxm' => $row['cywyxm'] ?? null,
  3322. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3323. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3324. ];
  3325. if ($asComplete) {
  3326. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3327. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3328. }
  3329. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3330. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3331. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3332. $this->success('操作成功');
  3333. return;
  3334. }
  3335. if ($exists) {
  3336. $upd = $data;
  3337. unset($upd['scydgy_id']);
  3338. if (!$asComplete) {
  3339. unset($upd['status']);
  3340. }
  3341. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3342. } else {
  3343. // 新增:不写 status;完结时 $data 已含 status=1
  3344. $data['createtime'] = date('Y-m-d H:i:s');
  3345. Db::table('purchase_order')->insert($data);
  3346. }
  3347. } catch (\Throwable $e) {
  3348. $this->error($e->getMessage());
  3349. }
  3350. try {
  3351. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3352. if (is_array($rpo)) {
  3353. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3354. $poIdLog = $tid > 0 ? $tid : null;
  3355. }
  3356. } catch (\Throwable $e) {
  3357. $poIdLog = null;
  3358. }
  3359. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3360. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3361. if ($asComplete) {
  3362. $this->addOrderLog(
  3363. $ids,
  3364. 'mark_complete',
  3365. '点击「完结」,已标记为已完结',
  3366. $poIdLog
  3367. );
  3368. try {
  3369. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3370. if ($pdfPublicPath === '') {
  3371. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3372. }
  3373. } catch (\Throwable $e) {
  3374. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3375. }
  3376. } else {
  3377. $this->addOrderLog(
  3378. $ids,
  3379. 'save_qty_price',
  3380. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3381. $poIdLog
  3382. );
  3383. }
  3384. $this->pickHiddenScydgySetCache = null;
  3385. $this->success("操作成功");
  3386. }
  3387. /**
  3388. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3389. *
  3390. * @param array<int, array> $rows 引用传递当前页行
  3391. */
  3392. protected function mergePurchaseOrder(array &$rows)
  3393. {
  3394. if ($rows === []) {
  3395. return;
  3396. }
  3397. $ids = [];
  3398. foreach ($rows as $rw) {
  3399. if (!is_array($rw)) {
  3400. continue;
  3401. }
  3402. $id = (int)($rw['ID'] ?? 0);
  3403. if ($id > 0) {
  3404. $ids[$id] = true;
  3405. }
  3406. }
  3407. $idList = array_keys($ids);
  3408. if ($idList === []) {
  3409. return;
  3410. }
  3411. try {
  3412. $list = Db::table('purchase_order')
  3413. ->where('scydgy_id', 'in', $idList)
  3414. ->field('scydgy_id,This_quantity,ceilingPrice')
  3415. ->select();
  3416. } catch (\Throwable $e) {
  3417. return;
  3418. }
  3419. if (!is_array($list)) {
  3420. return;
  3421. }
  3422. $byId = [];
  3423. foreach ($list as $dbRow) {
  3424. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3425. continue;
  3426. }
  3427. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3428. }
  3429. foreach ($rows as &$rw) {
  3430. if (!is_array($rw)) {
  3431. continue;
  3432. }
  3433. $sid = (int)($rw['ID'] ?? 0);
  3434. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3435. continue;
  3436. }
  3437. $db = $byId[$sid];
  3438. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3439. if (array_key_exists('This_quantity', $db)) {
  3440. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3441. }
  3442. if (array_key_exists('ceilingPrice', $db)) {
  3443. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3444. } elseif (array_key_exists('ceiling_price', $db)) {
  3445. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3446. }
  3447. }
  3448. unset($rw);
  3449. }
  3450. /**
  3451. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3452. */
  3453. public function purchaseConfirmPick()
  3454. {
  3455. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3456. $this->error(__('Invalid parameters'));
  3457. }
  3458. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3459. $this->error(__('You have no permission'));
  3460. }
  3461. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3462. if ($batchRaw !== '') {
  3463. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3464. return;
  3465. }
  3466. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3467. $sid = (int)$scydgyId;
  3468. if (!$this->isValidScydgyRowId($sid)) {
  3469. $this->error('参数无效');
  3470. }
  3471. $parseIdList = function ($raw) {
  3472. if (is_array($raw)) {
  3473. $arr = $raw;
  3474. } else {
  3475. $decoded = json_decode((string)$raw, true);
  3476. $arr = is_array($decoded) ? $decoded : [];
  3477. }
  3478. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3479. };
  3480. $selectedRaw = $this->request->post('selected_ids', null);
  3481. if ($selectedRaw === null || $selectedRaw === '') {
  3482. $legacy = (int)$this->request->post('selected_id', 0);
  3483. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3484. } else {
  3485. $selectedIds = $parseIdList($selectedRaw);
  3486. }
  3487. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3488. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3489. try {
  3490. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3491. } catch (\InvalidArgumentException $e) {
  3492. $this->error($e->getMessage());
  3493. } catch (\Throwable $e) {
  3494. $this->error($e->getMessage());
  3495. }
  3496. $this->pickHiddenScydgySetCache = null;
  3497. $this->success('操作成功', '', $result);
  3498. }
  3499. /**
  3500. * 整单采购确认(多道工序一次提交)
  3501. */
  3502. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3503. {
  3504. $decoded = json_decode($batchRaw, true);
  3505. if (!is_array($decoded) || $decoded === []) {
  3506. $this->error('提交数据无效');
  3507. }
  3508. $picks = [];
  3509. foreach ($decoded as $item) {
  3510. if (!is_array($item)) {
  3511. continue;
  3512. }
  3513. $sid = (int)($item['scydgy_id'] ?? 0);
  3514. if (!$this->isValidScydgyRowId($sid)) {
  3515. continue;
  3516. }
  3517. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3518. if (!is_array($sel)) {
  3519. $sel = [(int)$sel];
  3520. }
  3521. $unsel = $item['unselected_ids'] ?? [];
  3522. if (!is_array($unsel)) {
  3523. $unsel = json_decode((string)$unsel, true);
  3524. $unsel = is_array($unsel) ? $unsel : [];
  3525. }
  3526. $picks[] = [
  3527. 'scydgy_id' => $sid,
  3528. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3529. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3530. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3531. ];
  3532. }
  3533. if ($picks === []) {
  3534. $this->error('提交数据无效');
  3535. }
  3536. Db::startTrans();
  3537. $results = [];
  3538. try {
  3539. foreach ($picks as $pick) {
  3540. $results[] = $this->runPurchaseConfirmPick(
  3541. (int)$pick['scydgy_id'],
  3542. $pick['selected_ids'],
  3543. $pick['unselected_ids'],
  3544. (int)$pick['purchase_order_id'],
  3545. false,
  3546. false
  3547. );
  3548. }
  3549. Db::commit();
  3550. } catch (\Throwable $e) {
  3551. Db::rollback();
  3552. $msg = $e->getMessage();
  3553. $this->error($msg !== '' ? $msg : '提交失败');
  3554. }
  3555. try {
  3556. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3557. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3558. } catch (\Throwable $e) {
  3559. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3560. }
  3561. $this->pickHiddenScydgySetCache = null;
  3562. $this->success('操作成功', '', ['batch' => $results]);
  3563. }
  3564. /**
  3565. * @return array<string, mixed>
  3566. */
  3567. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3568. {
  3569. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3570. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3571. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3572. $scydgyId = (string)$sid;
  3573. if ($selectedIds === []) {
  3574. throw new \InvalidArgumentException('请至少勾选一条明细');
  3575. }
  3576. $inter = array_intersect($selectedIds, $unselectedIds);
  3577. if ($inter !== []) {
  3578. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3579. }
  3580. $allIds = $this->purchaseOrderDetail($sid);
  3581. if ($allIds === []) {
  3582. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3583. }
  3584. foreach ($selectedIds as $id) {
  3585. if (!in_array($id, $allIds, true)) {
  3586. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3587. }
  3588. }
  3589. foreach ($unselectedIds as $id) {
  3590. if (!in_array($id, $allIds, true)) {
  3591. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3592. }
  3593. }
  3594. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3595. sort($union, SORT_NUMERIC);
  3596. $expect = $allIds;
  3597. sort($expect, SORT_NUMERIC);
  3598. if ($union !== $expect) {
  3599. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3600. }
  3601. if ($manageTransaction) {
  3602. Db::startTrans();
  3603. }
  3604. try {
  3605. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3606. $aff = 0;
  3607. try {
  3608. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3609. } catch (\Throwable $e) {
  3610. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3611. }
  3612. if ($aff < 1) {
  3613. throw new \Exception('更新选中状态失败');
  3614. }
  3615. $poPayload = [
  3616. 'status' => ProcuremenStatus::PO_COMPLETED,
  3617. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3618. ];
  3619. if ($purchaseOrderId > 0) {
  3620. $poAff = (int)Db::table('purchase_order')
  3621. ->where('id', $purchaseOrderId)
  3622. ->where('scydgy_id', $sid)
  3623. ->update($poPayload);
  3624. if ($poAff < 1) {
  3625. throw new \Exception('主表订单不存在或与工序行不匹配');
  3626. }
  3627. } else {
  3628. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3629. if ($poAff < 1) {
  3630. throw new \Exception('未找到');
  3631. }
  3632. }
  3633. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3634. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3635. if ($manageTransaction) {
  3636. Db::commit();
  3637. }
  3638. } catch (\Throwable $e) {
  3639. if ($manageTransaction) {
  3640. Db::rollback();
  3641. }
  3642. throw $e;
  3643. }
  3644. $poIdFinal = $purchaseOrderId;
  3645. if ($poIdFinal <= 0) {
  3646. try {
  3647. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3648. if (is_array($rpo)) {
  3649. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3650. }
  3651. } catch (\Throwable $e) {
  3652. $poIdFinal = 0;
  3653. }
  3654. }
  3655. $pickNames = [];
  3656. foreach ($selectedIds as $pid) {
  3657. $dr = $this->purchaseOrderDetai($sid, $pid);
  3658. $nm = trim((string)($dr['company_name'] ?? ''));
  3659. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3660. }
  3661. $this->addOrderLog(
  3662. $sid,
  3663. 'purchase_confirm',
  3664. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3665. $poIdFinal > 0 ? $poIdFinal : null
  3666. );
  3667. if ($sendNotifications) {
  3668. try {
  3669. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3670. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3671. 'scydgy_id' => $sid,
  3672. 'selected_ids' => $selectedIds,
  3673. 'unselected_ids' => $unselectedIds,
  3674. 'purchase_order_id' => $purchaseOrderId,
  3675. ]]);
  3676. } catch (\Throwable $e) {
  3677. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3678. }
  3679. }
  3680. Log::write(sprintf(
  3681. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3682. $scydgyId,
  3683. $purchaseOrderId,
  3684. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3685. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3686. ), 'notice');
  3687. $pdfPublicPath = '';
  3688. try {
  3689. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3690. } catch (\Throwable $e) {
  3691. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3692. }
  3693. return [
  3694. 'scydgy_id' => $scydgyId,
  3695. 'purchase_order_id' => $purchaseOrderId,
  3696. 'selected_ids' => $selectedIds,
  3697. 'unselected_ids' => $unselectedIds,
  3698. 'purchase_confirm_pdf' => $pdfPublicPath,
  3699. ];
  3700. }
  3701. /**
  3702. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3703. *
  3704. * @param int[]|string[] $scydgyIds
  3705. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3706. */
  3707. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3708. {
  3709. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3710. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3711. if ($scydgyIds === []) {
  3712. return $empty;
  3713. }
  3714. $pos = [];
  3715. try {
  3716. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3717. } catch (\Throwable $e) {
  3718. $rows = [];
  3719. }
  3720. if (is_array($rows)) {
  3721. foreach ($rows as $po) {
  3722. if (is_array($po)) {
  3723. $pos[] = $po;
  3724. }
  3725. }
  3726. }
  3727. if ($pos === []) {
  3728. return $empty;
  3729. }
  3730. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3731. return [
  3732. 'ccydh' => $ccydh,
  3733. 'pos' => $pos,
  3734. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3735. ];
  3736. }
  3737. /**
  3738. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3739. *
  3740. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3741. * @param array<int, array<string, mixed>> $picks
  3742. */
  3743. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3744. {
  3745. if ($picks === []) {
  3746. return;
  3747. }
  3748. $fallbackDetailId = 0;
  3749. $winners = [];
  3750. $losers = [];
  3751. foreach ($picks as $pick) {
  3752. if (!is_array($pick)) {
  3753. continue;
  3754. }
  3755. $sid = (int)($pick['scydgy_id'] ?? 0);
  3756. if (!$this->isValidScydgyRowId($sid)) {
  3757. continue;
  3758. }
  3759. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3760. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3761. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3762. $fallbackDetailId = (int)$selectedIds[0];
  3763. }
  3764. foreach ($selectedIds as $pid) {
  3765. $dr = $this->purchaseOrderDetai($sid, $pid);
  3766. if (!is_array($dr)) {
  3767. continue;
  3768. }
  3769. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3770. }
  3771. foreach ($unselectedIds as $pid) {
  3772. $dr = $this->purchaseOrderDetai($sid, $pid);
  3773. if (!is_array($dr)) {
  3774. continue;
  3775. }
  3776. $key = $this->notifySupplierDedupeKey($dr);
  3777. if (!isset($winners[$key])) {
  3778. $losers[$key] = $dr;
  3779. }
  3780. }
  3781. }
  3782. if ($winners === [] && $losers === []) {
  3783. return;
  3784. }
  3785. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3786. $sendSmsSafe = function ($phone, $content) {
  3787. $phone = trim((string)$phone);
  3788. if ($phone === '') {
  3789. return;
  3790. }
  3791. try {
  3792. $this->smsbao($phone, $content);
  3793. } catch (\Throwable $e) {
  3794. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3795. }
  3796. };
  3797. foreach ($winners as $dr) {
  3798. $cname = trim((string)($dr['company_name'] ?? ''));
  3799. $ph = trim((string)($dr['phone'] ?? ''));
  3800. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3801. 'company_name' => $cname,
  3802. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3803. 'phone' => $ph,
  3804. ]));
  3805. $sendSmsSafe($ph, $sms);
  3806. }
  3807. foreach ($losers as $dr) {
  3808. $cname = trim((string)($dr['company_name'] ?? ''));
  3809. $ph = trim((string)($dr['phone'] ?? ''));
  3810. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3811. 'company_name' => $cname,
  3812. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3813. 'phone' => $ph,
  3814. ]));
  3815. $sendSmsSafe($ph, $sms);
  3816. }
  3817. }
  3818. /**
  3819. * 短信去重键:优先手机号,否则公司名
  3820. */
  3821. protected function notifySupplierDedupeKey(array $detailRow): string
  3822. {
  3823. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3824. if ($ph !== '') {
  3825. return 'p:' . $ph;
  3826. }
  3827. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3828. return 'c:' . $cn;
  3829. }
  3830. /**
  3831. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3832. *
  3833. * @param int[] $detailIds
  3834. */
  3835. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3836. {
  3837. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3838. if ($detailIds === []) {
  3839. return;
  3840. }
  3841. $payload = ['status_name' => $statusName];
  3842. try {
  3843. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3844. } catch (\Throwable $e) {
  3845. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3846. }
  3847. }
  3848. /**
  3849. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3850. */
  3851. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3852. {
  3853. try {
  3854. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3855. } catch (\Throwable $e) {
  3856. return;
  3857. }
  3858. if (!is_array($rows)) {
  3859. return;
  3860. }
  3861. foreach ($rows as $dr) {
  3862. if (!is_array($dr)) {
  3863. continue;
  3864. }
  3865. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3866. if ($id <= 0) {
  3867. continue;
  3868. }
  3869. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3870. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3871. try {
  3872. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3873. } catch (\Throwable $e) {
  3874. }
  3875. }
  3876. }
  3877. /**
  3878. * @param array<string, mixed> $detailRow
  3879. */
  3880. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3881. {
  3882. $am = $detailRow['amount'] ?? null;
  3883. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3884. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3885. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3886. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3887. }
  3888. /**
  3889. * @return int[]
  3890. */
  3891. protected function purchaseOrderDetail(int $scydgyId): array
  3892. {
  3893. if (!$this->isValidScydgyRowId($scydgyId)) {
  3894. return [];
  3895. }
  3896. try {
  3897. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3898. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3899. $list = $listQuery->select();
  3900. } catch (\Throwable $e) {
  3901. return [];
  3902. }
  3903. if (!is_array($list)) {
  3904. return [];
  3905. }
  3906. $ids = [];
  3907. foreach ($list as $r) {
  3908. if (!is_array($r)) {
  3909. continue;
  3910. }
  3911. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3912. if ($pk > 0) {
  3913. $ids[] = $pk;
  3914. }
  3915. }
  3916. return array_values(array_unique($ids));
  3917. }
  3918. /**
  3919. * 获取当前登录用户信息 [id, 展示名]
  3920. */
  3921. protected function GetUseName(): array
  3922. {
  3923. $id = 0;
  3924. $name = '';
  3925. try {
  3926. if ($this->auth && $this->auth->isLogin()) {
  3927. $u = $this->auth->getUserInfo();
  3928. if (is_array($u)) {
  3929. $id = (int)($u['id'] ?? 0);
  3930. $name = trim((string)($u['nickname'] ?? ''));
  3931. if ($name === '') {
  3932. $name = trim((string)($u['username'] ?? ''));
  3933. }
  3934. }
  3935. }
  3936. } catch (\Throwable $e) {
  3937. }
  3938. if ($name === '') {
  3939. $name = '未知用户';
  3940. }
  3941. return [$id, $name];
  3942. }
  3943. /**
  3944. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3945. */
  3946. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3947. {
  3948. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3949. }
  3950. /**
  3951. * 按主键取一条
  3952. */
  3953. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3954. {
  3955. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3956. return [];
  3957. }
  3958. try {
  3959. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3960. if (is_array($one)) {
  3961. return $one;
  3962. }
  3963. } catch (\Throwable $e) {
  3964. }
  3965. try {
  3966. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3967. if (is_array($one)) {
  3968. return $one;
  3969. }
  3970. } catch (\Throwable $e) {
  3971. }
  3972. return [];
  3973. }
  3974. /**
  3975. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3976. */
  3977. protected function formatProcuremenDetailTime($v): string
  3978. {
  3979. if ($v === null || $v === '') {
  3980. return '';
  3981. }
  3982. if (is_numeric($v) && (int)$v > 946684800) {
  3983. return date('Y-m-d H:i:s', (int)$v);
  3984. }
  3985. return ProcuremenTime::formatDisplayDateTime($v);
  3986. }
  3987. /**
  3988. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3989. */
  3990. protected function formatDeliveryYmd($v): string
  3991. {
  3992. if ($v === null || $v === '') {
  3993. return '';
  3994. }
  3995. $s = trim((string)$v);
  3996. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3997. return '';
  3998. }
  3999. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4000. return $m[1];
  4001. }
  4002. $ts = strtotime($s);
  4003. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4004. }
  4005. /**
  4006. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4007. */
  4008. protected function detailRowSupplierOperated(array $r): bool
  4009. {
  4010. $am = $r['amount'] ?? null;
  4011. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4012. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4013. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4014. return $okAmt || $okDel;
  4015. }
  4016. /**
  4017. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4018. */
  4019. protected function resolveDetailSupplierOperTime(array $r): string
  4020. {
  4021. if (!$this->detailRowSupplierOperated($r)) {
  4022. return '';
  4023. }
  4024. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4025. if ($t !== '') {
  4026. return $t;
  4027. }
  4028. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4029. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4030. continue;
  4031. }
  4032. $t = $this->formatProcuremenDetailTime($r[$col]);
  4033. if ($t !== '') {
  4034. return $t;
  4035. }
  4036. }
  4037. return '';
  4038. }
  4039. /**
  4040. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4041. */
  4042. protected function detailRowSupplierAccepted(array $r): bool
  4043. {
  4044. $am = $r['amount'] ?? null;
  4045. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4046. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4047. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4048. return $okAmt && $okDel;
  4049. }
  4050. /**
  4051. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4052. */
  4053. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4054. {
  4055. if ($detailCount > 0) {
  4056. return true;
  4057. }
  4058. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4059. return true;
  4060. }
  4061. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4062. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4063. return true;
  4064. }
  4065. return false;
  4066. }
  4067. /**
  4068. * 下发时间:优先 pick_time,其次首条下发明细时间
  4069. */
  4070. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4071. {
  4072. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4073. if ($issueTime !== '') {
  4074. return $issueTime;
  4075. }
  4076. foreach ($details as $dr) {
  4077. if (!is_array($dr)) {
  4078. continue;
  4079. }
  4080. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4081. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4082. $issueTime = $t;
  4083. }
  4084. }
  4085. if ($issueTime !== '') {
  4086. return $issueTime;
  4087. }
  4088. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4089. }
  4090. /**
  4091. * 直接点「完结」时间:优先操作记录 mark_complete
  4092. */
  4093. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4094. {
  4095. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4096. }
  4097. /**
  4098. * 操作记录时间(取指定 action 最近一条)
  4099. *
  4100. * @param string|array<int, string> $actions
  4101. */
  4102. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4103. {
  4104. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4105. }
  4106. /**
  4107. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4108. *
  4109. * @param array $main purchase_order 一行
  4110. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4111. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4112. */
  4113. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4114. {
  4115. $issueCnt = count($details);
  4116. $acceptCnt = 0;
  4117. $pickedName = '';
  4118. $pickedTime = '';
  4119. foreach ($details as $dr) {
  4120. if (!is_array($dr)) {
  4121. continue;
  4122. }
  4123. if ($this->detailRowSupplierAccepted($dr)) {
  4124. $acceptCnt++;
  4125. }
  4126. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4127. if ($pickedName === '') {
  4128. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4129. }
  4130. if ($pickedTime === '') {
  4131. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4132. if ($pickedTime === '') {
  4133. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4134. }
  4135. }
  4136. }
  4137. }
  4138. $hasMain = $main !== [];
  4139. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4140. if ($poTime === '') {
  4141. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4142. }
  4143. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4144. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4145. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4146. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4147. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4148. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4149. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4150. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4151. $supplierTime = '';
  4152. if ($acceptCnt > 0) {
  4153. foreach ($details as $dr) {
  4154. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4155. continue;
  4156. }
  4157. $t = $this->resolveDetailSupplierOperTime($dr);
  4158. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4159. $supplierTime = $t;
  4160. }
  4161. }
  4162. }
  4163. $directComplete = ($mainCompleted && !$issued);
  4164. $doneTime = '';
  4165. if ($mainCompleted) {
  4166. if ($directComplete) {
  4167. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4168. }
  4169. if ($doneTime === '') {
  4170. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4171. }
  4172. if ($doneTime === '') {
  4173. foreach ($details as $dr) {
  4174. if (!is_array($dr)) {
  4175. continue;
  4176. }
  4177. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4178. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4179. $doneTime = $t;
  4180. }
  4181. }
  4182. }
  4183. if ($doneTime === '') {
  4184. $doneTime = $poTime;
  4185. }
  4186. if ($confirmApproveTime !== '') {
  4187. $doneTime = $confirmApproveTime;
  4188. }
  4189. }
  4190. if ($directComplete) {
  4191. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4192. $step1Done = $hasMain;
  4193. $step2Done = false;
  4194. $step3Done = false;
  4195. $step4Done = false;
  4196. $step5Done = false;
  4197. $step6Done = true;
  4198. } else {
  4199. $step1Done = $issued;
  4200. $step2Done = $issued;
  4201. $step3Done = $acceptCnt > 0;
  4202. $step4Done = $wflowPendingApproval;
  4203. if (!$step4Done) {
  4204. foreach ($details as $dr) {
  4205. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4206. $step4Done = true;
  4207. break;
  4208. }
  4209. }
  4210. }
  4211. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4212. $step6Done = $mainCompleted;
  4213. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4214. if ($mainCompleted && $issued) {
  4215. $step3Done = true;
  4216. $step4Done = true;
  4217. $step5Done = true;
  4218. if ($supplierTime === '') {
  4219. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4220. if ($fillT !== '') {
  4221. $supplierTime = $fillT;
  4222. }
  4223. }
  4224. if ($pickedTime === '') {
  4225. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4226. if ($fillT !== '') {
  4227. $pickedTime = $fillT;
  4228. }
  4229. }
  4230. if ($auditSelectTime === '') {
  4231. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4232. if ($fillT !== '') {
  4233. $auditSelectTime = $fillT;
  4234. }
  4235. }
  4236. if ($confirmApproveTime === '') {
  4237. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4238. if ($fillT !== '') {
  4239. $confirmApproveTime = $fillT;
  4240. }
  4241. }
  4242. }
  4243. }
  4244. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4245. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4246. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4247. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4248. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4249. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4250. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4251. $deadlineText = '';
  4252. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4253. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4254. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4255. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4256. $deadlineText = '招标截止 ' . $deadlineDisp;
  4257. }
  4258. }
  4259. $steps = [
  4260. [
  4261. 'title' => '未发',
  4262. 'subtitle' => '',
  4263. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4264. 'done' => $step1Done,
  4265. ],
  4266. [
  4267. 'title' => '下发',
  4268. 'subtitle' => $deadlineText,
  4269. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4270. 'done' => $step2Done,
  4271. ],
  4272. [
  4273. 'title' => '供应商接单',
  4274. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4275. 'time' => '',
  4276. 'done' => $step3Done,
  4277. ],
  4278. [
  4279. 'title' => '待确认',
  4280. 'subtitle' => $step4Done
  4281. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4282. : ($issued ? '待选供应商' : ''),
  4283. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4284. 'done' => $step4Done,
  4285. ],
  4286. [
  4287. 'title' => '待审批',
  4288. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4289. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4290. 'done' => $step5Done,
  4291. ],
  4292. [
  4293. 'title' => '已完结',
  4294. 'subtitle' => '',
  4295. 'time' => $step6Done ? $doneTime : '',
  4296. 'done' => $step6Done,
  4297. ],
  4298. ];
  4299. $currentIdx = count($steps) - 1;
  4300. if (!$directComplete) {
  4301. foreach ($steps as $i => $s) {
  4302. if (!$s['done']) {
  4303. $currentIdx = $i;
  4304. break;
  4305. }
  4306. }
  4307. }
  4308. $nSteps = count($steps);
  4309. foreach ($steps as $idx => &$s) {
  4310. $s['current'] = ($idx === $currentIdx);
  4311. if ($idx === 0) {
  4312. $s['pdf_left_bg'] = '';
  4313. } else {
  4314. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4315. }
  4316. if ($idx >= $nSteps - 1) {
  4317. $s['pdf_right_bg'] = '';
  4318. } else {
  4319. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4320. }
  4321. }
  4322. unset($s);
  4323. $labelMap = [
  4324. 'CCYDH' => '订单号',
  4325. 'CYJMC' => '印件名称',
  4326. 'CCLBMMC' => '承揽部门',
  4327. 'CGYMC' => '工序名称',
  4328. 'CDW' => '单位',
  4329. 'NGZL' => '工作量',
  4330. 'CDF' => '单价',
  4331. 'cGzzxMc' => '工作中心',
  4332. 'MBZ' => '备注',
  4333. 'This_quantity' => '本次数量',
  4334. 'ceilingPrice' => '最高限价',
  4335. ];
  4336. $orderSummary = [];
  4337. foreach ($labelMap as $key => $lab) {
  4338. if (!array_key_exists($key, $main)) {
  4339. continue;
  4340. }
  4341. $val = $main[$key];
  4342. if ($val === null) {
  4343. $val = '';
  4344. } elseif (!is_scalar($val)) {
  4345. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4346. } else {
  4347. $val = (string)$val;
  4348. }
  4349. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4350. }
  4351. $orderSummaryGrid = [];
  4352. $n = count($orderSummary);
  4353. for ($i = 0; $i < $n; $i += 2) {
  4354. $left = $orderSummary[$i];
  4355. $hasRight = ($i + 1) < $n;
  4356. $orderSummaryGrid[] = [
  4357. 'l1' => $left['label'],
  4358. 'v1' => $left['value'],
  4359. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4360. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4361. ];
  4362. }
  4363. return [
  4364. 'steps' => $steps,
  4365. 'orderSummary' => $orderSummary,
  4366. 'orderSummaryGrid' => $orderSummaryGrid,
  4367. 'detailRows' => $details,
  4368. ];
  4369. }
  4370. /**
  4371. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4372. *
  4373. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4374. */
  4375. protected function prepareProcuremenDetailsView(string $ids): array
  4376. {
  4377. $main = [];
  4378. try {
  4379. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4380. $main = is_array($one) ? $one : [];
  4381. } catch (\Throwable $e) {
  4382. $main = [];
  4383. }
  4384. $details = [];
  4385. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4386. if ($mergeRows === []) {
  4387. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4388. if ($mergeRows === [] && $main !== []) {
  4389. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4390. }
  4391. }
  4392. $detailSidList = [];
  4393. $anchorSid = (int)$ids;
  4394. if ($anchorSid !== 0) {
  4395. $detailSidList[$anchorSid] = true;
  4396. }
  4397. foreach ($mergeRows as $mr) {
  4398. if (!is_array($mr)) {
  4399. continue;
  4400. }
  4401. $sid = $this->extractScydgyRowId($mr);
  4402. if ($sid !== 0) {
  4403. $detailSidList[$sid] = true;
  4404. }
  4405. }
  4406. try {
  4407. if ($detailSidList !== []) {
  4408. $details = Db::table('purchase_order_detail')
  4409. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4410. ->order('id', 'asc')
  4411. ->select();
  4412. }
  4413. } catch (\Throwable $e) {
  4414. $details = [];
  4415. }
  4416. if (!is_array($details)) {
  4417. $details = [];
  4418. }
  4419. foreach ($details as &$r) {
  4420. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4421. $r['id'] = $r['ID'];
  4422. }
  4423. if (isset($r['createtime'])) {
  4424. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4425. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4426. } else {
  4427. $r['createtime_text'] = (string)$r['createtime'];
  4428. }
  4429. } else {
  4430. $r['createtime_text'] = '';
  4431. }
  4432. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4433. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4434. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4435. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4436. if (is_array($r)) {
  4437. $r = $this->maskSupplierContactFields($r);
  4438. }
  4439. }
  4440. unset($r);
  4441. $activeDetails = [];
  4442. foreach ($details as $r) {
  4443. if (is_array($r) && empty($r['is_void'])) {
  4444. $activeDetails[] = $r;
  4445. }
  4446. }
  4447. $operLogs = [];
  4448. try {
  4449. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4450. } catch (\Throwable $e) {
  4451. $operLogs = [];
  4452. }
  4453. if (!is_array($operLogs)) {
  4454. $operLogs = [];
  4455. }
  4456. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4457. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4458. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4459. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4460. if ($ccydh === '') {
  4461. foreach ($details as $r) {
  4462. if (!is_array($r)) {
  4463. continue;
  4464. }
  4465. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4466. if ($ccydh !== '') {
  4467. break;
  4468. }
  4469. }
  4470. }
  4471. $this->view->assign('ccydh', $ccydh);
  4472. $this->view->assign('steps', $bundle['steps']);
  4473. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4474. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4475. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4476. $this->view->assign('processCount', count($mergeRows));
  4477. $this->view->assign('detailRows', $details);
  4478. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4479. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4480. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4481. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4482. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4483. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4484. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4485. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4486. $this->view->assign('operLogs', $operLogs);
  4487. return [
  4488. 'ok' => $main !== [] || $details !== [],
  4489. 'ccydh' => $ccydh,
  4490. ];
  4491. }
  4492. /**
  4493. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4494. */
  4495. public function details()
  4496. {
  4497. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4498. if (is_array($ids)) {
  4499. $ids = isset($ids[0]) ? $ids[0] : '';
  4500. }
  4501. $ids = trim((string)$ids);
  4502. if ($ids === '') {
  4503. $this->error(__('Invalid parameters'));
  4504. }
  4505. $this->assertManualOrderDetailsViewable((int)$ids);
  4506. $this->prepareProcuremenDetailsView($ids);
  4507. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4508. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4509. $this->view->engine->layout(false);
  4510. try {
  4511. return $this->view->fetch('procuremen/details_dialog_shell');
  4512. } finally {
  4513. if ($restoreLayout) {
  4514. $this->view->engine->layout($restoreLayout);
  4515. }
  4516. }
  4517. }
  4518. /**
  4519. * 解析合并审核工序行(订单号须一致,且均未协助)
  4520. *
  4521. * @return array<int, array<string, mixed>>
  4522. */
  4523. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4524. {
  4525. $primary = json_decode($rowJson, true);
  4526. if (!is_array($primary)) {
  4527. $this->error(__('Invalid parameters'));
  4528. }
  4529. $merge = json_decode($mergeRowsJson, true);
  4530. if (!is_array($merge) || $merge === []) {
  4531. $merge = [$primary];
  4532. }
  4533. $seen = [];
  4534. $out = [];
  4535. foreach ($merge as $r) {
  4536. if (!is_array($r)) {
  4537. continue;
  4538. }
  4539. $id = $this->extractScydgyRowId($r);
  4540. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4541. continue;
  4542. }
  4543. $seen[$id] = true;
  4544. $out[] = $r;
  4545. }
  4546. if ($out === []) {
  4547. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4548. }
  4549. $ccydh = null;
  4550. foreach ($out as $r) {
  4551. $dh = trim((string)($r['CCYDH'] ?? ''));
  4552. if ($ccydh === null) {
  4553. $ccydh = $dh;
  4554. } elseif ($dh !== $ccydh) {
  4555. $this->error('合并审核要求所选行的订单号一致');
  4556. }
  4557. }
  4558. $ids = [];
  4559. foreach ($out as $r) {
  4560. $id = $this->extractScydgyRowId($r);
  4561. if ($this->isValidScydgyRowId($id)) {
  4562. $ids[$id] = true;
  4563. }
  4564. }
  4565. $poBySid = [];
  4566. $detCntBySid = [];
  4567. if ($ids !== []) {
  4568. $idList = array_keys($ids);
  4569. try {
  4570. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4571. if (is_array($poList)) {
  4572. foreach ($poList as $po) {
  4573. if (!is_array($po)) {
  4574. continue;
  4575. }
  4576. $sid = (int)($po['scydgy_id'] ?? 0);
  4577. if ($this->isValidScydgyRowId($sid)) {
  4578. $poBySid[$sid] = $po;
  4579. }
  4580. }
  4581. }
  4582. } catch (\Throwable $e) {
  4583. }
  4584. try {
  4585. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4586. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4587. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4588. if (is_array($detRows)) {
  4589. foreach ($detRows as $dr) {
  4590. if (!is_array($dr)) {
  4591. continue;
  4592. }
  4593. $sid = (int)($dr['scydgy_id'] ?? 0);
  4594. if ($this->isValidScydgyRowId($sid)) {
  4595. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4596. }
  4597. }
  4598. }
  4599. } catch (\Throwable $e) {
  4600. }
  4601. }
  4602. foreach ($out as $r) {
  4603. $id = $this->extractScydgyRowId($r);
  4604. if (!$this->isValidScydgyRowId($id)) {
  4605. continue;
  4606. }
  4607. $po = $poBySid[$id] ?? null;
  4608. if (!is_array($po)) {
  4609. continue;
  4610. }
  4611. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4612. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4613. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4614. }
  4615. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4616. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4617. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4618. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4619. }
  4620. }
  4621. return $out;
  4622. }
  4623. /**
  4624. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4625. */
  4626. protected function maskSupplierContactFields(array $item): array
  4627. {
  4628. if (array_key_exists('email', $item)) {
  4629. $item['email'] = mask_email((string)$item['email']);
  4630. }
  4631. if (array_key_exists('phone', $item)) {
  4632. $item['phone'] = mask_phone((string)$item['phone']);
  4633. }
  4634. return $item;
  4635. }
  4636. /**
  4637. * @param array<int, array<string, mixed>> $list
  4638. * @return array<int, array<string, mixed>>
  4639. */
  4640. protected function maskSupplierContactList(array $list): array
  4641. {
  4642. $out = [];
  4643. foreach ($list as $item) {
  4644. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4645. }
  4646. return $out;
  4647. }
  4648. /**
  4649. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4650. *
  4651. * @return array<string, string>|null
  4652. */
  4653. protected function buildCustomerContactPayloadFromRow($row): ?array
  4654. {
  4655. if (!is_array($row)) {
  4656. return null;
  4657. }
  4658. $norm = [];
  4659. foreach ($row as $k => $v) {
  4660. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4661. }
  4662. $row = $norm;
  4663. $st = $row['status'] ?? '';
  4664. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4665. return null;
  4666. }
  4667. $companyName = '';
  4668. foreach (['company_name', 'name'] as $nk) {
  4669. if (!empty($row[$nk])) {
  4670. $companyName = trim((string)$row[$nk]);
  4671. break;
  4672. }
  4673. }
  4674. if ($companyName === '') {
  4675. return null;
  4676. }
  4677. $username = '';
  4678. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4679. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4680. $username = trim((string)$row[$uk]);
  4681. break;
  4682. }
  4683. }
  4684. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4685. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4686. if ($phone === '' && isset($row['account'])) {
  4687. $phone = trim((string)$row['account']);
  4688. }
  4689. if ($phone === '' && isset($row['mobile'])) {
  4690. $phone = trim((string)$row['mobile']);
  4691. }
  4692. if ($email === '' && $phone === '') {
  4693. return null;
  4694. }
  4695. $category = '';
  4696. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4697. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4698. $category = trim((string)$row[$ck]);
  4699. break;
  4700. }
  4701. }
  4702. return [
  4703. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4704. 'name' => $companyName,
  4705. 'company_name' => $companyName,
  4706. 'username' => $username,
  4707. 'email' => $email,
  4708. 'phone' => $phone,
  4709. 'category' => $category,
  4710. 'company_type' => $category,
  4711. ];
  4712. }
  4713. /**
  4714. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4715. */
  4716. protected function resolveCustomerContactById(string $id): ?array
  4717. {
  4718. $id = trim($id);
  4719. if ($id === '' || !ctype_digit($id)) {
  4720. return null;
  4721. }
  4722. try {
  4723. $row = Db::table('customer')->where('id', (int)$id)->find();
  4724. } catch (\Throwable $e) {
  4725. return null;
  4726. }
  4727. return $this->buildCustomerContactPayloadFromRow($row);
  4728. }
  4729. /**
  4730. * 按供应商名称解析联系信息(兼容旧提交数据)
  4731. */
  4732. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4733. {
  4734. $name = trim($name);
  4735. if ($name === '') {
  4736. return null;
  4737. }
  4738. try {
  4739. $row = Db::table('customer')
  4740. ->where(function ($q) use ($name) {
  4741. $q->where('company_name', $name)->whereOr('name', $name);
  4742. })
  4743. ->order('id', 'desc')
  4744. ->find();
  4745. } catch (\Throwable $e) {
  4746. return null;
  4747. }
  4748. return $this->buildCustomerContactPayloadFromRow($row);
  4749. }
  4750. /**
  4751. * 规范化下发/确认时勾选的供应商
  4752. *
  4753. * @param array<int, mixed> $companies
  4754. * @return array<int, array<string, string>>
  4755. */
  4756. protected function normalizePickCompanies(array $companies): array
  4757. {
  4758. $out = [];
  4759. foreach ($companies as $c) {
  4760. if (!is_array($c)) {
  4761. continue;
  4762. }
  4763. $resolved = null;
  4764. $cid = trim((string)($c['id'] ?? ''));
  4765. if ($cid !== '') {
  4766. $resolved = $this->resolveCustomerContactById($cid);
  4767. }
  4768. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4769. if ($resolved === null && $name !== '') {
  4770. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4771. }
  4772. if ($resolved === null) {
  4773. continue;
  4774. }
  4775. $out[] = $resolved;
  4776. }
  4777. return $out;
  4778. }
  4779. /**
  4780. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4781. *
  4782. * @param array<int, array<string, mixed>> $pool
  4783. * @return array<int, array<string, mixed>>
  4784. */
  4785. protected function collapseProcuremenPoolByOrder(array $pool): array
  4786. {
  4787. if ($pool === []) {
  4788. return [];
  4789. }
  4790. $groups = [];
  4791. foreach ($pool as $row) {
  4792. if (!is_array($row)) {
  4793. continue;
  4794. }
  4795. $dh = trim((string)($row['CCYDH'] ?? ''));
  4796. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4797. if (!isset($groups[$key])) {
  4798. $groups[$key] = [];
  4799. }
  4800. $groups[$key][] = $row;
  4801. }
  4802. $out = [];
  4803. foreach ($groups as $ccydh => $rows) {
  4804. if ($rows === []) {
  4805. continue;
  4806. }
  4807. usort($rows, function ($a, $b) {
  4808. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4809. });
  4810. $head = $rows[0];
  4811. $gymcList = [];
  4812. foreach ($rows as $r) {
  4813. $g = trim((string)($r['CGYMC'] ?? ''));
  4814. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4815. $gymcList[] = $g;
  4816. }
  4817. }
  4818. $merged = $head;
  4819. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4820. $merged['process_count'] = count($rows);
  4821. $merged['_order_merge_rows'] = $rows;
  4822. if (count($rows) > 1) {
  4823. $merged['CGYMC'] = implode('、', $gymcList);
  4824. }
  4825. $mergedPickTime = '';
  4826. foreach ($rows as $r) {
  4827. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4828. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4829. $mergedPickTime = $t;
  4830. }
  4831. }
  4832. if ($mergedPickTime !== '') {
  4833. $merged['pick_time'] = $mergedPickTime;
  4834. }
  4835. $out[] = $merged;
  4836. }
  4837. usort($out, function ($a, $b) {
  4838. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4839. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4840. if ($ta === $tb) {
  4841. $ida = (int)($a['purchase_order_id'] ?? 0);
  4842. $idb = (int)($b['purchase_order_id'] ?? 0);
  4843. if ($ida !== $idb) {
  4844. return $idb <=> $ida;
  4845. }
  4846. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4847. }
  4848. if ($ta === '') {
  4849. return 1;
  4850. }
  4851. if ($tb === '') {
  4852. return -1;
  4853. }
  4854. return strcmp($tb, $ta);
  4855. });
  4856. return $out;
  4857. }
  4858. /**
  4859. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4860. *
  4861. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4862. */
  4863. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4864. {
  4865. $scydgyId = trim($scydgyId);
  4866. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4867. if ($scydgyId === '') {
  4868. return $empty;
  4869. }
  4870. try {
  4871. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4872. } catch (\Throwable $e) {
  4873. $anchor = null;
  4874. }
  4875. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4876. return $empty;
  4877. }
  4878. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4879. if ($ccydh === '') {
  4880. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4881. }
  4882. try {
  4883. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4884. } catch (\Throwable $e) {
  4885. $pos = [$anchor];
  4886. }
  4887. if (!is_array($pos) || $pos === []) {
  4888. $pos = [$anchor];
  4889. }
  4890. return [
  4891. 'ccydh' => $ccydh,
  4892. 'pos' => $pos,
  4893. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4894. ];
  4895. }
  4896. /**
  4897. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4898. */
  4899. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4900. {
  4901. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4902. return false;
  4903. }
  4904. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4905. return false;
  4906. }
  4907. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4908. return true;
  4909. }
  4910. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4911. $sid = (int)($po['scydgy_id'] ?? 0);
  4912. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4913. }
  4914. return false;
  4915. }
  4916. /**
  4917. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4918. *
  4919. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4920. */
  4921. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4922. {
  4923. $scydgyId = trim($scydgyId);
  4924. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4925. if ($scydgyId === '') {
  4926. return $empty;
  4927. }
  4928. try {
  4929. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4930. } catch (\Throwable $e) {
  4931. $anchor = null;
  4932. }
  4933. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4934. return $empty;
  4935. }
  4936. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4937. if ($ccydh === '') {
  4938. return [
  4939. 'ccydh' => '',
  4940. 'pos' => [$anchor],
  4941. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4942. ];
  4943. }
  4944. try {
  4945. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4946. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4947. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4948. } catch (\Throwable $e) {
  4949. $pos = [$anchor];
  4950. }
  4951. if (!is_array($pos) || $pos === []) {
  4952. $pos = [$anchor];
  4953. }
  4954. $pos = array_values(array_filter($pos, function ($po) {
  4955. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4956. }));
  4957. if ($pos === []) {
  4958. $pos = [$anchor];
  4959. }
  4960. return [
  4961. 'ccydh' => $ccydh,
  4962. 'pos' => $pos,
  4963. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4964. ];
  4965. }
  4966. /**
  4967. * @param array<int, array<string, mixed>> $purchaseOrders
  4968. * @return array<int, array<string, mixed>>
  4969. */
  4970. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4971. {
  4972. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4973. $byId = [];
  4974. foreach ($pool as $r) {
  4975. if (!is_array($r)) {
  4976. continue;
  4977. }
  4978. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4979. if ($this->isValidScydgyRowId($sid)) {
  4980. $byId[$sid] = $r;
  4981. }
  4982. }
  4983. $out = [];
  4984. foreach ($purchaseOrders as $po) {
  4985. if (!is_array($po)) {
  4986. continue;
  4987. }
  4988. $sid = (int)($po['scydgy_id'] ?? 0);
  4989. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4990. $out[] = $byId[$sid];
  4991. }
  4992. }
  4993. return $out;
  4994. }
  4995. /**
  4996. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4997. *
  4998. * @return array<int, array<string, mixed>>
  4999. */
  5000. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5001. {
  5002. $scydgyId = trim($scydgyId);
  5003. if ($scydgyId === '') {
  5004. return [];
  5005. }
  5006. try {
  5007. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5008. } catch (\Throwable $e) {
  5009. $anchor = null;
  5010. }
  5011. if (!is_array($anchor)) {
  5012. return [];
  5013. }
  5014. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5015. return [];
  5016. }
  5017. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5018. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5019. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5020. try {
  5021. $q = Db::table('purchase_order');
  5022. if ($ccydh !== '') {
  5023. $q->where('CCYDH', $ccydh);
  5024. } else {
  5025. $q->where('scydgy_id', $scydgyId);
  5026. }
  5027. if ($isValidPick) {
  5028. $q->where('pick_time', $pickTime);
  5029. }
  5030. $pos = $q->order('scydgy_id', 'asc')->select();
  5031. } catch (\Throwable $e) {
  5032. $pos = [$anchor];
  5033. }
  5034. if (!is_array($pos) || $pos === []) {
  5035. $pos = [$anchor];
  5036. }
  5037. $pos = array_values(array_filter($pos, function ($po) {
  5038. if (!is_array($po)) {
  5039. return false;
  5040. }
  5041. $mr = $po['mod_rq'] ?? null;
  5042. if ($mr === null || $mr === '') {
  5043. return true;
  5044. }
  5045. $mrs = trim((string)$mr);
  5046. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5047. }));
  5048. if ($pos === []) {
  5049. $pos = [$anchor];
  5050. }
  5051. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5052. if ($rows === []) {
  5053. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5054. }
  5055. return $rows;
  5056. }
  5057. /**
  5058. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5059. *
  5060. * @param array<int, array<string, mixed>> $mergeRows
  5061. * @return array<int, array<string, mixed>>
  5062. */
  5063. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5064. {
  5065. $list = array_values($mergeRows);
  5066. $n = count($list);
  5067. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5068. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5069. $mergeSame = $n > 1 && $orderKey0 !== '';
  5070. if ($mergeSame) {
  5071. foreach ($list as $rr) {
  5072. if (!is_array($rr)) {
  5073. $mergeSame = false;
  5074. break;
  5075. }
  5076. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5077. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5078. $mergeSame = false;
  5079. break;
  5080. }
  5081. }
  5082. }
  5083. $out = [];
  5084. foreach ($list as $idx => $r) {
  5085. if (!is_array($r)) {
  5086. continue;
  5087. }
  5088. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5089. if (is_scalar($qty)) {
  5090. $qty = trim((string)$qty);
  5091. } else {
  5092. $qty = '';
  5093. }
  5094. if ($qty === '') {
  5095. $gzl = $r['NGZL'] ?? '';
  5096. if (is_scalar($gzl)) {
  5097. $qty = trim((string)$gzl);
  5098. }
  5099. }
  5100. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5101. $sid = $this->extractScydgyRowId($r);
  5102. $out[] = [
  5103. 'seq' => $idx + 1,
  5104. 'scydgy_id' => $sid,
  5105. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5106. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5107. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5108. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5109. 'NGZL' => $r['NGZL'] ?? '',
  5110. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5111. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5112. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5113. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5114. 'show_order_cells' => !$mergeSame || $idx === 0,
  5115. 'order_rowspan' => $mergeSame ? $n : 1,
  5116. ];
  5117. }
  5118. return $out;
  5119. }
  5120. /**
  5121. * 解析金额/数量(去千分位等非数字字符)
  5122. */
  5123. protected function parseProcuremenMoneyNumber($value): ?float
  5124. {
  5125. if ($value === null || $value === '') {
  5126. return null;
  5127. }
  5128. if (is_numeric($value)) {
  5129. return (float)$value;
  5130. }
  5131. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5132. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5133. }
  5134. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5135. {
  5136. if ($amount === null) {
  5137. return '';
  5138. }
  5139. return (string)(int)round($amount);
  5140. }
  5141. /**
  5142. * 列表/详情展示:工作量为 0 时显示空
  5143. */
  5144. protected function formatProcuremenWorkloadDisplay($value): string
  5145. {
  5146. if ($value === null || $value === '') {
  5147. return '';
  5148. }
  5149. $s = trim((string)$value);
  5150. if ($s === '') {
  5151. return '';
  5152. }
  5153. if (is_numeric($s) && (float)$s == 0) {
  5154. return '';
  5155. }
  5156. return $s;
  5157. }
  5158. /**
  5159. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5160. */
  5161. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5162. {
  5163. foreach ($details as $d) {
  5164. if (!is_array($d)) {
  5165. continue;
  5166. }
  5167. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5168. $cn = trim((string)($d['company_name'] ?? ''));
  5169. if ($cn !== '') {
  5170. return $cn;
  5171. }
  5172. }
  5173. }
  5174. return trim((string)($main['pick_company_name'] ?? ''));
  5175. }
  5176. /**
  5177. * 详情报价小计:单价 × 本工序本次数量
  5178. */
  5179. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5180. {
  5181. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5182. if ($unit === null) {
  5183. return null;
  5184. }
  5185. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5186. if ($qty === null || $qty <= 0) {
  5187. return null;
  5188. }
  5189. return $unit * $qty;
  5190. }
  5191. /**
  5192. * 详情页:工序小计 + 供应商分组报价与总计
  5193. *
  5194. * @param array<int, array<string, mixed>> $mergeRows
  5195. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5196. * @return array{
  5197. * process_rows: array,
  5198. * supplier_groups: array,
  5199. * order_total_text: string,
  5200. * order_total_has: bool,
  5201. * selected_company: string
  5202. * }
  5203. */
  5204. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5205. {
  5206. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5207. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5208. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5209. $qtyBySid = [];
  5210. $gymcBySid = [];
  5211. $orderedSids = [];
  5212. foreach ($mergeRows as $mr) {
  5213. if (!is_array($mr)) {
  5214. continue;
  5215. }
  5216. $sid = $this->extractScydgyRowId($mr);
  5217. if ($this->isValidScydgyRowId($sid)) {
  5218. $orderedSids[] = $sid;
  5219. }
  5220. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5221. if ($qty === '') {
  5222. $qty = trim((string)($mr['NGZL'] ?? ''));
  5223. }
  5224. $qtyBySid[$sid] = $qty;
  5225. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5226. }
  5227. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5228. $detailByCompanySid = [];
  5229. foreach ($details as $d) {
  5230. if (!is_array($d)) {
  5231. continue;
  5232. }
  5233. $cn = trim((string)($d['company_name'] ?? ''));
  5234. $sid = (int)($d['scydgy_id'] ?? 0);
  5235. if ($cn === '' || $sid === 0) {
  5236. continue;
  5237. }
  5238. if (!isset($detailByCompanySid[$cn])) {
  5239. $detailByCompanySid[$cn] = [];
  5240. }
  5241. $detailByCompanySid[$cn][$sid] = $d;
  5242. }
  5243. $supplierGroups = [];
  5244. foreach ($detailByCompanySid as $cn => $bySid) {
  5245. $lines = [];
  5246. $groupTotal = 0.0;
  5247. $groupHas = false;
  5248. $groupVoid = true;
  5249. $usedSids = [];
  5250. $appendLine = function (int $sid, array $d) use (
  5251. &$lines,
  5252. &$groupTotal,
  5253. &$groupHas,
  5254. &$groupVoid,
  5255. $qtyBySid,
  5256. $gymcBySid,
  5257. $quoteVisible
  5258. ) {
  5259. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5260. if (!$isVoid) {
  5261. $groupVoid = false;
  5262. }
  5263. $qtyStr = $qtyBySid[$sid] ?? '';
  5264. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5265. $am = trim((string)($d['amount'] ?? ''));
  5266. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5267. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5268. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5269. $sub = null;
  5270. if (!$isVoid && $amountNum !== null) {
  5271. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5272. }
  5273. $ct = $this->resolveDetailSupplierOperTime($d);
  5274. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5275. $leadFilled = ($leadDays !== null);
  5276. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5277. $line = [
  5278. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5279. 'unit_price_text' => $amountFilled
  5280. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5281. : '未填写',
  5282. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5283. 'delivery_ymd' => $deliveryYmd,
  5284. 'amount_filled' => $amountFilled,
  5285. 'delivery_filled' => $deliveryFilled,
  5286. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5287. 'lead_days' => $leadFilled ? $leadDays : '',
  5288. 'lead_days_filled'=> $leadFilled,
  5289. 'lead_days_show' => $leadText,
  5290. 'lead_days_text' => $leadText,
  5291. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5292. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5293. 'is_void' => $isVoid,
  5294. 'oper_time_text' => $ct,
  5295. ];
  5296. if (!$quoteVisible && !$isVoid) {
  5297. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5298. } elseif ($sub !== null) {
  5299. $groupTotal += $sub;
  5300. $groupHas = true;
  5301. }
  5302. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5303. };
  5304. foreach ($orderedSids as $sid) {
  5305. if (!isset($bySid[$sid])) {
  5306. continue;
  5307. }
  5308. $usedSids[$sid] = true;
  5309. $appendLine($sid, $bySid[$sid]);
  5310. }
  5311. foreach ($bySid as $sid => $d) {
  5312. if (isset($usedSids[$sid])) {
  5313. continue;
  5314. }
  5315. $appendLine((int)$sid, $d);
  5316. }
  5317. $firstDetail = null;
  5318. foreach ($bySid as $d) {
  5319. if (is_array($d)) {
  5320. $firstDetail = $d;
  5321. break;
  5322. }
  5323. }
  5324. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5325. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5326. if ($username === '' && $ph !== '') {
  5327. $username = $this->resolveCustomerContactName($ph, $cn);
  5328. }
  5329. $remark = '';
  5330. foreach ($bySid as $d) {
  5331. if (!is_array($d)) {
  5332. continue;
  5333. }
  5334. $rm = '';
  5335. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5336. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5337. $rm = trim((string)$d[$rk]);
  5338. break;
  5339. }
  5340. }
  5341. if ($rm !== '') {
  5342. $remark = $rm;
  5343. break;
  5344. }
  5345. }
  5346. $lineCount = count($lines);
  5347. $hasRemark = $lineCount > 0;
  5348. $supplierGroup = [
  5349. 'company_name' => $cn,
  5350. 'username' => $username,
  5351. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5352. 'phone' => $ph,
  5353. 'remark' => $remark,
  5354. 'has_remark' => $hasRemark,
  5355. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5356. 'is_void' => $groupVoid,
  5357. 'lines' => $lines,
  5358. 'line_count' => $lineCount,
  5359. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5360. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5361. 'has_total' => $lineCount > 0,
  5362. ];
  5363. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5364. $supplierGroups[] = $supplierGroup;
  5365. }
  5366. usort($supplierGroups, function ($a, $b) {
  5367. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5368. return ($a['is_void'] ?? false) ? 1 : -1;
  5369. }
  5370. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5371. return ($a['is_selected'] ?? false) ? -1 : 1;
  5372. }
  5373. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5374. });
  5375. return [
  5376. 'process_rows' => $processRows,
  5377. 'supplier_groups' => $supplierGroups,
  5378. 'order_total_text' => '',
  5379. 'order_total_has' => false,
  5380. 'selected_company' => $selectedCompany,
  5381. ];
  5382. }
  5383. /**
  5384. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5385. */
  5386. protected function buildProcessLinesPlain(array $mergeRows): string
  5387. {
  5388. $lines = [];
  5389. $i = 1;
  5390. foreach ($mergeRows as $r) {
  5391. if (!is_array($r)) {
  5392. continue;
  5393. }
  5394. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5395. $dw = trim((string)($r['CDW'] ?? ''));
  5396. $gzl = trim((string)($r['NGZL'] ?? ''));
  5397. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5398. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5399. if ($dw !== '') {
  5400. $parts[] = '单位:' . $dw;
  5401. }
  5402. if ($gzl !== '') {
  5403. $parts[] = '工作量:' . $gzl;
  5404. }
  5405. if ($qty !== '') {
  5406. $parts[] = '本次数量:' . $qty;
  5407. }
  5408. $lines[] = implode(' ', $parts);
  5409. $i++;
  5410. }
  5411. return implode("\n", $lines);
  5412. }
  5413. /**
  5414. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5415. *
  5416. * @return array<string, string>
  5417. */
  5418. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5419. {
  5420. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5421. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5422. }
  5423. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5424. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5425. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5426. $cyjmc = '';
  5427. foreach ($mergeRows as $mr) {
  5428. if (!is_array($mr)) {
  5429. continue;
  5430. }
  5431. if ($ccydh === '') {
  5432. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5433. }
  5434. if ($cyjmc === '') {
  5435. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5436. }
  5437. }
  5438. if ($pos !== []) {
  5439. $firstPo = $pos[0];
  5440. if (is_array($firstPo)) {
  5441. if ($ccydh === '') {
  5442. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5443. }
  5444. if ($cyjmc === '') {
  5445. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5446. }
  5447. }
  5448. }
  5449. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5450. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5451. if (is_array($any)) {
  5452. if ($ccydh === '') {
  5453. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5454. }
  5455. if ($cyjmc === '') {
  5456. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5457. }
  5458. }
  5459. }
  5460. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5461. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5462. $cgymc = '';
  5463. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5464. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5465. }
  5466. return [
  5467. 'ccydh' => $ccydh,
  5468. 'cyjmc' => $cyjmc,
  5469. 'cgymc' => $cgymc,
  5470. 'process_lines' => $processLines,
  5471. 'process_lines_html' => '',
  5472. ];
  5473. }
  5474. /**
  5475. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5476. */
  5477. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5478. {
  5479. $lines = [];
  5480. if ($ccydh !== '') {
  5481. $lines[] = '订单号:' . $ccydh;
  5482. }
  5483. if ($cyjmc !== '') {
  5484. $lines[] = '印件名称:' . $cyjmc;
  5485. }
  5486. if ($processPlain !== '') {
  5487. $lines[] = $processPlain;
  5488. }
  5489. return implode("\n", $lines);
  5490. }
  5491. /**
  5492. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5493. *
  5494. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5495. */
  5496. protected function buildPlatformLinksPlain(array $detailLinks): string
  5497. {
  5498. $lines = [];
  5499. $i = 1;
  5500. foreach ($detailLinks as $lk) {
  5501. if (!is_array($lk)) {
  5502. continue;
  5503. }
  5504. $url = trim((string)($lk['url'] ?? ''));
  5505. if ($url === '') {
  5506. continue;
  5507. }
  5508. $label = trim((string)($lk['cgymc'] ?? ''));
  5509. if ($label === '') {
  5510. $label = '工序' . $i;
  5511. }
  5512. $lines[] = $label . ':' . $url;
  5513. $i++;
  5514. }
  5515. return implode("\n", $lines);
  5516. }
  5517. /**
  5518. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5519. *
  5520. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5521. */
  5522. protected function buildPlatformLinksHtml(array $detailLinks): string
  5523. {
  5524. $parts = [];
  5525. $i = 1;
  5526. foreach ($detailLinks as $lk) {
  5527. if (!is_array($lk)) {
  5528. continue;
  5529. }
  5530. $url = trim((string)($lk['url'] ?? ''));
  5531. if ($url === '') {
  5532. continue;
  5533. }
  5534. $label = trim((string)($lk['cgymc'] ?? ''));
  5535. if ($label === '') {
  5536. $label = '工序' . $i;
  5537. }
  5538. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5539. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5540. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5541. $i++;
  5542. }
  5543. return implode("<br>\n", $parts);
  5544. }
  5545. /**
  5546. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5547. *
  5548. * @return array<string, mixed>
  5549. */
  5550. protected function loadMailerConfig(): array
  5551. {
  5552. try {
  5553. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5554. } catch (\Throwable $e) {
  5555. $cfg = [];
  5556. }
  5557. return is_array($cfg) ? $cfg : [];
  5558. }
  5559. protected function loadNotifyTemplateRow(string $scene): ?array
  5560. {
  5561. try {
  5562. $row = Db::table('purchase_sms_template')
  5563. ->where('scene', $scene)
  5564. ->where(function ($q) {
  5565. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5566. })
  5567. ->order('id', 'asc')
  5568. ->find();
  5569. } catch (\Throwable $e) {
  5570. return null;
  5571. }
  5572. if (!is_array($row) || $row === []) {
  5573. return null;
  5574. }
  5575. return [
  5576. 'title' => trim((string)($row['title'] ?? '')),
  5577. 'content' => trim((string)($row['content'] ?? '')),
  5578. ];
  5579. }
  5580. /**
  5581. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5582. */
  5583. protected function buildProcessLinesHtml(array $mergeRows): string
  5584. {
  5585. if (count($mergeRows) <= 1) {
  5586. $r = $mergeRows[0] ?? [];
  5587. if (!is_array($r)) {
  5588. return '';
  5589. }
  5590. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5591. $dw = trim((string)($r['CDW'] ?? ''));
  5592. $gzl = trim((string)($r['NGZL'] ?? ''));
  5593. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5594. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5595. if ($dw !== '') {
  5596. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5597. }
  5598. if ($gzl !== '') {
  5599. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5600. }
  5601. if ($qty !== '') {
  5602. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5603. }
  5604. return $html;
  5605. }
  5606. $rows = '';
  5607. $i = 1;
  5608. foreach ($mergeRows as $r) {
  5609. if (!is_array($r)) {
  5610. continue;
  5611. }
  5612. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5613. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5614. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5615. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5616. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5617. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5618. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5619. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5620. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5621. $i++;
  5622. }
  5623. if ($rows === '') {
  5624. return '';
  5625. }
  5626. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5627. . '<thead><tr style="background:#f5f5f5;">'
  5628. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5629. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5630. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5631. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5632. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5633. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5634. }
  5635. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5636. {
  5637. $sysRq = trim($sysRq);
  5638. if ($sysRq === '') {
  5639. if ($required) {
  5640. $this->error('请选择招标截止日期');
  5641. }
  5642. return '';
  5643. }
  5644. $ts = strtotime($sysRq);
  5645. if ($ts === false || $ts <= 0) {
  5646. $this->error('招标截止日期格式无效');
  5647. }
  5648. $ymd = date('Y-m-d', $ts);
  5649. if ($ymd < date('Y-m-d')) {
  5650. $this->error('招标截止日期不能早于今天');
  5651. }
  5652. if ($ts <= time()) {
  5653. $this->error('招标截止时间不能早于当前时间');
  5654. }
  5655. return date('Y-m-d H:i:s', $ts);
  5656. }
  5657. /**
  5658. * 确保 purchase_order.delivery_deadline 存在
  5659. */
  5660. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  5661. {
  5662. static $done = false;
  5663. if ($done) {
  5664. return;
  5665. }
  5666. $done = true;
  5667. try {
  5668. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  5669. if (empty($cols)) {
  5670. Db::execute(
  5671. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  5672. );
  5673. }
  5674. } catch (\Throwable $e) {
  5675. // ignore
  5676. }
  5677. }
  5678. /**
  5679. * 解析交货截止日期(仅年月日)
  5680. */
  5681. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  5682. {
  5683. $raw = trim($raw);
  5684. if ($raw === '') {
  5685. if ($required) {
  5686. $this->error('请选择交货截止日期');
  5687. }
  5688. return '';
  5689. }
  5690. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  5691. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  5692. } else {
  5693. $ts = strtotime(str_replace('/', '-', $raw));
  5694. if ($ts === false || $ts <= 0) {
  5695. $this->error('交货截止日期格式无效');
  5696. }
  5697. $ymd = date('Y-m-d', $ts);
  5698. }
  5699. if ($ymd < date('Y-m-d')) {
  5700. $this->error('交货截止日期不能早于今天');
  5701. }
  5702. return $ymd;
  5703. }
  5704. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  5705. {
  5706. $s = trim((string)$value);
  5707. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  5708. return '';
  5709. }
  5710. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5711. return $m[1];
  5712. }
  5713. $ts = strtotime(str_replace('/', '-', $s));
  5714. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  5715. }
  5716. /**
  5717. * @param array{pos?:array} $bundle
  5718. */
  5719. protected function resolveBundleDeliveryDeadline(array $bundle): string
  5720. {
  5721. foreach ($bundle['pos'] ?? [] as $po) {
  5722. if (!is_array($po)) {
  5723. continue;
  5724. }
  5725. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  5726. if ($d !== '') {
  5727. return $d;
  5728. }
  5729. }
  5730. return '';
  5731. }
  5732. protected function formatProcuremenSysRqForInput($sysRq): string
  5733. {
  5734. $sr = trim((string)$sysRq);
  5735. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5736. return '';
  5737. }
  5738. $ts = strtotime($sr);
  5739. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5740. }
  5741. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5742. {
  5743. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5744. if ($sr === '') {
  5745. return '—';
  5746. }
  5747. $ts = strtotime($sr);
  5748. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5749. }
  5750. /**
  5751. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5752. *
  5753. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5754. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5755. */
  5756. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5757. {
  5758. return $bundle;
  5759. }
  5760. /**
  5761. * 写入/更新 purchase_order(单道工序行)
  5762. */
  5763. protected function upsertPurchaseOrderFromRow(
  5764. array $row,
  5765. string $sysRqDb,
  5766. $wflowStatus = null,
  5767. ?string $pickTime = null,
  5768. ?array $exists = null,
  5769. ?string $deliveryDeadline = null
  5770. ): void {
  5771. $ids = $this->extractScydgyRowId($row);
  5772. if (!$this->isValidScydgyRowId($ids)) {
  5773. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5774. }
  5775. if ($exists === null) {
  5776. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5777. }
  5778. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  5779. $data = [
  5780. 'scydgy_id' => $ids,
  5781. 'CCYDH' => $row['CCYDH'] ?? null,
  5782. 'CYJMC' => $row['CYJMC'] ?? null,
  5783. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5784. 'CDXMC' => $row['CDXMC'] ?? null,
  5785. 'CGYBH' => $row['CGYBH'] ?? null,
  5786. 'CGYMC' => $row['CGYMC'] ?? null,
  5787. 'CDW' => $row['CDW'] ?? null,
  5788. 'NGZL' => $row['NGZL'] ?? null,
  5789. 'CDF' => $row['CDF'] ?? null,
  5790. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5791. 'MBZ' => $row['MBZ'] ?? null,
  5792. 'bwjg' => $row['bwjg'] ?? null,
  5793. 'iStatus' => $row['iStatus'] ?? null,
  5794. 'dStamp' => $row['dStamp'] ?? null,
  5795. 'dputrecord' => $row['dputrecord'] ?? null,
  5796. 'cywyxm' => $row['cywyxm'] ?? null,
  5797. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5798. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5799. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5800. 'sys_rq' => $sysRqDb,
  5801. ];
  5802. if ($deliveryDeadline !== null) {
  5803. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  5804. }
  5805. if ($wflowStatus !== null && $wflowStatus !== '') {
  5806. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5807. }
  5808. if ($pickTime !== null && $pickTime !== '') {
  5809. $data['pick_time'] = $pickTime;
  5810. $data['pick_company_name'] = '';
  5811. }
  5812. if ($exists) {
  5813. $upd = $data;
  5814. unset($upd['scydgy_id']);
  5815. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5816. } else {
  5817. $data['createtime'] = date('Y-m-d H:i:s');
  5818. Db::table('purchase_order')->insert($data);
  5819. }
  5820. }
  5821. /**
  5822. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5823. *
  5824. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5825. */
  5826. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5827. {
  5828. $toDb = function ($value) {
  5829. if ($value === null) {
  5830. return null;
  5831. }
  5832. if (is_scalar($value)) {
  5833. return $value;
  5834. }
  5835. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5836. };
  5837. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5838. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5839. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5840. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5841. if ($username === '') {
  5842. $username = $this->resolveCustomerContactName($phone, $companyName);
  5843. }
  5844. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5845. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5846. }
  5847. if ($phone === '') {
  5848. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5849. }
  5850. $detailLinks = [];
  5851. foreach ($mergeRows as $row) {
  5852. if (!is_array($row)) {
  5853. continue;
  5854. }
  5855. $sid = $this->extractScydgyRowId($row);
  5856. $detailId = 0;
  5857. if ($skipExisting) {
  5858. try {
  5859. $existsQuery = Db::table('purchase_order_detail')
  5860. ->where('scydgy_id', $sid)
  5861. ->where('company_name', $companyName);
  5862. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5863. $exists = $existsQuery->find();
  5864. } catch (\Throwable $e) {
  5865. $exists = null;
  5866. }
  5867. if (is_array($exists)) {
  5868. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5869. }
  5870. }
  5871. if ($detailId <= 0) {
  5872. $one = [
  5873. 'scydgy_id' => $toDb($sid),
  5874. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5875. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5876. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5877. 'username' => $username !== '' ? $username : null,
  5878. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5879. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5880. 'createtime' => date('Y-m-d H:i:s'),
  5881. 'status' => ProcuremenStatus::POD_UNPICKED,
  5882. 'status_name' => '未提交',
  5883. ];
  5884. Db::table('purchase_order_detail')->insert($one);
  5885. $detailId = (int)Db::getLastInsID();
  5886. }
  5887. $mprocUrl = '';
  5888. if ($buildMobileLinks && $detailId > 0) {
  5889. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5890. }
  5891. $detailLinks[] = [
  5892. 'detail_id' => $detailId,
  5893. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5894. 'url' => $mprocUrl,
  5895. ];
  5896. }
  5897. return $detailLinks;
  5898. }
  5899. /**
  5900. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5901. * @return array<string, mixed>
  5902. */
  5903. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5904. {
  5905. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5906. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5907. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5908. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5909. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5910. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5911. $isMerge = !empty($ctx['is_merge']);
  5912. $contactName = trim((string)($c['username'] ?? ''));
  5913. if ($contactName === '') {
  5914. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5915. }
  5916. $notifyVars = [
  5917. 'company_name' => $companyName,
  5918. 'contact_name' => $contactName,
  5919. 'phone' => $phone,
  5920. 'email' => $toEmail,
  5921. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5922. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5923. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5924. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5925. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5926. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5927. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5928. 'platform_url' => $platformUrl,
  5929. 'platform_links' => $platformLinksPlain,
  5930. 'platform_links_html' => $platformLinksHtml,
  5931. ];
  5932. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5933. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5934. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5935. return [
  5936. 'company_name' => $companyName,
  5937. 'phone' => $phone,
  5938. 'email' => $toEmail,
  5939. 'sms_content' => $smsContent,
  5940. 'mail_plain' => $mailPlain,
  5941. 'mail_body' => $mailBody,
  5942. 'notify_vars' => $notifyVars,
  5943. 'detail_links' => $detailLinks,
  5944. ];
  5945. }
  5946. /**
  5947. * @param array<string, mixed> $chosen
  5948. * @param array<int, array<string, mixed>> $mergeRows
  5949. * @param array{ccydh:string, pos:array} $bundle
  5950. */
  5951. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5952. {
  5953. if (!$sendSms && !$sendEmail) {
  5954. return;
  5955. }
  5956. $companyName = trim((string)($chosen['name'] ?? ''));
  5957. $phone = trim((string)($chosen['phone'] ?? ''));
  5958. $toEmail = trim((string)($chosen['email'] ?? ''));
  5959. if ($companyName === '') {
  5960. throw new \Exception('供应商名称无效');
  5961. }
  5962. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5963. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5964. }
  5965. if ($sendSms && $phone === '') {
  5966. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5967. }
  5968. $sids = [];
  5969. foreach ($mergeRows as $mr) {
  5970. if (!is_array($mr)) {
  5971. continue;
  5972. }
  5973. $sid = $this->extractScydgyRowId($mr);
  5974. if ($this->isValidScydgyRowId($sid)) {
  5975. $sids[$sid] = true;
  5976. }
  5977. }
  5978. if ($sids === []) {
  5979. throw new \Exception('未找到工序行,无法发送通知');
  5980. }
  5981. $sysRqNotify = '';
  5982. $pos = $bundle['pos'] ?? [];
  5983. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5984. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5985. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5986. $ts = strtotime($sr);
  5987. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5988. }
  5989. }
  5990. try {
  5991. $detailsQuery = Db::table('purchase_order_detail')
  5992. ->where('scydgy_id', 'in', array_keys($sids))
  5993. ->where('company_name', $companyName);
  5994. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5995. $details = $detailsQuery->order('id', 'asc')->select();
  5996. } catch (\Throwable $e) {
  5997. $details = [];
  5998. }
  5999. if (!is_array($details) || $details === []) {
  6000. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6001. try {
  6002. $detailsQuery = Db::table('purchase_order_detail')
  6003. ->where('scydgy_id', 'in', array_keys($sids))
  6004. ->where('company_name', $companyName);
  6005. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6006. $details = $detailsQuery->order('id', 'asc')->select();
  6007. } catch (\Throwable $e) {
  6008. $details = [];
  6009. }
  6010. }
  6011. if (!is_array($details) || $details === []) {
  6012. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6013. }
  6014. $detailLinks = [];
  6015. foreach ($details as $d) {
  6016. if (!is_array($d)) {
  6017. continue;
  6018. }
  6019. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6020. if ($detailId <= 0) {
  6021. continue;
  6022. }
  6023. $sid = (int)($d['scydgy_id'] ?? 0);
  6024. $gymc = '';
  6025. foreach ($mergeRows as $mr) {
  6026. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6027. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6028. break;
  6029. }
  6030. }
  6031. $detailLinks[] = [
  6032. 'detail_id' => $detailId,
  6033. 'cgymc' => $gymc,
  6034. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6035. ];
  6036. }
  6037. if ($detailLinks === []) {
  6038. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6039. }
  6040. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6041. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6042. $notifyBundle['email_log_scene'] = $emailLogScene;
  6043. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6044. $poIdLog = 0;
  6045. $pos = $bundle['pos'] ?? [];
  6046. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6047. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6048. }
  6049. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6050. if ($sendEmail) {
  6051. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6052. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6053. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6054. }
  6055. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6056. $mailConfig = $this->loadMailerConfig();
  6057. if (!$this->isProcuremenNotifyDryRun()) {
  6058. if (empty($mailConfig['host'])) {
  6059. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6060. }
  6061. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6062. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6063. }
  6064. }
  6065. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6066. }
  6067. if ($sendSms) {
  6068. $this->issueSendSupplierSms($notifyBundle);
  6069. }
  6070. }
  6071. /**
  6072. * @param array<int, array<string, mixed>> $quoteGroups
  6073. * @return array<int, array<string, mixed>>
  6074. */
  6075. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6076. {
  6077. $names = [];
  6078. if (is_string($companiesJson) && $companiesJson !== '') {
  6079. $decoded = json_decode($companiesJson, true);
  6080. if (is_array($decoded)) {
  6081. foreach ($decoded as $nm) {
  6082. $nm = trim((string)$nm);
  6083. if ($nm !== '') {
  6084. $names[] = $nm;
  6085. }
  6086. }
  6087. }
  6088. }
  6089. $names = array_values(array_unique($names));
  6090. if ($names === [] && $selectedCompany !== '') {
  6091. $names = [$selectedCompany];
  6092. }
  6093. if ($names === []) {
  6094. return $quoteGroups;
  6095. }
  6096. $targets = [];
  6097. foreach ($quoteGroups as $g) {
  6098. if (!is_array($g)) {
  6099. continue;
  6100. }
  6101. $cn = trim((string)($g['name'] ?? ''));
  6102. if ($cn !== '' && in_array($cn, $names, true)) {
  6103. $targets[] = $g;
  6104. }
  6105. }
  6106. return $targets;
  6107. }
  6108. /**
  6109. * @return array{pos:array, merge_rows:array, bundle:array}
  6110. */
  6111. protected function loadAuditResendBundle(string $scydgyId): array
  6112. {
  6113. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6114. $pos = $bundle['pos'];
  6115. $mergeRows = $bundle['merge_rows'];
  6116. if ($pos === [] || $mergeRows === []) {
  6117. $this->error('该订单不在待确认供应商状态');
  6118. }
  6119. $sysRqDb = '';
  6120. if (isset($pos[0]) && is_array($pos[0])) {
  6121. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6122. }
  6123. foreach ($pos as $i => $poRow) {
  6124. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6125. $pos[$i]['sys_rq'] = $sysRqDb;
  6126. }
  6127. }
  6128. $bundle['pos'] = $pos;
  6129. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6130. }
  6131. /**
  6132. * @param array<int, array<string, mixed>> $targets
  6133. */
  6134. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6135. {
  6136. if ($targets === []) {
  6137. $this->error('未找到可通知的供应商');
  6138. }
  6139. $notifyErrors = [];
  6140. try {
  6141. $this->notifyDryRunPreview = [];
  6142. foreach ($targets as $g) {
  6143. if (!is_array($g)) {
  6144. continue;
  6145. }
  6146. $cname = trim((string)($g['name'] ?? ''));
  6147. if ($cname === '') {
  6148. continue;
  6149. }
  6150. $chosen = [
  6151. 'name' => $cname,
  6152. 'company_name' => $cname,
  6153. 'email' => trim((string)($g['email'] ?? '')),
  6154. 'phone' => trim((string)($g['phone'] ?? '')),
  6155. 'username' => trim((string)($g['username'] ?? '')),
  6156. ];
  6157. try {
  6158. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6159. } catch (\Throwable $e) {
  6160. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6161. }
  6162. }
  6163. } catch (\Throwable $e) {
  6164. $this->error('通知发送失败:' . $e->getMessage());
  6165. }
  6166. if ($notifyErrors !== []) {
  6167. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6168. }
  6169. if ($this->isProcuremenNotifyDryRun()) {
  6170. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6171. 'notify_dry_run' => true,
  6172. 'notify_preview' => $this->notifyDryRunPreview,
  6173. ]);
  6174. }
  6175. $nameLabels = [];
  6176. foreach ($targets as $g) {
  6177. if (!is_array($g)) {
  6178. continue;
  6179. }
  6180. $n = trim((string)($g['name'] ?? ''));
  6181. if ($n !== '') {
  6182. $nameLabels[] = $n;
  6183. }
  6184. }
  6185. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6186. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6187. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6188. $seenLogSid = [];
  6189. foreach ($bundle['pos'] ?? [] as $poRow) {
  6190. if (!is_array($poRow)) {
  6191. continue;
  6192. }
  6193. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6194. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6195. continue;
  6196. }
  6197. $seenLogSid[$sid] = true;
  6198. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6199. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6200. }
  6201. if ($seenLogSid === []) {
  6202. foreach ($mergeRows as $mr) {
  6203. if (!is_array($mr)) {
  6204. continue;
  6205. }
  6206. $sid = $this->extractScydgyRowId($mr);
  6207. if ($this->isValidScydgyRowId($sid)) {
  6208. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6209. break;
  6210. }
  6211. }
  6212. }
  6213. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6214. }
  6215. /**
  6216. * 协助下发 — 发送短信(一家供应商)
  6217. *
  6218. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6219. */
  6220. protected function issueSendSupplierSms(array $bundle): void
  6221. {
  6222. $companyName = (string)($bundle['company_name'] ?? '');
  6223. $phone = (string)($bundle['phone'] ?? '');
  6224. $smsContent = (string)($bundle['sms_content'] ?? '');
  6225. $this->logIssueNotifyDebug('短信', [
  6226. 'company' => $companyName,
  6227. 'phone' => $phone,
  6228. 'sms_content' => $smsContent,
  6229. ]);
  6230. if ($this->isProcuremenNotifyDryRun()) {
  6231. $this->recordNotifyDryRunPreview([
  6232. 'scene' => 'issue_sms',
  6233. 'company_name' => $companyName,
  6234. 'phone' => $phone,
  6235. 'sms_content' => $smsContent,
  6236. ]);
  6237. return;
  6238. }
  6239. $this->smsbao($phone, $smsContent);
  6240. }
  6241. /**
  6242. * 协助下发 — 发送邮件(一家供应商)
  6243. *
  6244. * @param array<string, mixed> $bundle
  6245. * @param array<string, mixed> $mailConfig
  6246. */
  6247. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6248. {
  6249. $companyName = (string)($bundle['company_name'] ?? '');
  6250. $toEmail = (string)($bundle['email'] ?? '');
  6251. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6252. $mailBody = (string)($bundle['mail_body'] ?? '');
  6253. $this->logIssueNotifyDebug('邮件', [
  6254. 'company' => $companyName,
  6255. 'email' => $toEmail,
  6256. 'mail_subject' => $mailSubject,
  6257. 'mail_body' => $mailPlain,
  6258. ]);
  6259. if ($this->isProcuremenNotifyDryRun()) {
  6260. $this->recordNotifyDryRunPreview([
  6261. 'scene' => 'issue_email',
  6262. 'company_name' => $companyName,
  6263. 'email' => $toEmail,
  6264. 'mail_subject' => $mailSubject,
  6265. 'mail_body' => $mailPlain,
  6266. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6267. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6268. 'detail_links' => $bundle['detail_links'] ?? [],
  6269. ]);
  6270. return;
  6271. }
  6272. $mail = new PHPMailer(true);
  6273. $mail->isSMTP();
  6274. $mail->Host = $mailConfig['host'];
  6275. $mail->SMTPAuth = true;
  6276. $mail->Username = $mailConfig['addr'];
  6277. $mail->Password = $mailConfig['pass'];
  6278. $mail->SMTPSecure = $mailConfig['security'];
  6279. $mail->Port = $mailConfig['port'];
  6280. $mail->CharSet = $mailConfig['charset'];
  6281. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6282. $mail->addAddress($toEmail, $companyName);
  6283. $mail->isHTML(true);
  6284. $mail->Subject = $mailSubject;
  6285. $mail->Body = $mailBody;
  6286. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6287. $sendOk = true;
  6288. $failReason = '';
  6289. try {
  6290. $mail->send();
  6291. } catch (\Throwable $e) {
  6292. $sendOk = false;
  6293. $failReason = $e->getMessage();
  6294. $this->persistEmailSendLog([
  6295. 'from_email' => $fromEmail,
  6296. 'to_email' => $toEmail,
  6297. 'send_time' => date('Y-m-d H:i:s'),
  6298. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6299. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6300. 'company_name' => $companyName,
  6301. 'mail_subject' => $mailSubject,
  6302. 'status' => 0,
  6303. 'fail_reason' => $failReason,
  6304. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6305. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6306. ]);
  6307. throw $e;
  6308. }
  6309. $this->persistEmailSendLog([
  6310. 'from_email' => $fromEmail,
  6311. 'to_email' => $toEmail,
  6312. 'send_time' => date('Y-m-d H:i:s'),
  6313. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6314. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6315. 'company_name' => $companyName,
  6316. 'mail_subject' => $mailSubject,
  6317. 'status' => 1,
  6318. 'fail_reason' => '',
  6319. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6320. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6321. ]);
  6322. }
  6323. /**
  6324. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6325. *
  6326. * @param array<int, array<string, mixed>> $mergeRows
  6327. * @return array<string, mixed>
  6328. */
  6329. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6330. {
  6331. $head = $mergeRows[0] ?? [];
  6332. $isMerge = count($mergeRows) > 1;
  6333. return [
  6334. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6335. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6336. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6337. 'is_merge' => $isMerge,
  6338. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6339. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6340. 'deadline' => $sysRqNotify,
  6341. ];
  6342. }
  6343. /**
  6344. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6345. *
  6346. * @param array<string, mixed> $data
  6347. */
  6348. protected function logIssueNotifyDebug(string $type, array $data): void
  6349. {
  6350. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6351. return;
  6352. }
  6353. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6354. }
  6355. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6356. {
  6357. try {
  6358. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6359. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6360. return;
  6361. } catch (\Throwable $e) {
  6362. }
  6363. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6364. if (is_file($sqlFile)) {
  6365. $sql = file_get_contents($sqlFile);
  6366. if (is_string($sql) && $sql !== '') {
  6367. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6368. $stmt = trim($stmt);
  6369. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6370. continue;
  6371. }
  6372. try {
  6373. Db::execute($stmt);
  6374. } catch (\Throwable $ignore) {
  6375. }
  6376. }
  6377. }
  6378. }
  6379. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6380. }
  6381. /**
  6382. * @param array<string, mixed> $row
  6383. */
  6384. protected function persistEmailSendLog(array $row): void
  6385. {
  6386. try {
  6387. $this->ensurePurchaseEmailSendLogTableOnce();
  6388. } catch (\Throwable $e) {
  6389. return;
  6390. }
  6391. list($adminId, $adminName) = $this->GetUseName();
  6392. $cut = function ($s, $max) {
  6393. $s = (string)$s;
  6394. if (function_exists('mb_substr')) {
  6395. return mb_substr($s, 0, $max, 'UTF-8');
  6396. }
  6397. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6398. };
  6399. $data = [
  6400. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6401. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6402. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6403. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6404. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6405. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6406. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6407. 'status' => !empty($row['status']) ? 1 : 0,
  6408. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6409. 'admin_id' => (int)$adminId,
  6410. 'admin_name' => $cut($adminName, 64),
  6411. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6412. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6413. 'createtime' => date('Y-m-d H:i:s'),
  6414. ];
  6415. try {
  6416. Db::table('purchase_email_send_log')->insert($data);
  6417. } catch (\Throwable $e) {
  6418. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6419. }
  6420. }
  6421. protected function formatEmailLogSceneText(string $scene): string
  6422. {
  6423. $map = [
  6424. 'pick_issue' => '初选下发',
  6425. 'audit_resend' => '确认页重发',
  6426. ];
  6427. return $map[$scene] ?? $scene;
  6428. }
  6429. /**
  6430. * 邮件发送日志列表
  6431. */
  6432. public function emailLog()
  6433. {
  6434. $this->relationSearch = false;
  6435. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6436. $this->request->filter(['strip_tags', 'trim']);
  6437. $bakModel = $this->model;
  6438. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6439. if ($this->request->isAjax()) {
  6440. $this->ensurePurchaseEmailSendLogTableOnce();
  6441. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6442. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6443. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6444. $list = $this->model
  6445. ->where($where)
  6446. ->order($sortField, $orderDir)
  6447. ->paginate($limit);
  6448. $rows = [];
  6449. foreach ($list->items() as $item) {
  6450. $row = is_array($item) ? $item : $item->toArray();
  6451. $scene = trim((string)($row['scene'] ?? ''));
  6452. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6453. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6454. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6455. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6456. $rows[] = $row;
  6457. }
  6458. $this->model = $bakModel;
  6459. return json(['total' => $list->total(), 'rows' => $rows]);
  6460. }
  6461. $this->model = $bakModel;
  6462. return $this->view->fetch('procuremen/emaillog');
  6463. }
  6464. /**
  6465. * 协助下发弹窗(选多家供应商并通知)
  6466. */
  6467. public function pickReview()
  6468. {
  6469. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6470. $this->error(__('You have no permission'));
  6471. }
  6472. if ($this->request->isPost()) {
  6473. $this->error('请使用弹窗内「确认下发」提交');
  6474. }
  6475. $this->view->assign('pickMode', 1);
  6476. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6477. }
  6478. /**
  6479. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6480. */
  6481. public function add()
  6482. {
  6483. if ($this->request->isPost()) {
  6484. $params = $this->request->post('row/a');
  6485. if (!is_array($params)) {
  6486. $this->error(__('Parameter %s can not be empty', ''));
  6487. }
  6488. [, $adminName] = $this->GetUseName();
  6489. $params['cywyxm'] = $adminName;
  6490. try {
  6491. $sid = $this->saveManualPickOrder($params);
  6492. } catch (\InvalidArgumentException $e) {
  6493. $this->error($e->getMessage());
  6494. } catch (\Throwable $e) {
  6495. $this->error($e->getMessage());
  6496. }
  6497. $this->success('新增成功', '', [
  6498. 'scydgy_id' => $sid,
  6499. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6500. ]);
  6501. }
  6502. [, $adminName] = $this->GetUseName();
  6503. $this->view->assign('adminNickname', $adminName);
  6504. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6505. $this->view->assign('defaultCclbmmc', '营销中心');
  6506. return $this->view->fetch();
  6507. }
  6508. /**
  6509. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6510. */
  6511. public function rfqlist()
  6512. {
  6513. $this->relationSearch = false;
  6514. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6515. $this->request->filter(['strip_tags', 'trim']);
  6516. if ($this->request->isAjax()) {
  6517. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6518. $limit = max(10, min(500, (int)$limit));
  6519. $applyFilters = function ($query) use ($where) {
  6520. $query->where('scydgy_id', '<', 0);
  6521. $query->whereRaw(
  6522. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6523. );
  6524. if (!$this->auth->isSuperAdmin()) {
  6525. [, $adminName] = $this->GetUseName();
  6526. $query->where('cywyxm', $adminName);
  6527. }
  6528. if (!empty($where)) {
  6529. $query->where($where);
  6530. }
  6531. };
  6532. $countQuery = Db::table('purchase_order');
  6533. $applyFilters($countQuery);
  6534. $total = (int)$countQuery->count();
  6535. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6536. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6537. $listQuery = Db::table('purchase_order');
  6538. $applyFilters($listQuery);
  6539. $rows = $listQuery
  6540. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6541. ->order($sortField, $orderDir)
  6542. ->limit($offset, $limit)
  6543. ->select();
  6544. if (!is_array($rows)) {
  6545. $rows = [];
  6546. }
  6547. $out = [];
  6548. foreach ($rows as $r) {
  6549. if (!is_array($r)) {
  6550. continue;
  6551. }
  6552. $sid = (int)($r['scydgy_id'] ?? 0);
  6553. if ($sid >= 0) {
  6554. continue;
  6555. }
  6556. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6557. if ($createdText === '') {
  6558. $createdText = trim((string)($r['dStamp'] ?? ''));
  6559. }
  6560. $out[] = [
  6561. 'id' => (int)($r['id'] ?? 0),
  6562. 'scydgy_id' => $sid,
  6563. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6564. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6565. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6566. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6567. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6568. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6569. 'createtime' => $r['createtime'] ?? null,
  6570. 'createtime_text' => $createdText,
  6571. ];
  6572. }
  6573. return json(['total' => $total, 'rows' => $out]);
  6574. }
  6575. [, $adminName] = $this->GetUseName();
  6576. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6577. $this->view->assign('adminNickname', $adminName);
  6578. return $this->view->fetch('procuremen/rfqlist');
  6579. }
  6580. /**
  6581. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6582. */
  6583. public function rfqlistDetails()
  6584. {
  6585. return $this->details();
  6586. }
  6587. /**
  6588. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6589. */
  6590. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6591. {
  6592. if ($scydgyId >= 0) {
  6593. return;
  6594. }
  6595. try {
  6596. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6597. } catch (\Throwable $e) {
  6598. $po = null;
  6599. }
  6600. if (!is_array($po)) {
  6601. $this->error('订单不存在');
  6602. }
  6603. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6604. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6605. $this->error('订单不存在');
  6606. }
  6607. if ($this->auth->isSuperAdmin()) {
  6608. return;
  6609. }
  6610. [, $adminName] = $this->GetUseName();
  6611. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6612. if ($cywy !== '' && $cywy === $adminName) {
  6613. return;
  6614. }
  6615. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6616. try {
  6617. if ($this->auth->check($rule)) {
  6618. return;
  6619. }
  6620. } catch (\Throwable $e) {
  6621. }
  6622. }
  6623. $this->error('无权查看该订单');
  6624. }
  6625. /**
  6626. * 手工新增协助工序进度文案
  6627. */
  6628. protected function formatProcuremenRfqProgressText(array $row): string
  6629. {
  6630. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6631. return ProcuremenStatus::PO_COMPLETED;
  6632. }
  6633. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6634. return '待采购确认';
  6635. }
  6636. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6637. return '待确认供应商';
  6638. }
  6639. $sid = (int)($row['scydgy_id'] ?? 0);
  6640. if ($sid < 0) {
  6641. try {
  6642. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6643. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6644. $detCnt = (int)$detCntQuery->count();
  6645. if ($detCnt > 0) {
  6646. return '已下发待确认';
  6647. }
  6648. } catch (\Throwable $e) {
  6649. }
  6650. }
  6651. return '待协助下发';
  6652. }
  6653. /**
  6654. * 协助初选列表 — 批量软删除
  6655. */
  6656. public function pickDelete()
  6657. {
  6658. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6659. $this->error(__('Invalid parameters'));
  6660. }
  6661. if (!$this->procuremenCanPickDelete()) {
  6662. $this->error(__('You have no permission'));
  6663. }
  6664. $rowsRaw = $this->request->post('rows_json', '[]');
  6665. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6666. if (!is_array($rows) || $rows === []) {
  6667. $this->error('请至少勾选一条工序');
  6668. }
  6669. $done = 0;
  6670. Db::startTrans();
  6671. try {
  6672. foreach ($rows as $row) {
  6673. if (!is_array($row)) {
  6674. continue;
  6675. }
  6676. $this->softDeleteProcuremenPickRow($row);
  6677. $done++;
  6678. }
  6679. if ($done < 1) {
  6680. throw new \Exception('没有可删除的工序');
  6681. }
  6682. Db::commit();
  6683. } catch (\InvalidArgumentException $e) {
  6684. Db::rollback();
  6685. $this->error($e->getMessage());
  6686. } catch (\Throwable $e) {
  6687. Db::rollback();
  6688. $this->error($e->getMessage());
  6689. }
  6690. $this->pickHiddenScydgySetCache = null;
  6691. $this->success('已删除 ' . $done . ' 条工序');
  6692. }
  6693. /**
  6694. * 下发 — 手工新增工序(弹窗)
  6695. */
  6696. public function pickAdd()
  6697. {
  6698. if ($this->request->isPost()) {
  6699. $params = $this->request->post('row/a');
  6700. if (!is_array($params)) {
  6701. $this->error(__('Parameter %s can not be empty', ''));
  6702. }
  6703. try {
  6704. $sid = $this->saveManualPickOrder($params);
  6705. } catch (\InvalidArgumentException $e) {
  6706. $this->error($e->getMessage());
  6707. } catch (\Throwable $e) {
  6708. $this->error($e->getMessage());
  6709. }
  6710. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6711. }
  6712. return $this->view->fetch('procuremen/pick_add');
  6713. }
  6714. /**
  6715. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6716. */
  6717. public function pickSubmit()
  6718. {
  6719. if (!$this->request->isPost()) {
  6720. $this->error(__('Invalid parameters'));
  6721. }
  6722. // ---------- 接口订单数据 ----------
  6723. $rowJson = $this->request->post('row_json', '');
  6724. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6725. $companiesJson = $this->request->post('companies_json', '[]');
  6726. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6727. $companies = json_decode($companiesJson, true);
  6728. if (!is_array($companies)) {
  6729. $this->error('供应商数据无效');
  6730. }
  6731. $issueCompanies = $this->normalizePickCompanies($companies);
  6732. if ($issueCompanies === []) {
  6733. $this->error('请至少选择一家合作供应商');
  6734. }
  6735. $issueNameLabels = [];
  6736. foreach ($issueCompanies as $pc) {
  6737. $issueNameLabels[] = $pc['name'];
  6738. }
  6739. $issueNamesSummary = implode('、', $issueNameLabels);
  6740. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6741. if ($sysRq === '') {
  6742. $this->error('请选择招标截止日期');
  6743. }
  6744. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  6745. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  6746. (string)$this->request->post('delivery_deadline', ''),
  6747. true
  6748. );
  6749. $isMerge = count($mergeRows) > 1;
  6750. $ccydhLog = '';
  6751. foreach ($mergeRows as $row) {
  6752. if (!is_array($row)) {
  6753. continue;
  6754. }
  6755. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6756. if ($ccydhLog !== '') {
  6757. break;
  6758. }
  6759. }
  6760. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6761. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6762. $logMsg = '下发' . $orderPart . $procPart
  6763. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6764. $issueTime = date('Y-m-d H:i:s');
  6765. $logSidList = [];
  6766. foreach ($mergeRows as $row) {
  6767. if (!is_array($row)) {
  6768. continue;
  6769. }
  6770. $sid = $this->extractScydgyRowId($row);
  6771. if ($this->isValidScydgyRowId($sid)) {
  6772. $logSidList[$sid] = true;
  6773. }
  6774. }
  6775. $existingBySid = [];
  6776. if ($logSidList !== []) {
  6777. try {
  6778. $existingRows = Db::table('purchase_order')
  6779. ->where('scydgy_id', 'in', array_keys($logSidList))
  6780. ->select();
  6781. if (is_array($existingRows)) {
  6782. foreach ($existingRows as $poRow) {
  6783. if (!is_array($poRow)) {
  6784. continue;
  6785. }
  6786. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6787. if ($this->isValidScydgyRowId($sid)) {
  6788. $existingBySid[$sid] = $poRow;
  6789. }
  6790. }
  6791. }
  6792. } catch (\Throwable $e) {
  6793. $existingBySid = [];
  6794. }
  6795. }
  6796. Db::startTrans();
  6797. try {
  6798. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6799. foreach ($mergeRows as $row) {
  6800. if (!is_array($row)) {
  6801. continue;
  6802. }
  6803. $sid = $this->extractScydgyRowId($row);
  6804. $this->upsertPurchaseOrderFromRow(
  6805. $row,
  6806. $sysRqDb,
  6807. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6808. $issueTime,
  6809. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  6810. $deliveryDeadlineDb
  6811. );
  6812. }
  6813. foreach ($issueCompanies as $c) {
  6814. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6815. }
  6816. Db::commit();
  6817. } catch (\Throwable $e) {
  6818. Db::rollback();
  6819. $this->error($e->getMessage());
  6820. }
  6821. $poIdBySid = [];
  6822. if ($logSidList !== []) {
  6823. try {
  6824. $poIdBySid = Db::table('purchase_order')
  6825. ->where('scydgy_id', 'in', array_keys($logSidList))
  6826. ->column('id', 'scydgy_id');
  6827. } catch (\Throwable $e) {
  6828. $poIdBySid = [];
  6829. }
  6830. }
  6831. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6832. if ($logSidList !== []) {
  6833. list($adminId, $adminName) = $this->GetUseName();
  6834. $cut = function ($s, $max) {
  6835. if (function_exists('mb_substr')) {
  6836. return mb_substr($s, 0, $max, 'UTF-8');
  6837. }
  6838. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6839. };
  6840. $logRows = [];
  6841. $seenLogSid = [];
  6842. foreach ($mergeRows as $row) {
  6843. if (!is_array($row)) {
  6844. continue;
  6845. }
  6846. $ids = $this->extractScydgyRowId($row);
  6847. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6848. continue;
  6849. }
  6850. $seenLogSid[$ids] = true;
  6851. $poIdLog = null;
  6852. if (isset($poIdBySid[$ids])) {
  6853. $tid = (int)$poIdBySid[$ids];
  6854. $poIdLog = $tid > 0 ? $tid : null;
  6855. }
  6856. $logRows[] = [
  6857. 'scydgy_id' => $ids,
  6858. 'purchase_order_id' => $poIdLog,
  6859. 'admin_id' => $adminId,
  6860. 'admin_name' => $cut($adminName, 64),
  6861. 'action' => $cut('issue_submit', 64),
  6862. 'content' => $cut($logMsg, 1000),
  6863. 'createtime' => ProcuremenTime::nowDateTime(),
  6864. ];
  6865. }
  6866. if ($logRows !== []) {
  6867. try {
  6868. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6869. } catch (\Throwable $e) {
  6870. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6871. }
  6872. }
  6873. }
  6874. $notifyErrors = [];
  6875. $posNotify = [];
  6876. if ($logSidList !== []) {
  6877. try {
  6878. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6879. } catch (\Throwable $e) {
  6880. $posNotify = [];
  6881. }
  6882. }
  6883. if (!is_array($posNotify)) {
  6884. $posNotify = [];
  6885. }
  6886. foreach ($posNotify as $i => $prow) {
  6887. if (is_array($posNotify[$i])) {
  6888. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6889. }
  6890. }
  6891. $ccydhPick = '';
  6892. foreach ($mergeRows as $row) {
  6893. if (!is_array($row)) {
  6894. continue;
  6895. }
  6896. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6897. if ($ccydhPick !== '') {
  6898. break;
  6899. }
  6900. }
  6901. $notifyBundleBase = [
  6902. 'ccydh' => $ccydhPick,
  6903. 'pos' => $posNotify,
  6904. 'merge_rows' => $mergeRows,
  6905. ];
  6906. try {
  6907. $this->notifyDryRunPreview = [];
  6908. foreach ($issueCompanies as $c) {
  6909. if (!is_array($c)) {
  6910. continue;
  6911. }
  6912. $cname = trim((string)($c['name'] ?? ''));
  6913. if ($cname === '') {
  6914. continue;
  6915. }
  6916. try {
  6917. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6918. } catch (\Throwable $e) {
  6919. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6920. }
  6921. }
  6922. } catch (\Throwable $e) {
  6923. $this->error('通知发送失败:' . $e->getMessage());
  6924. }
  6925. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6926. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6927. }
  6928. if ($this->isProcuremenNotifyDryRun()) {
  6929. $this->success('【演练模式】已保存并生成通知预览', '', [
  6930. 'notify_dry_run' => true,
  6931. 'notify_preview' => $this->notifyDryRunPreview,
  6932. ]);
  6933. }
  6934. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6935. }
  6936. /**
  6937. * 确认供应商弹窗
  6938. */
  6939. public function auditIssue()
  6940. {
  6941. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6942. if (is_array($ids)) {
  6943. $ids = isset($ids[0]) ? $ids[0] : '';
  6944. }
  6945. $ids = trim((string)$ids);
  6946. if ($ids === '') {
  6947. $this->error(__('Invalid parameters'));
  6948. }
  6949. if ($this->request->isPost()) {
  6950. $this->error('请使用弹窗内「确认」提交');
  6951. }
  6952. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6953. $pos = $bundle['pos'];
  6954. if ($pos === []) {
  6955. $this->error('该订单不在待确认供应商状态');
  6956. }
  6957. $po = $pos[0];
  6958. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6959. if ($quoteGroups === []) {
  6960. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6961. }
  6962. $pickedName = '';
  6963. foreach ($pos as $poRow) {
  6964. if (!is_array($poRow)) {
  6965. continue;
  6966. }
  6967. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6968. if ($pn !== '') {
  6969. $pickedName = $pn;
  6970. break;
  6971. }
  6972. }
  6973. $this->view->assign('po', $po);
  6974. $this->view->assign('scydgyId', $ids);
  6975. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6976. $mergeRows = $bundle['merge_rows'];
  6977. $this->view->assign('processRows', $mergeRows);
  6978. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6979. $this->view->assign('processCount', count($mergeRows));
  6980. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6981. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6982. $this->view->assign('pickedCompanyName', $pickedName);
  6983. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  6984. if ($sysRqForView === '') {
  6985. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6986. }
  6987. $this->view->assign('sysRq', $sysRqForView);
  6988. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  6989. if ($deliveryDeadlineForView === '') {
  6990. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  6991. }
  6992. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  6993. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6994. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  6995. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  6996. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  6997. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  6998. return $this->view->fetch('procuremen/audit_issue');
  6999. }
  7000. /**
  7001. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7002. *
  7003. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7004. */
  7005. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7006. {
  7007. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7008. }
  7009. /**
  7010. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7011. *
  7012. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7013. */
  7014. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7015. {
  7016. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7017. return false;
  7018. }
  7019. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7020. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7021. return true;
  7022. }
  7023. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7024. }
  7025. /**
  7026. * 确认页 — 补加供应商弹窗
  7027. */
  7028. public function auditAppend()
  7029. {
  7030. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7031. $this->error(__('You have no permission'));
  7032. }
  7033. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7034. if (is_array($ids)) {
  7035. $ids = isset($ids[0]) ? $ids[0] : '';
  7036. }
  7037. $ids = trim((string)$ids);
  7038. if ($ids === '') {
  7039. $this->error(__('Invalid parameters'));
  7040. }
  7041. if ($this->request->isPost()) {
  7042. $this->error('请使用弹窗内「确认」提交');
  7043. }
  7044. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7045. if (($bundle['pos'] ?? []) === []) {
  7046. $this->error('该订单不在待确认供应商状态');
  7047. }
  7048. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7049. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7050. $this->error('已开标验证,不能再补加供应商');
  7051. }
  7052. $this->error('已经超过了招标截止日期,不可操作');
  7053. }
  7054. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7055. $existingNames = [];
  7056. foreach ($quoteGroups as $g) {
  7057. if (!is_array($g)) {
  7058. continue;
  7059. }
  7060. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7061. if ($n !== '') {
  7062. $existingNames[$n] = true;
  7063. }
  7064. }
  7065. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7066. $mergeRows = $bundle['merge_rows'] ?? [];
  7067. $this->view->assign('scydgyId', $ids);
  7068. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7069. $this->view->assign('po', $po);
  7070. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7071. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7072. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7073. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7074. if ($sysRqForView === '') {
  7075. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7076. }
  7077. $this->view->assign('sysRq', $sysRqForView);
  7078. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7079. if ($deliveryDeadlineForView === '') {
  7080. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7081. }
  7082. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7083. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7084. }
  7085. /**
  7086. * 确认页 — 补加供应商提交
  7087. */
  7088. public function auditAppendSubmit()
  7089. {
  7090. if (!$this->request->isPost()) {
  7091. $this->error(__('Invalid parameters'));
  7092. }
  7093. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7094. $this->error(__('You have no permission'));
  7095. }
  7096. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7097. if ($ids === '') {
  7098. $this->error(__('Invalid parameters'));
  7099. }
  7100. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7101. if (($bundle['pos'] ?? []) === []) {
  7102. $this->error('该订单不在待确认供应商状态');
  7103. }
  7104. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7105. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7106. $this->error('已开标验证,不能再补加供应商');
  7107. }
  7108. $this->error('已经超过了招标截止日期,不可操作');
  7109. }
  7110. $companiesJson = $this->request->post('companies_json', '[]');
  7111. $companies = json_decode((string)$companiesJson, true);
  7112. if (!is_array($companies)) {
  7113. $this->error('供应商数据无效');
  7114. }
  7115. $issueCompanies = $this->normalizePickCompanies($companies);
  7116. if ($issueCompanies === []) {
  7117. $this->error('请至少选择一家合作供应商');
  7118. }
  7119. $mergeRows = $bundle['merge_rows'] ?? [];
  7120. if (!is_array($mergeRows) || $mergeRows === []) {
  7121. $this->error('未找到工序行,无法补加');
  7122. }
  7123. $existingNames = [];
  7124. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7125. if (!is_array($g)) {
  7126. continue;
  7127. }
  7128. $n = trim((string)($g['company_name'] ?? ''));
  7129. if ($n !== '') {
  7130. $existingNames[$n] = true;
  7131. }
  7132. }
  7133. $toAdd = [];
  7134. foreach ($issueCompanies as $c) {
  7135. if (!is_array($c)) {
  7136. continue;
  7137. }
  7138. $n = trim((string)($c['name'] ?? ''));
  7139. if ($n === '' || isset($existingNames[$n])) {
  7140. continue;
  7141. }
  7142. $toAdd[] = $c;
  7143. }
  7144. if ($toAdd === []) {
  7145. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7146. }
  7147. $addedNames = [];
  7148. Db::startTrans();
  7149. try {
  7150. foreach ($toAdd as $c) {
  7151. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7152. $addedNames[] = trim((string)($c['name'] ?? ''));
  7153. }
  7154. Db::commit();
  7155. } catch (\Throwable $e) {
  7156. Db::rollback();
  7157. $this->error($e->getMessage());
  7158. }
  7159. $notifyErrors = [];
  7160. $notifyBundleBase = [
  7161. 'ccydh' => $bundle['ccydh'] ?? '',
  7162. 'pos' => $bundle['pos'] ?? [],
  7163. 'merge_rows' => $mergeRows,
  7164. ];
  7165. foreach ($toAdd as $c) {
  7166. if (!is_array($c)) {
  7167. continue;
  7168. }
  7169. $cname = trim((string)($c['name'] ?? ''));
  7170. if ($cname === '') {
  7171. continue;
  7172. }
  7173. try {
  7174. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7175. } catch (\Throwable $e) {
  7176. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7177. }
  7178. }
  7179. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7180. $seenLogSid = [];
  7181. foreach ($bundle['pos'] ?? [] as $poRow) {
  7182. if (!is_array($poRow)) {
  7183. continue;
  7184. }
  7185. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7186. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7187. continue;
  7188. }
  7189. $seenLogSid[$sid] = true;
  7190. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7191. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7192. }
  7193. if ($seenLogSid === []) {
  7194. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7195. if ($this->isValidScydgyRowId($logSid)) {
  7196. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7197. }
  7198. }
  7199. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7200. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7201. }
  7202. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7203. }
  7204. /**
  7205. * 开标双重验证 — 可选验证人列表
  7206. */
  7207. public function bidOpenUsers()
  7208. {
  7209. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7210. $this->error('无权限');
  7211. }
  7212. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7213. if ($scydgyId !== '') {
  7214. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7215. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7216. $this->success('已完成开标验证', null, [
  7217. 'verified' => 1,
  7218. 'users' => [],
  7219. ]);
  7220. }
  7221. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7222. }
  7223. $this->success('', null, [
  7224. 'verified' => 0,
  7225. 'users' => $this->listBidOpenVerifierCandidates(),
  7226. ]);
  7227. }
  7228. /**
  7229. * 开标双重验证 — 向指定管理员发送短信验证码
  7230. */
  7231. public function bidOpenSendCode()
  7232. {
  7233. if (!$this->request->isPost()) {
  7234. $this->error(__('Invalid parameters'));
  7235. }
  7236. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7237. $this->error('无权限');
  7238. }
  7239. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7240. $adminId = (int)$this->request->post('admin_id', 0);
  7241. if ($scydgyId === '' || $adminId <= 0) {
  7242. $this->error('参数无效');
  7243. }
  7244. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7245. if ($bundle['pos'] === []) {
  7246. $this->error('该订单不在待确认供应商状态');
  7247. }
  7248. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7249. $this->success('已完成开标验证,无需重复发送');
  7250. }
  7251. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7252. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7253. if ($ccydh === '') {
  7254. $this->error('订单号无效');
  7255. }
  7256. $admin = $this->loadBidOpenAdminUser($adminId);
  7257. if ($admin === null) {
  7258. $this->error('验证人无效或未绑定手机号');
  7259. }
  7260. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7261. $cd = max(30, min(120, $cd));
  7262. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7263. $this->error('发送过于频繁,请稍后再试');
  7264. }
  7265. $code = (string)random_int(100000, 999999);
  7266. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7267. $ttl = max(60, min(600, $ttl));
  7268. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7269. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7270. try {
  7271. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7272. } catch (\Throwable $e) {
  7273. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7274. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7275. $this->error($e->getMessage());
  7276. }
  7277. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7278. }
  7279. /**
  7280. * 开标双重验证 — 两人验证码校验并记录
  7281. */
  7282. public function bidOpenVerify()
  7283. {
  7284. if (!$this->request->isPost()) {
  7285. $this->error(__('Invalid parameters'));
  7286. }
  7287. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7288. $this->error('无权限');
  7289. }
  7290. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7291. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7292. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7293. $code1 = trim((string)$this->request->post('code1', ''));
  7294. $code2 = trim((string)$this->request->post('code2', ''));
  7295. if ($scydgyId === '') {
  7296. $this->error('参数无效');
  7297. }
  7298. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7299. $this->error('请选择两位验证人');
  7300. }
  7301. if ($verifier1Id === $verifier2Id) {
  7302. $this->error('两位验证人不能相同');
  7303. }
  7304. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7305. $this->error('请输入6位短信验证码');
  7306. }
  7307. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7308. if ($bundle['pos'] === []) {
  7309. $this->error('该订单不在待确认供应商状态');
  7310. }
  7311. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7312. if ($ccydh === '') {
  7313. $this->error('订单号无效');
  7314. }
  7315. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7316. $this->success('已完成开标验证');
  7317. }
  7318. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7319. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7320. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7321. if ($verifier1 === null || $verifier2 === null) {
  7322. $this->error('验证人无效或未绑定手机号');
  7323. }
  7324. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7325. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7326. }
  7327. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7328. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7329. }
  7330. try {
  7331. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7332. } catch (\Throwable $e) {
  7333. $this->error($e->getMessage());
  7334. }
  7335. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7336. }
  7337. /**
  7338. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7339. */
  7340. public function auditSubmit()
  7341. {
  7342. if (!$this->request->isPost()) {
  7343. $this->error(__('Invalid parameters'));
  7344. }
  7345. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7346. if ($scydgyId === '') {
  7347. $this->error('参数无效');
  7348. }
  7349. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7350. $pos = $bundle['pos'];
  7351. $mergeRows = $bundle['merge_rows'];
  7352. if ($pos === [] || $mergeRows === []) {
  7353. $this->error('该订单不在待确认供应商状态');
  7354. }
  7355. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7356. if ($quoteGroups === []) {
  7357. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7358. }
  7359. $companyName = trim((string)$this->request->post('selected_company', ''));
  7360. if ($companyName === '') {
  7361. $this->error('请选择一家供应商');
  7362. }
  7363. $matched = null;
  7364. foreach ($quoteGroups as $g) {
  7365. if (!is_array($g)) {
  7366. continue;
  7367. }
  7368. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7369. $matched = $g;
  7370. break;
  7371. }
  7372. }
  7373. if ($matched === null) {
  7374. $this->error('所选供应商不在本单报价列表中');
  7375. }
  7376. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7377. if ($sysRqDb === '') {
  7378. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  7379. } else {
  7380. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  7381. }
  7382. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7383. $this->error('请先完成开标双重验证后再确认供应商');
  7384. }
  7385. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7386. $procCnt = count($mergeRows);
  7387. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7388. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7389. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  7390. Db::startTrans();
  7391. try {
  7392. foreach ($pos as $poRow) {
  7393. if (!is_array($poRow)) {
  7394. continue;
  7395. }
  7396. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7397. if (!$this->isValidScydgyRowId($sid)) {
  7398. continue;
  7399. }
  7400. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7401. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7402. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7403. 'pick_company_name' => $companyName,
  7404. 'sys_rq' => $sysRqDb,
  7405. ]);
  7406. }
  7407. Db::commit();
  7408. } catch (\Throwable $e) {
  7409. Db::rollback();
  7410. $this->error($e->getMessage());
  7411. }
  7412. foreach ($pos as $poRow) {
  7413. if (!is_array($poRow)) {
  7414. continue;
  7415. }
  7416. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7417. if (!$this->isValidScydgyRowId($sid)) {
  7418. continue;
  7419. }
  7420. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7421. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7422. }
  7423. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7424. }
  7425. /**
  7426. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7427. */
  7428. public function auditResendSms()
  7429. {
  7430. if (!$this->request->isPost()) {
  7431. $this->error(__('Invalid parameters'));
  7432. }
  7433. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7434. if ($scydgyId === '') {
  7435. $this->error('参数无效');
  7436. }
  7437. $loaded = $this->loadAuditResendBundle($scydgyId);
  7438. $mergeRows = $loaded['merge_rows'];
  7439. $bundle = $loaded['bundle'];
  7440. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7441. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7442. if ($quoteGroups === []) {
  7443. $this->error('暂无可通知的供应商');
  7444. }
  7445. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7446. $companiesJson = (string)$this->request->post('companies_json', '');
  7447. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7448. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7449. }
  7450. /**
  7451. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7452. */
  7453. public function auditResendEmail()
  7454. {
  7455. if (!$this->request->isPost()) {
  7456. $this->error(__('Invalid parameters'));
  7457. }
  7458. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7459. if ($scydgyId === '') {
  7460. $this->error('参数无效');
  7461. }
  7462. $loaded = $this->loadAuditResendBundle($scydgyId);
  7463. $mergeRows = $loaded['merge_rows'];
  7464. $bundle = $loaded['bundle'];
  7465. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7466. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7467. if ($quoteGroups === []) {
  7468. $this->error('暂无可通知的供应商');
  7469. }
  7470. $companiesJson = (string)$this->request->post('companies_json', '');
  7471. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7472. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7473. if ($companiesJson === '' && $selectedCompany === '') {
  7474. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7475. }
  7476. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7477. }
  7478. /**
  7479. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7480. *
  7481. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7482. * @return array<int, true> 已处理的 scydgy_id 集合
  7483. */
  7484. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7485. {
  7486. $pos = $bundle['pos'] ?? [];
  7487. if (!is_array($pos) || $pos === []) {
  7488. return [];
  7489. }
  7490. $sids = [];
  7491. foreach ($pos as $poRow) {
  7492. if (!is_array($poRow)) {
  7493. continue;
  7494. }
  7495. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7496. if ($this->isValidScydgyRowId($sid)) {
  7497. $sids[$sid] = true;
  7498. }
  7499. }
  7500. if ($sids === []) {
  7501. return [];
  7502. }
  7503. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7504. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7505. $suffix = trim((string)$logSuffix, ',, ');
  7506. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7507. $logMsg .= ':从历史存证退回协助初选';
  7508. } else {
  7509. $logMsg .= ':退回协助初选';
  7510. }
  7511. Db::table('purchase_order')
  7512. ->where('scydgy_id', 'in', array_keys($sids))
  7513. ->update([
  7514. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7515. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7516. 'pick_company_name' => '',
  7517. 'pick_time' => null,
  7518. 'sys_rq' => null,
  7519. 'mod_rq' => null,
  7520. ]);
  7521. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7522. foreach (array_keys($sids) as $sid) {
  7523. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7524. }
  7525. return $sids;
  7526. }
  7527. /**
  7528. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7529. *
  7530. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7531. */
  7532. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7533. {
  7534. $scydgyId = trim($scydgyId);
  7535. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7536. if ($scydgyId === '') {
  7537. return $empty;
  7538. }
  7539. try {
  7540. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7541. } catch (\Throwable $e) {
  7542. $anchor = null;
  7543. }
  7544. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7545. return $empty;
  7546. }
  7547. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7548. if ($ccydh === '') {
  7549. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7550. }
  7551. try {
  7552. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7553. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7554. $pos = $query->order('scydgy_id', 'asc')->select();
  7555. } catch (\Throwable $e) {
  7556. $pos = [$anchor];
  7557. }
  7558. if (!is_array($pos) || $pos === []) {
  7559. $pos = [$anchor];
  7560. }
  7561. return [
  7562. 'ccydh' => $ccydh,
  7563. 'pos' => $pos,
  7564. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7565. ];
  7566. }
  7567. protected function purchaseOrderRowIsCompleted(array $po): bool
  7568. {
  7569. $st = $po['status'] ?? null;
  7570. if ($st === 1 || $st === '1') {
  7571. return true;
  7572. }
  7573. if (is_string($st) && trim($st) === '1') {
  7574. return true;
  7575. }
  7576. return is_numeric($st) && (int)$st === 1;
  7577. }
  7578. /**
  7579. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7580. */
  7581. public function auditAbandon()
  7582. {
  7583. if (!$this->request->isPost()) {
  7584. $this->error(__('Invalid parameters'));
  7585. }
  7586. $anchorIds = [];
  7587. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7588. if ($batchRaw !== '') {
  7589. $decoded = json_decode($batchRaw, true);
  7590. if (is_array($decoded)) {
  7591. foreach ($decoded as $id) {
  7592. $s = trim((string)$id);
  7593. if ($s !== '') {
  7594. $anchorIds[] = $s;
  7595. }
  7596. }
  7597. }
  7598. }
  7599. if ($anchorIds === []) {
  7600. $single = trim((string)$this->request->post('scydgy_id', ''));
  7601. if ($single !== '') {
  7602. $anchorIds[] = $single;
  7603. }
  7604. }
  7605. if ($anchorIds === []) {
  7606. $this->error('请至少选择一条订单');
  7607. }
  7608. $processedCcydh = [];
  7609. $doneOrders = 0;
  7610. $allSids = [];
  7611. Db::startTrans();
  7612. try {
  7613. foreach ($anchorIds as $anchorId) {
  7614. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7615. if (($bundle['pos'] ?? []) === []) {
  7616. continue;
  7617. }
  7618. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7619. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7620. if (isset($processedCcydh[$dedupeKey])) {
  7621. continue;
  7622. }
  7623. $processedCcydh[$dedupeKey] = true;
  7624. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7625. if ($sids === []) {
  7626. continue;
  7627. }
  7628. $doneOrders++;
  7629. foreach (array_keys($sids) as $sid) {
  7630. $allSids[(int)$sid] = true;
  7631. }
  7632. }
  7633. if ($doneOrders < 1) {
  7634. throw new \Exception('所选订单均不在待确认供应商状态');
  7635. }
  7636. Db::commit();
  7637. } catch (\Throwable $e) {
  7638. Db::rollback();
  7639. $this->error($e->getMessage());
  7640. }
  7641. $this->pickHiddenScydgySetCache = null;
  7642. $msg = $doneOrders > 1
  7643. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7644. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7645. $this->success($msg);
  7646. }
  7647. /**
  7648. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7649. */
  7650. public function archiveAbandon()
  7651. {
  7652. if (!$this->request->isPost()) {
  7653. $this->error(__('Invalid parameters'));
  7654. }
  7655. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7656. $this->error(__('You have no permission'));
  7657. }
  7658. $anchorIds = [];
  7659. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7660. if ($batchRaw !== '') {
  7661. $decoded = json_decode($batchRaw, true);
  7662. if (is_array($decoded)) {
  7663. foreach ($decoded as $id) {
  7664. $s = trim((string)$id);
  7665. if ($s !== '') {
  7666. $anchorIds[] = $s;
  7667. }
  7668. }
  7669. }
  7670. }
  7671. if ($anchorIds === []) {
  7672. $single = trim((string)$this->request->post('scydgy_id', ''));
  7673. if ($single !== '') {
  7674. $anchorIds[] = $single;
  7675. }
  7676. }
  7677. if ($anchorIds === []) {
  7678. $this->error('请至少选择一条订单');
  7679. }
  7680. $processedCcydh = [];
  7681. $doneOrders = 0;
  7682. Db::startTrans();
  7683. try {
  7684. foreach ($anchorIds as $anchorId) {
  7685. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7686. if (($bundle['pos'] ?? []) === []) {
  7687. continue;
  7688. }
  7689. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7690. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7691. if (isset($processedCcydh[$dedupeKey])) {
  7692. continue;
  7693. }
  7694. $processedCcydh[$dedupeKey] = true;
  7695. $sids = $this->abandonOrderBundleToPick(
  7696. $bundle,
  7697. 'archive_abandon',
  7698. ',从历史存证退回协助初选'
  7699. );
  7700. if ($sids === []) {
  7701. continue;
  7702. }
  7703. $doneOrders++;
  7704. }
  7705. if ($doneOrders < 1) {
  7706. throw new \Exception('所选订单均不是已完结状态');
  7707. }
  7708. Db::commit();
  7709. } catch (\Throwable $e) {
  7710. Db::rollback();
  7711. $this->error($e->getMessage());
  7712. }
  7713. $this->pickHiddenScydgySetCache = null;
  7714. $msg = $doneOrders > 1
  7715. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7716. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7717. $this->success($msg);
  7718. }
  7719. /**
  7720. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7721. */
  7722. public function purchaseApprovalReject()
  7723. {
  7724. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7725. $this->error(__('Invalid parameters'));
  7726. }
  7727. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7728. $this->error(__('You have no permission'));
  7729. }
  7730. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7731. $decoded = json_decode($batchRaw, true);
  7732. if (!is_array($decoded) || $decoded === []) {
  7733. $this->error('提交数据无效');
  7734. }
  7735. $done = 0;
  7736. Db::startTrans();
  7737. try {
  7738. foreach ($decoded as $item) {
  7739. if (!is_array($item)) {
  7740. continue;
  7741. }
  7742. $sid = (int)($item['scydgy_id'] ?? 0);
  7743. if (!$this->isValidScydgyRowId($sid)) {
  7744. continue;
  7745. }
  7746. $this->runPurchaseApprovalRejectForSid($sid);
  7747. $done++;
  7748. }
  7749. if ($done < 1) {
  7750. throw new \Exception('所选订单均不在待审批状态');
  7751. }
  7752. Db::commit();
  7753. } catch (\Throwable $e) {
  7754. Db::rollback();
  7755. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7756. }
  7757. $this->pickHiddenScydgySetCache = null;
  7758. $this->success('已驳回并退回「协助审批下发」');
  7759. }
  7760. /**
  7761. * @throws \Exception
  7762. */
  7763. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7764. {
  7765. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7766. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7767. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7768. $allIds = $this->purchaseOrderDetail($sid);
  7769. if ($allIds === []) {
  7770. throw new \Exception('未找到下发明细');
  7771. }
  7772. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7773. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7774. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7775. 'pick_company_name' => '',
  7776. ]);
  7777. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7778. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7779. $poId = 0;
  7780. try {
  7781. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7782. if (is_array($po)) {
  7783. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7784. }
  7785. } catch (\Throwable $e) {
  7786. }
  7787. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7788. }
  7789. /**
  7790. * 审核弹窗(旧入口,POST 已关闭)
  7791. */
  7792. public function review()
  7793. {
  7794. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7795. $this->error(__('You have no permission'));
  7796. }
  7797. if ($this->request->isPost()) {
  7798. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7799. }
  7800. $this->view->assign('pickMode', 0);
  7801. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  7802. }
  7803. /**
  7804. * 审核弹窗获取公司列表
  7805. */
  7806. public function reviewCompanies()
  7807. {
  7808. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  7809. $this->error(__('You have no permission'));
  7810. }
  7811. if (!$this->request->isAjax()) {
  7812. $this->error(__('Invalid parameters'));
  7813. }
  7814. $list = [];
  7815. try {
  7816. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7817. $rows = Db::table('customer')
  7818. ->where(function ($q) {
  7819. $q->where('status', 1)
  7820. ->whereOr('status', '1')
  7821. ->whereOr('status', '')
  7822. ->whereNull('status');
  7823. })
  7824. ->order('id', 'desc')
  7825. ->select();
  7826. } catch (\Throwable $e) {
  7827. $this->success('', '', []);
  7828. return;
  7829. }
  7830. if (!is_array($rows)) {
  7831. $this->success('', '', []);
  7832. return;
  7833. }
  7834. $detailColCandidates = [
  7835. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7836. 'company_detail', 'company_desc', 'address',
  7837. ];
  7838. foreach ($rows as $row) {
  7839. if (!is_array($row)) {
  7840. continue;
  7841. }
  7842. $norm = [];
  7843. foreach ($row as $k => $v) {
  7844. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7845. }
  7846. $row = $norm;
  7847. $st = $row['status'] ?? '';
  7848. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7849. continue;
  7850. }
  7851. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7852. if ($payload === null) {
  7853. continue;
  7854. }
  7855. $detail = '';
  7856. foreach ($detailColCandidates as $dk) {
  7857. if (!isset($row[$dk])) {
  7858. continue;
  7859. }
  7860. $dv = trim((string)$row[$dk]);
  7861. if ($dv !== '') {
  7862. $detail = $dv;
  7863. break;
  7864. }
  7865. }
  7866. $payload['detail'] = $detail;
  7867. $list[] = $this->maskSupplierContactFields($payload);
  7868. }
  7869. $this->success('', '', $list);
  7870. }
  7871. /**
  7872. * 采购确认-下发明细弹窗:
  7873. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7874. */
  7875. public function outward_detail()
  7876. {
  7877. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7878. if (is_array($ids)) {
  7879. $ids = isset($ids[0]) ? $ids[0] : '';
  7880. }
  7881. $ids = trim((string)$ids);
  7882. if ($ids === '') {
  7883. $this->error(__('Invalid parameters'));
  7884. }
  7885. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7886. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7887. $wffTab = 'all';
  7888. }
  7889. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7890. $purchaseOrderId = 0;
  7891. $po = null;
  7892. try {
  7893. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7894. if (is_array($po)) {
  7895. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7896. }
  7897. } catch (\Throwable $e) {
  7898. $purchaseOrderId = 0;
  7899. $po = null;
  7900. }
  7901. if (!$isPurchaseConfirm && is_array($po)) {
  7902. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7903. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7904. $isPurchaseConfirm = true;
  7905. }
  7906. }
  7907. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7908. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7909. $confirmProcessCount = 1;
  7910. $confirmPickGroups = [];
  7911. $processDisplayRows = [];
  7912. $allDetailsBySid = [];
  7913. $requiredSidList = [];
  7914. $sidList = [$ids];
  7915. if ($isPurchaseConfirm) {
  7916. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7917. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7918. if ($mergeRows !== []) {
  7919. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7920. }
  7921. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7922. if ($confirmBundle['pos'] !== []) {
  7923. $sidList = [];
  7924. foreach ($confirmBundle['pos'] as $poRow) {
  7925. if (!is_array($poRow)) {
  7926. continue;
  7927. }
  7928. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7929. if (!$this->isValidScydgyRowId($sid)) {
  7930. continue;
  7931. }
  7932. $sidList[] = (string)$sid;
  7933. $requiredSidList[] = $sid;
  7934. }
  7935. }
  7936. if ($sidList === []) {
  7937. $sidList = [$ids];
  7938. $requiredSidList = [(int)$ids];
  7939. }
  7940. $confirmProcessCount = max(1, count($requiredSidList));
  7941. if (is_array($po) && $purchaseOrderId <= 0) {
  7942. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7943. }
  7944. }
  7945. $rows = [];
  7946. try {
  7947. if (count($sidList) === 1) {
  7948. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7949. } else {
  7950. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7951. }
  7952. } catch (\Throwable $e) {
  7953. $rows = [];
  7954. }
  7955. if ($isPurchaseConfirm) {
  7956. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7957. }
  7958. foreach ($rows as &$r) {
  7959. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7960. $r['id'] = $r['ID'];
  7961. }
  7962. if (isset($r['createtime'])) {
  7963. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7964. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7965. } else {
  7966. $r['createtime_text'] = (string)$r['createtime'];
  7967. }
  7968. } else {
  7969. $r['createtime_text'] = '';
  7970. }
  7971. if (is_array($r)) {
  7972. $r = $this->maskSupplierContactFields($r);
  7973. }
  7974. }
  7975. unset($r);
  7976. $pickedCompanyName = '';
  7977. if ($isPurchaseConfirm) {
  7978. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7979. if (!is_array($poRow)) {
  7980. continue;
  7981. }
  7982. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7983. if ($pn !== '') {
  7984. $pickedCompanyName = $pn;
  7985. break;
  7986. }
  7987. }
  7988. }
  7989. $this->view->assign('rows', $rows ?: []);
  7990. $this->view->assign('rowCount', count($rows ?: []));
  7991. $this->view->assign('scydgyId', $ids);
  7992. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7993. $this->view->assign('headTitle', $headTitle);
  7994. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7995. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7996. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7997. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7998. $this->view->assign('processDisplayRows', $processDisplayRows);
  7999. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8000. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8001. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8002. $sysRqDisplay = '—';
  8003. if ($isPurchaseConfirm) {
  8004. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8005. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8006. );
  8007. }
  8008. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8009. $this->view->assign('sysRq', $isPurchaseConfirm
  8010. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8011. : '');
  8012. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8013. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8014. : '');
  8015. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8016. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8017. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8018. if ($isPurchaseConfirm) {
  8019. return $this->view->fetch();
  8020. }
  8021. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8022. $this->view->engine->layout(false);
  8023. try {
  8024. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8025. $this->view->assign('dialogBody', $bodyHtml);
  8026. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8027. } finally {
  8028. if ($restoreLayout) {
  8029. $this->view->engine->layout($restoreLayout);
  8030. }
  8031. }
  8032. }
  8033. /**
  8034. * 月度导出记录表(不存在时自动创建)
  8035. */
  8036. protected function ensurePurchaseMonthExportLogTable(): void
  8037. {
  8038. try {
  8039. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8040. } catch (\Throwable $e) {
  8041. Db::execute(
  8042. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8043. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8044. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8045. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8046. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8047. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8048. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8049. `createtime` int(10) unsigned DEFAULT NULL,
  8050. PRIMARY KEY (`id`),
  8051. KEY `idx_ym` (`ym`),
  8052. KEY `idx_ct` (`createtime`)
  8053. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8054. );
  8055. }
  8056. }
  8057. /**
  8058. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8059. *
  8060. * @param array<int, mixed> $dbRows
  8061. * @return array<int, array<string, mixed>>
  8062. */
  8063. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8064. {
  8065. $keyword = trim((string)$this->request->get('search', ''));
  8066. if ($keyword === '') {
  8067. $keyword = trim((string)$this->request->request('search', ''));
  8068. }
  8069. $filter = $this->request->get('filter', '');
  8070. $op = $this->request->get('op', '');
  8071. if (is_string($filter) && $filter !== '') {
  8072. $filterArr = (array)json_decode($filter, true);
  8073. } else {
  8074. $filterArr = is_array($filter) ? $filter : [];
  8075. }
  8076. if (is_string($op) && $op !== '') {
  8077. $opArr = (array)json_decode($op, true);
  8078. } else {
  8079. $opArr = is_array($op) ? $op : [];
  8080. }
  8081. if ($keyword === '' && $filterArr === []) {
  8082. return array_values(array_filter($dbRows, 'is_array'));
  8083. }
  8084. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8085. $out = [];
  8086. foreach ($dbRows as $row) {
  8087. if (!is_array($row)) {
  8088. continue;
  8089. }
  8090. if ($keyword !== '') {
  8091. $hit = false;
  8092. foreach ($searchFields as $f) {
  8093. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8094. $hit = true;
  8095. break;
  8096. }
  8097. }
  8098. if (!$hit) {
  8099. continue;
  8100. }
  8101. }
  8102. $passFilter = true;
  8103. foreach ($filterArr as $field => $val) {
  8104. $field = (string)$field;
  8105. $val = trim((string)$val);
  8106. if ($field === '' || $val === '') {
  8107. continue;
  8108. }
  8109. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8110. continue;
  8111. }
  8112. $cell = (string)($row[$field] ?? '');
  8113. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8114. if ($mode === '=' || $mode === 'EQUAL') {
  8115. if (strcasecmp($cell, $val) !== 0) {
  8116. $passFilter = false;
  8117. break;
  8118. }
  8119. } elseif (mb_stripos($cell, $val) === false) {
  8120. $passFilter = false;
  8121. break;
  8122. }
  8123. }
  8124. if (!$passFilter) {
  8125. continue;
  8126. }
  8127. $out[] = $row;
  8128. }
  8129. return $out;
  8130. }
  8131. /**
  8132. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8133. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8134. */
  8135. public function export_month_outward()
  8136. {
  8137. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8138. $this->error(__('You have no permission'));
  8139. }
  8140. $this->request->filter(['strip_tags', 'trim']);
  8141. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8142. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8143. $ym = date('Y-m');
  8144. }
  8145. $dbRows = [];
  8146. try {
  8147. $query = Db::table('purchase_order');
  8148. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8149. $dbRows = $query->select();
  8150. } catch (\Throwable $e) {
  8151. $dbRows = [];
  8152. }
  8153. if (!is_array($dbRows)) {
  8154. $dbRows = [];
  8155. }
  8156. $completeTsMap = [];
  8157. $sidList = [];
  8158. foreach ($dbRows as $dbRow) {
  8159. if (!is_array($dbRow)) {
  8160. continue;
  8161. }
  8162. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8163. if ($sid > 0) {
  8164. $sidList[$sid] = true;
  8165. }
  8166. }
  8167. if ($sidList !== []) {
  8168. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8169. }
  8170. $searchKw = trim((string)$this->request->get('search', ''));
  8171. if ($searchKw === '') {
  8172. $searchKw = trim((string)$this->request->request('search', ''));
  8173. }
  8174. $filterRaw = $this->request->get('filter', '');
  8175. $filterArrTmp = [];
  8176. if (is_string($filterRaw) && $filterRaw !== '') {
  8177. $filterArrTmp = (array)json_decode($filterRaw, true);
  8178. } elseif (is_array($filterRaw)) {
  8179. $filterArrTmp = $filterRaw;
  8180. }
  8181. $hasSearch = ($searchKw !== '');
  8182. if (!$hasSearch) {
  8183. foreach ($filterArrTmp as $fv) {
  8184. if (trim((string)$fv) !== '') {
  8185. $hasSearch = true;
  8186. break;
  8187. }
  8188. }
  8189. }
  8190. // 有搜索时跨月份导出(与列表一致);无搜索时仍按查看月份
  8191. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8192. if (!is_array($dbRow)) {
  8193. return false;
  8194. }
  8195. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8196. if ($done['ts'] <= 0) {
  8197. return false;
  8198. }
  8199. if ($hasSearch) {
  8200. return true;
  8201. }
  8202. return date('Y-m', $done['ts']) === $ym;
  8203. }));
  8204. // 与列表页一致:按搜索关键字 / 通用搜索过滤
  8205. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8206. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8207. $filtered = $pool;
  8208. $mainBySid = [];
  8209. foreach ($filtered as $rw) {
  8210. if (!is_array($rw)) {
  8211. continue;
  8212. }
  8213. $rid = (int)($rw['ID'] ?? 0);
  8214. if ($rid > 0) {
  8215. $mainBySid[$rid] = $rw;
  8216. }
  8217. }
  8218. if ($mainBySid === []) {
  8219. $detailRows = [];
  8220. } else {
  8221. try {
  8222. $detailRows = Db::table('purchase_order_detail')
  8223. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8224. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8225. ->order('status', 'desc')
  8226. ->order('CCYDH', 'asc')
  8227. ->order('company_name', 'asc')
  8228. ->order('id', 'asc')
  8229. ->select();
  8230. } catch (\Throwable $e) {
  8231. try {
  8232. $detailRows = Db::table('purchase_order_detail')
  8233. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8234. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8235. ->order('status', 'desc')
  8236. ->order('CCYDH', 'asc')
  8237. ->order('company_name', 'asc')
  8238. ->order('ID', 'asc')
  8239. ->select();
  8240. } catch (\Throwable $e2) {
  8241. $detailRows = [];
  8242. }
  8243. }
  8244. }
  8245. if (!is_array($detailRows)) {
  8246. $detailRows = [];
  8247. }
  8248. $exportLines = [];
  8249. $detailSidSeen = [];
  8250. foreach ($detailRows as $dr) {
  8251. if (!is_array($dr)) {
  8252. continue;
  8253. }
  8254. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8255. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8256. continue;
  8257. }
  8258. if (isset($detailSidSeen[$sid])) {
  8259. continue;
  8260. }
  8261. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8262. continue;
  8263. }
  8264. $detailSidSeen[$sid] = true;
  8265. $m = $mainBySid[$sid];
  8266. $exportLines[] = [
  8267. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8268. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8269. 'company_name' => (string)($dr['company_name'] ?? ''),
  8270. 'CDF' => (string)($m['CDF'] ?? ''),
  8271. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8272. 'gx' => $this->procuremenExportGxText($m),
  8273. 'detail' => $dr,
  8274. ];
  8275. }
  8276. foreach ($detailRows as $dr) {
  8277. if (!is_array($dr)) {
  8278. continue;
  8279. }
  8280. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8281. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8282. continue;
  8283. }
  8284. $detailSidSeen[$sid] = true;
  8285. $m = $mainBySid[$sid];
  8286. $exportLines[] = [
  8287. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8288. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8289. 'company_name' => (string)($dr['company_name'] ?? ''),
  8290. 'CDF' => (string)($m['CDF'] ?? ''),
  8291. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8292. 'gx' => $this->procuremenExportGxText($m),
  8293. 'detail' => $dr,
  8294. ];
  8295. }
  8296. foreach ($mainBySid as $sid => $m) {
  8297. if (isset($detailSidSeen[$sid])) {
  8298. continue;
  8299. }
  8300. $company = trim((string)($m['pick_company_name'] ?? ''));
  8301. $exportLines[] = [
  8302. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8303. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8304. 'company_name' => $company,
  8305. 'CDF' => (string)($m['CDF'] ?? ''),
  8306. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8307. 'gx' => $this->procuremenExportGxText($m),
  8308. 'detail' => [],
  8309. ];
  8310. }
  8311. $groups = [];
  8312. foreach ($exportLines as $line) {
  8313. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8314. if (!isset($groups[$k])) {
  8315. $groups[$k] = [];
  8316. }
  8317. $groups[$k][] = $line;
  8318. }
  8319. ksort($groups, SORT_STRING);
  8320. $spreadsheet = new Spreadsheet();
  8321. $sheet = $spreadsheet->getActiveSheet();
  8322. $sheet->setTitle('外协加工明细');
  8323. $mon = (int)substr($ym, 5, 2);
  8324. $sheet->mergeCells('A1:H1');
  8325. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8326. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8327. $sheet->getStyle('A1')->getAlignment()
  8328. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8329. ->setVertical(Alignment::VERTICAL_CENTER);
  8330. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8331. $col = 'A';
  8332. foreach ($headers as $h) {
  8333. $sheet->setCellValue($col . '2', $h);
  8334. $col++;
  8335. }
  8336. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8337. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8338. $rowNum = 3;
  8339. $sumSubtotalCounts = 0;
  8340. $grandAmount = 0.0;
  8341. $globalSeq = 0;
  8342. if ($groups === []) {
  8343. $sheet->mergeCells('A3:H3');
  8344. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8345. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8346. $rowNum = 4;
  8347. } else {
  8348. foreach ($groups as $items) {
  8349. if ($items === []) {
  8350. continue;
  8351. }
  8352. $groupLineCount = count($items);
  8353. $subAmount = 0.0;
  8354. foreach ($items as $line) {
  8355. $globalSeq++;
  8356. $dr = $line['detail'];
  8357. $amt = $this->procuremenExportAmount($dr);
  8358. $subAmount += $amt;
  8359. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8360. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8361. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8362. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8363. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8364. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8365. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8366. $sheet->setCellValue('H' . $rowNum, $amt);
  8367. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8368. $rowNum++;
  8369. }
  8370. $sumSubtotalCounts += $groupLineCount;
  8371. $grandAmount += $subAmount;
  8372. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8373. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8374. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8375. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8376. ->setVertical(Alignment::VERTICAL_CENTER);
  8377. $rowNum++;
  8378. }
  8379. }
  8380. $sheet->setCellValue('A' . $rowNum, '总计');
  8381. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8382. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8383. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8384. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8385. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8386. $lastRow = $rowNum;
  8387. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8388. 'borders' => [
  8389. 'allBorders' => [
  8390. 'borderStyle' => Border::BORDER_THIN,
  8391. 'color' => ['rgb' => '000000'],
  8392. ],
  8393. ],
  8394. ]);
  8395. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8396. if ($lastRow >= 3) {
  8397. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8398. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8399. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8400. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8401. }
  8402. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8403. $sheet->getColumnDimension('A')->setWidth(7);
  8404. $sheet->getColumnDimension('B')->setWidth(16);
  8405. $sheet->getColumnDimension('C')->setWidth(52);
  8406. $sheet->getColumnDimension('D')->setWidth(32);
  8407. $sheet->getColumnDimension('E')->setWidth(12);
  8408. $sheet->getColumnDimension('F')->setWidth(44);
  8409. $sheet->getColumnDimension('G')->setWidth(26);
  8410. $sheet->getColumnDimension('H')->setWidth(13);
  8411. $sheet->getRowDimension(1)->setRowHeight(28);
  8412. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8413. $quoteStartRow = $lastRow + 3;
  8414. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  8415. if ($quoteLastRow >= $quoteStartRow) {
  8416. $sheet->getColumnDimension('E')->setWidth(28);
  8417. }
  8418. $ymCompact = str_replace('-', '', $ym);
  8419. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8420. $filename = $fileBase . '.xlsx';
  8421. try {
  8422. $this->ensurePurchaseMonthExportLogTable();
  8423. list($adminId, $adminName) = $this->GetUseName();
  8424. Db::table('purchase_month_export_log')->insert([
  8425. 'ym' => $ym,
  8426. 'admin_id' => (int)$adminId,
  8427. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8428. 'row_count' => count($exportLines),
  8429. 'total_amount' => round($grandAmount, 2),
  8430. 'createtime' => time(),
  8431. ]);
  8432. } catch (\Throwable $e) {
  8433. Log::write('month export log: ' . $e->getMessage(), 'error');
  8434. }
  8435. if (ob_get_length()) {
  8436. ob_end_clean();
  8437. }
  8438. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8439. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8440. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8441. header('Cache-Control: max-age=0');
  8442. $writer = new Xlsx($spreadsheet);
  8443. $writer->save('php://output');
  8444. $spreadsheet->disconnectWorksheets();
  8445. unset($spreadsheet);
  8446. exit;
  8447. }
  8448. /**
  8449. * 导出用:工序列文案
  8450. */
  8451. protected function procuremenExportGxText(array $r)
  8452. {
  8453. $a = trim((string)($r['CDXMC'] ?? ''));
  8454. $b = trim((string)($r['CGYMC'] ?? ''));
  8455. if ($a !== '' && $b !== '') {
  8456. return $a . ':' . $b;
  8457. }
  8458. return $a !== '' ? $a : $b;
  8459. }
  8460. /**
  8461. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8462. */
  8463. protected function procuremenExportAmount(array $r)
  8464. {
  8465. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8466. if (!array_key_exists($k, $r)) {
  8467. continue;
  8468. }
  8469. $v = $r[$k];
  8470. if ($v === null || $v === '') {
  8471. continue;
  8472. }
  8473. if (is_numeric($v)) {
  8474. return (float)$v;
  8475. }
  8476. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8477. if ($v !== '' && is_numeric($v)) {
  8478. return (float)$v;
  8479. }
  8480. }
  8481. return 0.0;
  8482. }
  8483. /**
  8484. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8485. *
  8486. * @param array<int, array<string, mixed>> $detailRows
  8487. * @param array<int, array<string, mixed>> $mainBySid
  8488. * @return array<int, array<string, mixed>>
  8489. */
  8490. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8491. {
  8492. $lines = [];
  8493. foreach ($detailRows as $dr) {
  8494. if (!is_array($dr)) {
  8495. continue;
  8496. }
  8497. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8498. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8499. continue;
  8500. }
  8501. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8502. continue;
  8503. }
  8504. $cn = trim((string)($dr['company_name'] ?? ''));
  8505. if ($cn === '') {
  8506. continue;
  8507. }
  8508. $m = $mainBySid[$sid];
  8509. $am = trim((string)($dr['amount'] ?? ''));
  8510. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8511. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8512. $amountText = $amountFilled
  8513. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8514. : '未填写';
  8515. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8516. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8517. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8518. $deliveryShow = $deliveryRaw;
  8519. }
  8520. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8521. ? $deliveryShow
  8522. : '未填写';
  8523. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8524. $lines[] = [
  8525. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8526. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8527. 'gx' => $this->procuremenExportGxText($m),
  8528. 'company_name' => $cn,
  8529. 'amount_text' => $amountText,
  8530. 'amount_num' => $amountFilled ? $amountNum : null,
  8531. 'delivery_text' => $deliveryText,
  8532. 'picked_text' => $picked ? '中标' : '未中标',
  8533. 'picked' => $picked,
  8534. ];
  8535. }
  8536. $winnerSupplierByOrder = [];
  8537. foreach ($lines as $line) {
  8538. $dh = trim((string)($line['CCYDH'] ?? ''));
  8539. $cn = trim((string)($line['company_name'] ?? ''));
  8540. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8541. $winnerSupplierByOrder[$dh][$cn] = true;
  8542. }
  8543. }
  8544. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8545. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8546. if ($c !== 0) {
  8547. return $c;
  8548. }
  8549. $dh = trim((string)($a['CCYDH'] ?? ''));
  8550. $aCn = trim((string)($a['company_name'] ?? ''));
  8551. $bCn = trim((string)($b['company_name'] ?? ''));
  8552. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8553. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8554. if ($aSupplierWin !== $bSupplierWin) {
  8555. return $aSupplierWin ? -1 : 1;
  8556. }
  8557. $c = strcmp($aCn, $bCn);
  8558. if ($c !== 0) {
  8559. return $c;
  8560. }
  8561. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8562. return !empty($a['picked']) ? -1 : 1;
  8563. }
  8564. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8565. if ($c !== 0) {
  8566. return $c;
  8567. }
  8568. return 0;
  8569. });
  8570. return $lines;
  8571. }
  8572. /**
  8573. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8574. *
  8575. * @param array<int, array<string, mixed>> $quoteLines
  8576. */
  8577. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8578. {
  8579. $mon = (int)substr($ym, 5, 2);
  8580. $titleRow = $startRow;
  8581. $headerRow = $startRow + 1;
  8582. $dataStartRow = $startRow + 2;
  8583. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8584. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8585. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8586. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8587. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8588. ->setVertical(Alignment::VERTICAL_CENTER);
  8589. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8590. $col = 'A';
  8591. foreach ($headers as $h) {
  8592. $sheet->setCellValue($col . $headerRow, $h);
  8593. $col++;
  8594. }
  8595. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8596. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8597. $rowNum = $dataStartRow;
  8598. if ($quoteLines === []) {
  8599. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8600. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8601. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8602. $rowNum = $dataStartRow + 1;
  8603. } else {
  8604. $i = 0;
  8605. foreach ($quoteLines as $line) {
  8606. $i++;
  8607. $sheet->setCellValue('A' . $rowNum, $i);
  8608. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8609. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8610. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8611. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8612. if ($line['amount_num'] !== null) {
  8613. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8614. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8615. } else {
  8616. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8617. }
  8618. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8619. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8620. if (!empty($line['picked'])) {
  8621. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8622. }
  8623. $rowNum++;
  8624. }
  8625. }
  8626. $lastRow = $rowNum - 1;
  8627. if ($lastRow >= $headerRow) {
  8628. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8629. 'borders' => [
  8630. 'allBorders' => [
  8631. 'borderStyle' => Border::BORDER_THIN,
  8632. 'color' => ['rgb' => '000000'],
  8633. ],
  8634. ],
  8635. ]);
  8636. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8637. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8638. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8639. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8640. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8641. if ($lastRow >= $dataStartRow) {
  8642. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8643. }
  8644. }
  8645. return $lastRow;
  8646. }
  8647. /**
  8648. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8649. */
  8650. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8651. {
  8652. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8653. return;
  8654. }
  8655. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8656. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8657. ->setVertical(Alignment::VERTICAL_CENTER);
  8658. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8659. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8660. ->setVertical(Alignment::VERTICAL_CENTER);
  8661. if ($lastCol > 'B') {
  8662. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8663. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8664. ->setVertical(Alignment::VERTICAL_CENTER);
  8665. }
  8666. }
  8667. /**
  8668. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8669. */
  8670. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8671. {
  8672. $s = trim($ccydh);
  8673. if ($s === '') {
  8674. return 'ORDER';
  8675. }
  8676. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8677. $s = trim($s, '._-');
  8678. if ($s === '') {
  8679. return 'ORDER';
  8680. }
  8681. if (function_exists('mb_substr')) {
  8682. return mb_substr($s, 0, 80, 'UTF-8');
  8683. }
  8684. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8685. }
  8686. /**
  8687. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8688. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8689. *
  8690. * @return array{objectKey: string, webPath: string}
  8691. */
  8692. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8693. {
  8694. $sid = (int)$scydgyId;
  8695. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8696. $y = date('Y');
  8697. $m = date('m');
  8698. $d = date('d');
  8699. $basename = $safeOrder . '_' . $sid . '.pdf';
  8700. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8701. return [
  8702. 'objectKey' => $objectKey,
  8703. 'webPath' => '/' . $objectKey,
  8704. ];
  8705. }
  8706. /**
  8707. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8708. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8709. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8710. *
  8711. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8712. */
  8713. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8714. {
  8715. if (!$this->isValidScydgyRowId($scydgyId)) {
  8716. return '';
  8717. }
  8718. $ids = trim((string)$scydgyId);
  8719. $prep = $this->prepareProcuremenDetailsView($ids);
  8720. if (!$prep['ok']) {
  8721. return '';
  8722. }
  8723. $ccydh = $prep['ccydh'];
  8724. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8725. $objectKey = $paths['objectKey'];
  8726. $webPath = $paths['webPath'];
  8727. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8728. $this->view->assign([
  8729. 'pdf_export' => 1,
  8730. 'pdfMetaLine' => $meta,
  8731. ]);
  8732. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8733. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8734. $this->view->engine->layout(false);
  8735. try {
  8736. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8737. } catch (\Throwable $e) {
  8738. if ($restoreLayout) {
  8739. $this->view->engine->layout($restoreLayout);
  8740. }
  8741. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8742. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8743. return '';
  8744. }
  8745. if ($restoreLayout) {
  8746. $this->view->engine->layout($restoreLayout);
  8747. }
  8748. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8749. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8750. if (!is_dir($tempDir)) {
  8751. @mkdir($tempDir, 0755, true);
  8752. }
  8753. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8754. try {
  8755. $mpdf = new \Mpdf\Mpdf([
  8756. 'mode' => 'utf-8',
  8757. 'format' => 'A4',
  8758. 'margin_left' => 12,
  8759. 'margin_right' => 12,
  8760. 'margin_top' => 14,
  8761. 'margin_bottom' => 14,
  8762. 'tempDir' => $tempDir,
  8763. 'autoScriptToLang' => true,
  8764. 'autoLangToFont' => true,
  8765. ]);
  8766. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8767. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8768. $mpdf->SetBasePath('http://127.0.0.1/');
  8769. $mpdf->WriteHTML($html);
  8770. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8771. } catch (\Throwable $e) {
  8772. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8773. if (is_file($tempPdf)) {
  8774. @unlink($tempPdf);
  8775. }
  8776. return '';
  8777. }
  8778. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8779. if ($ossUrl !== '') {
  8780. @unlink($tempPdf);
  8781. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8782. return $ossUrl;
  8783. }
  8784. $pi = pathinfo($objectKey);
  8785. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8786. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8787. if ($baseFile === '') {
  8788. @unlink($tempPdf);
  8789. return '';
  8790. }
  8791. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8792. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8793. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8794. @unlink($tempPdf);
  8795. return '';
  8796. }
  8797. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8798. if (!@copy($tempPdf, $fullPath)) {
  8799. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8800. @unlink($tempPdf);
  8801. return '';
  8802. }
  8803. @unlink($tempPdf);
  8804. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8805. return $webPath;
  8806. }
  8807. /**
  8808. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8809. */
  8810. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8811. {
  8812. if ($scydgyId <= 0 || $webPath === '') {
  8813. return;
  8814. }
  8815. try {
  8816. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8817. } catch (\Throwable $e) {
  8818. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8819. }
  8820. }
  8821. /**
  8822. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8823. *
  8824. * @param array<string, string> $vars
  8825. * @return array<string, string>
  8826. */
  8827. protected function normalizeSmsTemplateVars(array $vars): array
  8828. {
  8829. $out = [];
  8830. foreach ($vars as $k => $v) {
  8831. $out[(string)$k] = trim((string)$v);
  8832. }
  8833. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8834. $out['contact_name'] = $out['company_name'];
  8835. }
  8836. return $out;
  8837. }
  8838. /**
  8839. * 按手机号或公司名称查 customer 表联系人姓名
  8840. */
  8841. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8842. {
  8843. $phone = trim($phone);
  8844. $companyName = trim($companyName);
  8845. try {
  8846. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8847. $row = Db::table('customer')
  8848. ->where(function ($q) use ($phone) {
  8849. $q->where('phone', $phone)->whereOr('account', $phone);
  8850. })
  8851. ->order('id', 'asc')
  8852. ->find();
  8853. if (is_array($row)) {
  8854. $nm = trim((string)($row['username'] ?? ''));
  8855. if ($nm !== '') {
  8856. return $nm;
  8857. }
  8858. }
  8859. }
  8860. if ($companyName !== '') {
  8861. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8862. if (is_array($row)) {
  8863. return trim((string)($row['username'] ?? ''));
  8864. }
  8865. }
  8866. } catch (\Throwable $e) {
  8867. }
  8868. return '';
  8869. }
  8870. /**
  8871. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8872. */
  8873. protected function plainTextToHtmlEmailBody(string $text): string
  8874. {
  8875. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8876. $parts = explode("\n", $text);
  8877. $out = [];
  8878. foreach ($parts as $line) {
  8879. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8880. $out[] = $line;
  8881. } else {
  8882. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8883. }
  8884. }
  8885. return implode("<br>\n", $out);
  8886. }
  8887. /**
  8888. * 短信场景:去掉链接类变量,避免误填 URL
  8889. *
  8890. * @param array<string, string> $vars
  8891. * @return array<string, string>
  8892. */
  8893. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8894. {
  8895. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8896. return $vars;
  8897. }
  8898. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8899. $vars[$k] = '';
  8900. }
  8901. return $vars;
  8902. }
  8903. /**
  8904. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8905. *
  8906. * @param array<string, string> $vars
  8907. */
  8908. protected function renderNotifyTemplate(string $scene, array $vars): string
  8909. {
  8910. $vars = $this->normalizeSmsTemplateVars($vars);
  8911. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8912. $row = $this->loadNotifyTemplateRow($scene);
  8913. if ($row === null) {
  8914. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8915. }
  8916. $tpl = trim((string)($row['content'] ?? ''));
  8917. if ($tpl === '') {
  8918. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8919. }
  8920. foreach ($vars as $k => $v) {
  8921. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8922. }
  8923. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8924. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8925. return $tpl;
  8926. }
  8927. protected function resolveProcuremenEmailSubject(string $scene): string
  8928. {
  8929. $map = [
  8930. 'review_email' => '您有新的协助加工订单',
  8931. ];
  8932. $subject = trim((string)($map[$scene] ?? ''));
  8933. if ($subject === '') {
  8934. $this->error('未配置邮件主题:' . $scene);
  8935. }
  8936. return $subject;
  8937. }
  8938. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8939. {
  8940. $map = [
  8941. 'review_email' => '协助下发-邮箱',
  8942. 'review_sms' => '协助下发-短信',
  8943. 'confirm_ok' => '采购确认-通过',
  8944. 'confirm_fail' => '采购确认-未通过',
  8945. 'bid_open' => '开标双重验证',
  8946. ];
  8947. $label = $map[$scene] ?? $scene;
  8948. if ($titleRequired) {
  8949. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8950. }
  8951. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8952. }
  8953. /**
  8954. * 是否开启协助通知演练(不发真实短信/邮件)
  8955. */
  8956. protected function isProcuremenNotifyDryRun(): bool
  8957. {
  8958. return (bool)Config::get('procuremen_notify_dry_run');
  8959. }
  8960. /**
  8961. * @param array<string, mixed> $payload
  8962. */
  8963. protected function recordNotifyDryRunPreview(array $payload): void
  8964. {
  8965. $this->notifyDryRunPreview[] = $payload;
  8966. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8967. }
  8968. /**
  8969. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8970. * @throws \Exception
  8971. */
  8972. protected function smsbao($phone, $content)
  8973. {
  8974. if ($this->isProcuremenNotifyDryRun()) {
  8975. $this->recordNotifyDryRunPreview([
  8976. 'scene' => 'sms_only',
  8977. 'phone' => $phone,
  8978. 'sms_content' => $content,
  8979. ]);
  8980. return;
  8981. }
  8982. $statusStr = [
  8983. '0' => '短信发送成功',
  8984. '-1' => '参数不全',
  8985. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8986. '30' => '密码错误',
  8987. '40' => '账号不存在',
  8988. '41' => '余额不足',
  8989. '42' => '帐户已过期',
  8990. '43' => 'IP地址限制',
  8991. '50' => '内容含有敏感词',
  8992. ];
  8993. $smsapi = 'http://api.smsbao.com/';
  8994. $user = 'zhuwei123';
  8995. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8996. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8997. $result = @file_get_contents($sendurl);
  8998. if ($result === false) {
  8999. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9000. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9001. }
  9002. $result = trim((string)$result);
  9003. if ($result !== '0') {
  9004. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9005. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9006. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9007. }
  9008. }
  9009. }