Procuremen.php 336 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012
  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. foreach ($rows as &$rw) {
  1135. if (!is_array($rw)) {
  1136. continue;
  1137. }
  1138. $mergeIds = [];
  1139. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1140. foreach ($rw['_order_merge_rows'] as $mr) {
  1141. $mid = (int)($mr['ID'] ?? 0);
  1142. if ($this->isValidScydgyRowId($mid)) {
  1143. $mergeIds[$mid] = true;
  1144. }
  1145. }
  1146. }
  1147. $rid = (int)($rw['ID'] ?? 0);
  1148. if ($this->isValidScydgyRowId($rid)) {
  1149. $mergeIds[$rid] = true;
  1150. }
  1151. $buckets = [];
  1152. foreach (array_keys($mergeIds) as $mid) {
  1153. if (isset($quoteBucket[$mid])) {
  1154. $buckets[] = $quoteBucket[$mid];
  1155. }
  1156. }
  1157. $supplierText = $buckets !== []
  1158. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1159. : '';
  1160. if ($wffTab === 'confirm') {
  1161. $rw['picked_supplier_name'] = $supplierText;
  1162. } else {
  1163. $rw['notify_supplier_text'] = $supplierText;
  1164. }
  1165. }
  1166. unset($rw);
  1167. }
  1168. if ($wffTab === 'all' && count($rows) > 0) {
  1169. $this->mergePurchaseOrder($rows);
  1170. }
  1171. if ($wffTab === 'pick' && count($rows) > 0) {
  1172. $this->mergePurchaseOrder($rows);
  1173. }
  1174. foreach ($rows as &$rwClean) {
  1175. if (is_array($rwClean)) {
  1176. unset($rwClean['_order_merge_rows']);
  1177. if (array_key_exists('NGZL', $rwClean)) {
  1178. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1179. }
  1180. }
  1181. }
  1182. unset($rwClean);
  1183. return json([
  1184. 'total' => count($filtered),
  1185. 'rows' => $rows,
  1186. 'activeYm' => $ym,
  1187. ]);
  1188. } catch (\Throwable $e) {
  1189. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1190. return json([
  1191. 'total' => 0,
  1192. 'rows' => [],
  1193. ]);
  1194. }
  1195. }
  1196. /**
  1197. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1198. *
  1199. * @return array<int, true>
  1200. */
  1201. protected function loadPickHiddenScydgySet(): array
  1202. {
  1203. if ($this->pickHiddenScydgySetCache !== null) {
  1204. return $this->pickHiddenScydgySetCache;
  1205. }
  1206. $hideSet = [];
  1207. try {
  1208. $poIds = Db::table('purchase_order')
  1209. ->where(function ($q) {
  1210. $q->whereIn('wflow_status', array_merge(
  1211. ProcuremenStatus::wflowPendingConfirmValues(),
  1212. ProcuremenStatus::wflowPendingApprovalValues()
  1213. ))
  1214. ->whereOr(function ($q1) {
  1215. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1216. })
  1217. ->whereOr(function ($q2) {
  1218. $q2->whereNotNull('pick_time')
  1219. ->where('pick_time', '<>', '')
  1220. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1221. })
  1222. ->whereOr(function ($q3) {
  1223. $q3->whereNotNull('mod_rq')
  1224. ->where('mod_rq', '<>', '')
  1225. ->where('mod_rq', 'not like', '0000-00-00%');
  1226. });
  1227. })
  1228. ->column('scydgy_id');
  1229. if (is_array($poIds)) {
  1230. foreach ($poIds as $pid) {
  1231. $k = (int)$pid;
  1232. if ($k !== 0) {
  1233. $hideSet[$k] = true;
  1234. }
  1235. }
  1236. }
  1237. } catch (\Throwable $e) {
  1238. }
  1239. try {
  1240. $detIdsQuery = Db::table('purchase_order_detail');
  1241. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1242. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1243. if (is_array($detIds)) {
  1244. foreach ($detIds as $pid) {
  1245. $k = (int)$pid;
  1246. if ($this->isValidScydgyRowId($k)) {
  1247. $hideSet[$k] = true;
  1248. }
  1249. }
  1250. }
  1251. } catch (\Throwable $e) {
  1252. }
  1253. $this->pickHiddenScydgySetCache = $hideSet;
  1254. return $hideSet;
  1255. }
  1256. /**
  1257. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1258. *
  1259. * @return array<int, array<string, mixed>>
  1260. */
  1261. protected function loadPickManualOrderRows(): array
  1262. {
  1263. try {
  1264. $dbRows = Db::table('purchase_order')
  1265. ->where('scydgy_id', '<', 0)
  1266. ->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%\')')
  1267. ->order('scydgy_id', 'asc')
  1268. ->select();
  1269. } catch (\Throwable $e) {
  1270. try {
  1271. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1272. } catch (\Throwable $e2) {
  1273. return [];
  1274. }
  1275. }
  1276. if (!is_array($dbRows) || $dbRows === []) {
  1277. return [];
  1278. }
  1279. $detailSidSet = [];
  1280. try {
  1281. $negIds = [];
  1282. foreach ($dbRows as $dbRow) {
  1283. if (!is_array($dbRow)) {
  1284. continue;
  1285. }
  1286. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1287. if ($sid < 0) {
  1288. $negIds[$sid] = true;
  1289. }
  1290. }
  1291. if ($negIds !== []) {
  1292. $detQuery = Db::table('purchase_order_detail')
  1293. ->where('scydgy_id', 'in', array_keys($negIds));
  1294. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1295. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1296. if (is_array($detRows)) {
  1297. foreach ($detRows as $did) {
  1298. $detailSidSet[(int)$did] = true;
  1299. }
  1300. }
  1301. }
  1302. } catch (\Throwable $e) {
  1303. }
  1304. $pool = [];
  1305. foreach ($dbRows as $dbRow) {
  1306. if (!is_array($dbRow)) {
  1307. continue;
  1308. }
  1309. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1310. if ($sid >= 0) {
  1311. continue;
  1312. }
  1313. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1314. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1315. continue;
  1316. }
  1317. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1318. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1319. continue;
  1320. }
  1321. if (isset($detailSidSet[$sid])) {
  1322. continue;
  1323. }
  1324. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1325. $r['_is_manual'] = 1;
  1326. $pool[] = $r;
  1327. }
  1328. return $pool;
  1329. }
  1330. /**
  1331. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1332. */
  1333. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1334. {
  1335. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1336. foreach ($keys as $k) {
  1337. $t = trim((string)($row[$k] ?? ''));
  1338. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1339. return $t;
  1340. }
  1341. }
  1342. return '';
  1343. }
  1344. /**
  1345. * 分配手工新增工序行 ID(负数递减)
  1346. */
  1347. protected function allocateManualScydgyId(): int
  1348. {
  1349. try {
  1350. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1351. $min = (int)$min;
  1352. return $min < 0 ? $min - 1 : -1;
  1353. } catch (\Throwable $e) {
  1354. return -1;
  1355. }
  1356. }
  1357. /**
  1358. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1359. */
  1360. protected function allocateManualOrderCcydh(): string
  1361. {
  1362. $prefix = 'YW' . date('Ymd');
  1363. $maxSeq = 0;
  1364. try {
  1365. $rows = Db::table('purchase_order')
  1366. ->where('CCYDH', 'like', $prefix . '%')
  1367. ->column('CCYDH');
  1368. if (is_array($rows)) {
  1369. foreach ($rows as $ccydh) {
  1370. $ccydh = trim((string)$ccydh);
  1371. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1372. $maxSeq = max($maxSeq, (int)$m[1]);
  1373. }
  1374. }
  1375. }
  1376. } catch (\Throwable $e) {
  1377. }
  1378. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1379. }
  1380. /**
  1381. * purchase_order.mod_rq 是否有有效软删除时间
  1382. */
  1383. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1384. {
  1385. $t = trim((string)$modRq);
  1386. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1387. }
  1388. /**
  1389. * 列表行 → purchase_order 写入字段
  1390. *
  1391. * @return array<string, mixed>
  1392. */
  1393. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1394. {
  1395. return [
  1396. 'scydgy_id' => $scydgyId,
  1397. 'CCYDH' => $row['CCYDH'] ?? null,
  1398. 'CYJMC' => $row['CYJMC'] ?? null,
  1399. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1400. 'CDXMC' => $row['CDXMC'] ?? null,
  1401. 'CGYBH' => $row['CGYBH'] ?? null,
  1402. 'CGYMC' => $row['CGYMC'] ?? null,
  1403. 'CDW' => $row['CDW'] ?? null,
  1404. 'NGZL' => $row['NGZL'] ?? null,
  1405. 'CDF' => $row['CDF'] ?? null,
  1406. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1407. 'MBZ' => $row['MBZ'] ?? null,
  1408. 'bwjg' => $row['bwjg'] ?? null,
  1409. 'iStatus' => $row['iStatus'] ?? null,
  1410. 'dStamp' => $row['dStamp'] ?? null,
  1411. 'dputrecord' => $row['dputrecord'] ?? null,
  1412. 'cywyxm' => $row['cywyxm'] ?? null,
  1413. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1414. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1415. ];
  1416. }
  1417. /**
  1418. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1419. *
  1420. * @return array{po:?array<string,mixed>, hidden:bool}
  1421. */
  1422. protected function resolvePickRowPoContext(int $sid): array
  1423. {
  1424. $po = null;
  1425. try {
  1426. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1427. if (is_array($found)) {
  1428. $po = $found;
  1429. }
  1430. } catch (\Throwable $e) {
  1431. }
  1432. $hideSet = $this->loadPickHiddenScydgySet();
  1433. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1434. }
  1435. /**
  1436. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1437. */
  1438. protected function assertPickRowCanDelete(int $sid, array $row): void
  1439. {
  1440. $ctx = $this->resolvePickRowPoContext($sid);
  1441. $po = $ctx['po'];
  1442. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1443. return;
  1444. }
  1445. if (is_array($po)) {
  1446. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1447. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1448. }
  1449. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1450. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1451. }
  1452. }
  1453. if ($ctx['hidden']) {
  1454. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1455. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1456. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1457. }
  1458. }
  1459. /**
  1460. * 初选直接完结前校验
  1461. */
  1462. protected function assertPickRowCanComplete(int $sid, array $row): void
  1463. {
  1464. $ctx = $this->resolvePickRowPoContext($sid);
  1465. $po = $ctx['po'];
  1466. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1467. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1468. }
  1469. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1470. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1471. }
  1472. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1473. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1474. }
  1475. }
  1476. /**
  1477. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1478. */
  1479. protected function softDeleteProcuremenPickRow(array $row): void
  1480. {
  1481. $sid = $this->extractScydgyRowId($row);
  1482. if (!$this->isValidScydgyRowId($sid)) {
  1483. throw new \InvalidArgumentException('无效的行主键');
  1484. }
  1485. $this->assertPickRowCanDelete($sid, $row);
  1486. $po = $this->resolvePickRowPoContext($sid)['po'];
  1487. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1488. return;
  1489. }
  1490. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1491. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1492. }
  1493. $now = date('Y-m-d H:i:s');
  1494. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1495. if (is_array($exists)) {
  1496. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1497. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1498. } else {
  1499. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1500. $data['mod_rq'] = $now;
  1501. $data['createtime'] = $now;
  1502. Db::table('purchase_order')->insert($data);
  1503. $poIdLog = (int)Db::getLastInsID();
  1504. }
  1505. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1506. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1507. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1508. if ($gymcLog !== '') {
  1509. $logTail .= ' / ' . $gymcLog;
  1510. }
  1511. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1512. }
  1513. /**
  1514. * 手工新增协助工序(写入 purchase_order)
  1515. *
  1516. * @param array<string, mixed> $params
  1517. * @return int scydgy_id
  1518. */
  1519. protected function saveManualPickOrder(array $params): int
  1520. {
  1521. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1522. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1523. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1524. if ($ccydh === '') {
  1525. $ccydh = $this->allocateManualOrderCcydh();
  1526. }
  1527. $now = date('Y-m-d H:i:s');
  1528. $sid = $this->allocateManualScydgyId();
  1529. $data = [
  1530. 'scydgy_id' => $sid,
  1531. 'CCYDH' => $ccydh,
  1532. 'CYJMC' => $cyjmc,
  1533. 'CGYMC' => $cgymc,
  1534. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1535. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1536. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1537. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1538. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1539. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1540. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1541. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1542. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1543. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1544. 'createtime' => $now,
  1545. 'dStamp' => $now,
  1546. 'dputrecord' => $now,
  1547. ];
  1548. Db::table('purchase_order')->insert($data);
  1549. $poId = (int)Db::getLastInsID();
  1550. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1551. return $sid;
  1552. }
  1553. protected function formatProcuremenRowLabel(array $row): string
  1554. {
  1555. $dh = trim((string)($row['CCYDH'] ?? ''));
  1556. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1557. if ($dh !== '' && $gymc !== '') {
  1558. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1559. }
  1560. if ($dh !== '') {
  1561. return '订单「' . $dh . '」';
  1562. }
  1563. if ($gymc !== '') {
  1564. return '工序「' . $gymc . '」';
  1565. }
  1566. $id = $this->extractScydgyRowId($row);
  1567. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1568. }
  1569. /**
  1570. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1571. */
  1572. protected function extractScydgyRowId(array $row): int
  1573. {
  1574. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1575. }
  1576. protected function isValidScydgyRowId(int $id): bool
  1577. {
  1578. return ProcuremenGuard::isValidScydgyId($id);
  1579. }
  1580. protected function isManualScydgyRowId(int $id): bool
  1581. {
  1582. return $id < 0;
  1583. }
  1584. /**
  1585. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1586. *
  1587. * @param int[] $scydgyIds
  1588. * @return array<int, string[]>
  1589. */
  1590. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1591. {
  1592. $out = [];
  1593. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1594. if ($scydgyIds === []) {
  1595. return $out;
  1596. }
  1597. try {
  1598. $rows = Db::table('purchase_order_detail')
  1599. ->where('scydgy_id', 'in', $scydgyIds)
  1600. ->field('scydgy_id,company_name')
  1601. ->order('company_name', 'asc')
  1602. ->select();
  1603. } catch (\Throwable $e) {
  1604. $rows = [];
  1605. }
  1606. if (!is_array($rows)) {
  1607. return $out;
  1608. }
  1609. foreach ($rows as $r) {
  1610. if (!is_array($r)) {
  1611. continue;
  1612. }
  1613. $sid = (int)($r['scydgy_id'] ?? 0);
  1614. $cn = trim((string)($r['company_name'] ?? ''));
  1615. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1616. continue;
  1617. }
  1618. if (!isset($out[$sid])) {
  1619. $out[$sid] = [];
  1620. }
  1621. if (!in_array($cn, $out[$sid], true)) {
  1622. $out[$sid][] = $cn;
  1623. }
  1624. }
  1625. return $out;
  1626. }
  1627. /**
  1628. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1629. *
  1630. * @param string[] $names
  1631. */
  1632. protected function formatNotifySupplierDisplay(array $names): string
  1633. {
  1634. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1635. return trim((string)$n);
  1636. }, $names))));
  1637. if ($names === []) {
  1638. return '';
  1639. }
  1640. sort($names, SORT_STRING);
  1641. return implode("\n", $names);
  1642. }
  1643. /**
  1644. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1645. *
  1646. * @param int[] $scydgyIds
  1647. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1648. */
  1649. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1650. {
  1651. $out = [];
  1652. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1653. if ($scydgyIds === []) {
  1654. return $out;
  1655. }
  1656. try {
  1657. $rows = Db::table('purchase_order_detail')
  1658. ->where('scydgy_id', 'in', $scydgyIds)
  1659. ->field('scydgy_id,company_name,amount')
  1660. ->select();
  1661. } catch (\Throwable $e) {
  1662. $rows = [];
  1663. }
  1664. if (!is_array($rows)) {
  1665. return $out;
  1666. }
  1667. foreach ($rows as $r) {
  1668. if (!is_array($r)) {
  1669. continue;
  1670. }
  1671. $sid = (int)($r['scydgy_id'] ?? 0);
  1672. $cn = trim((string)($r['company_name'] ?? ''));
  1673. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1674. continue;
  1675. }
  1676. if (!isset($out[$sid])) {
  1677. $out[$sid] = ['all' => [], 'quoted' => []];
  1678. }
  1679. $out[$sid]['all'][$cn] = true;
  1680. $am = trim((string)($r['amount'] ?? ''));
  1681. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1682. $out[$sid]['quoted'][$cn] = true;
  1683. }
  1684. }
  1685. return $out;
  1686. }
  1687. /**
  1688. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1689. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1690. */
  1691. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1692. {
  1693. $merged = ['all' => [], 'quoted' => []];
  1694. foreach ($buckets as $b) {
  1695. if (!is_array($b)) {
  1696. continue;
  1697. }
  1698. foreach ($b['all'] ?? [] as $cn => $_) {
  1699. $merged['all'][$cn] = true;
  1700. }
  1701. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1702. $merged['quoted'][$cn] = true;
  1703. }
  1704. }
  1705. return $merged;
  1706. }
  1707. /**
  1708. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1709. */
  1710. protected function formatQuotedSupplierLines(array $bucket): string
  1711. {
  1712. $all = array_keys($bucket['all'] ?? []);
  1713. if ($all === []) {
  1714. return '';
  1715. }
  1716. sort($all, SORT_STRING);
  1717. $lines = [];
  1718. foreach ($all as $cn) {
  1719. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1720. $lines[] = $cn . '(' . $status . ')';
  1721. }
  1722. return implode("\n", $lines);
  1723. }
  1724. /**
  1725. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1726. */
  1727. protected function resolveBundleSysRq(array $bundle): string
  1728. {
  1729. foreach ($bundle['pos'] ?? [] as $po) {
  1730. if (!is_array($po)) {
  1731. continue;
  1732. }
  1733. $sr = trim((string)($po['sys_rq'] ?? ''));
  1734. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1735. return $sr;
  1736. }
  1737. }
  1738. return '';
  1739. }
  1740. /**
  1741. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1742. */
  1743. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1744. {
  1745. $raw = trim((string)$sysRq);
  1746. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1747. return true;
  1748. }
  1749. $ts = strtotime(str_replace('T', ' ', $raw));
  1750. if ($ts === false || $ts <= 0) {
  1751. return true;
  1752. }
  1753. return time() >= $ts;
  1754. }
  1755. /**
  1756. * 开标前校验:必须已过报价截止时间
  1757. *
  1758. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1759. */
  1760. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1761. {
  1762. $sysRq = $this->resolveBundleSysRq($bundle);
  1763. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1764. $this->error('未到截止时间');
  1765. }
  1766. }
  1767. /**
  1768. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1769. *
  1770. * @param array<string, mixed> $line
  1771. */
  1772. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1773. {
  1774. $amountFilled = !empty($line['amount_filled']);
  1775. $deliveryFilled = !empty($line['delivery_filled']);
  1776. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1777. $line['amount_show'] = '';
  1778. if (array_key_exists('amount_text', $line)) {
  1779. $line['amount_text'] = $line['unit_price_text'];
  1780. }
  1781. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1782. $line['delivery_show'] = $deliveryText;
  1783. if (array_key_exists('delivery_text', $line)) {
  1784. $line['delivery_text'] = $deliveryText;
  1785. }
  1786. $line['delivery_ymd'] = '';
  1787. $line['subtotal_text'] = $amountFilled ? '' : '';
  1788. $line['subtotal_num'] = null;
  1789. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1790. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1791. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1792. $line['amount_filled'] = false;
  1793. $line['delivery_filled'] = false;
  1794. $line['is_quoted'] = false;
  1795. if (array_key_exists('quote_label', $line)) {
  1796. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未开标验证' : '未报价';
  1797. }
  1798. }
  1799. protected function ensurePurchaseOrderBidOpenTable(): void
  1800. {
  1801. try {
  1802. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1803. } catch (\Throwable $e) {
  1804. Db::execute(
  1805. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1806. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1807. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1808. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1809. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1810. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1811. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1812. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1813. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1814. `createtime` datetime DEFAULT NULL,
  1815. PRIMARY KEY (`id`),
  1816. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1817. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1818. );
  1819. }
  1820. }
  1821. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1822. {
  1823. $ccydh = trim($ccydh);
  1824. if ($ccydh === '') {
  1825. return false;
  1826. }
  1827. $this->ensurePurchaseOrderBidOpenTable();
  1828. try {
  1829. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1830. return is_array($row);
  1831. } catch (\Throwable $e) {
  1832. return false;
  1833. }
  1834. }
  1835. /**
  1836. * @param array{ccydh?:string} $bundle
  1837. */
  1838. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1839. {
  1840. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1841. }
  1842. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1843. {
  1844. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1845. }
  1846. protected function loadBidOpenAdminUser(int $adminId): ?array
  1847. {
  1848. if ($adminId <= 0) {
  1849. return null;
  1850. }
  1851. try {
  1852. $row = Db::name('admin')->where('id', $adminId)->find();
  1853. } catch (\Throwable $e) {
  1854. return null;
  1855. }
  1856. if (!is_array($row)) {
  1857. return null;
  1858. }
  1859. $status = strtolower(trim((string)($row['status'] ?? '')));
  1860. if ($status !== '' && $status !== 'normal') {
  1861. return null;
  1862. }
  1863. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  1864. return null;
  1865. }
  1866. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  1867. if (!preg_match('/^1\d{10}$/', $phone)) {
  1868. return null;
  1869. }
  1870. $name = trim((string)($row['nickname'] ?? ''));
  1871. if ($name === '') {
  1872. $name = trim((string)($row['username'] ?? ''));
  1873. }
  1874. return [
  1875. 'id' => (int)$row['id'],
  1876. 'username' => trim((string)($row['username'] ?? '')),
  1877. 'nickname' => $name,
  1878. 'mobile' => $phone,
  1879. ];
  1880. }
  1881. /**
  1882. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  1883. */
  1884. protected function bidOpenVerifierAuthGroupRootId(): int
  1885. {
  1886. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  1887. return $id > 0 ? $id : 10;
  1888. }
  1889. /**
  1890. * @return int[]
  1891. */
  1892. protected function loadBidOpenVerifierAuthGroupIds(): array
  1893. {
  1894. static $memo = [];
  1895. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  1896. if (isset($memo[$rootId])) {
  1897. return $memo[$rootId];
  1898. }
  1899. try {
  1900. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  1901. } catch (\Throwable $e) {
  1902. $memo[$rootId] = [$rootId];
  1903. return $memo[$rootId];
  1904. }
  1905. if (!is_array($groups) || $groups === []) {
  1906. $memo[$rootId] = [$rootId];
  1907. return $memo[$rootId];
  1908. }
  1909. $groupList = [];
  1910. foreach ($groups as $g) {
  1911. if (is_array($g)) {
  1912. $groupList[] = $g;
  1913. }
  1914. }
  1915. if ($groupList === []) {
  1916. $memo[$rootId] = [$rootId];
  1917. return $memo[$rootId];
  1918. }
  1919. $tree = \fast\Tree::instance();
  1920. $tree->init($groupList);
  1921. $ids = $tree->getChildrenIds($rootId, true);
  1922. if (!is_array($ids) || $ids === []) {
  1923. $memo[$rootId] = [$rootId];
  1924. return $memo[$rootId];
  1925. }
  1926. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  1927. return $memo[$rootId];
  1928. }
  1929. protected function isBidOpenVerifierAdmin(int $adminId): bool
  1930. {
  1931. if ($adminId <= 0) {
  1932. return false;
  1933. }
  1934. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1935. if ($groupIds === []) {
  1936. return false;
  1937. }
  1938. try {
  1939. return (bool)Db::name('auth_group_access')
  1940. ->where('uid', $adminId)
  1941. ->where('group_id', 'in', $groupIds)
  1942. ->count();
  1943. } catch (\Throwable $e) {
  1944. return false;
  1945. }
  1946. }
  1947. /**
  1948. * @return array<int, array<string, mixed>>
  1949. */
  1950. protected function listBidOpenVerifierCandidates(): array
  1951. {
  1952. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1953. if ($groupIds === []) {
  1954. return [];
  1955. }
  1956. try {
  1957. $adminIds = Db::name('auth_group_access')
  1958. ->where('group_id', 'in', $groupIds)
  1959. ->column('uid');
  1960. } catch (\Throwable $e) {
  1961. $adminIds = [];
  1962. }
  1963. $adminIds = is_array($adminIds)
  1964. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  1965. : [];
  1966. if ($adminIds === []) {
  1967. return [];
  1968. }
  1969. try {
  1970. $rows = Db::name('admin')
  1971. ->where('status', 'normal')
  1972. ->where('id', 'in', $adminIds)
  1973. ->where('mobile', '<>', '')
  1974. ->order('id', 'asc')
  1975. ->select();
  1976. } catch (\Throwable $e) {
  1977. return [];
  1978. }
  1979. if (!is_array($rows)) {
  1980. return [];
  1981. }
  1982. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  1983. $out = [];
  1984. foreach ($rows as $row) {
  1985. if (!is_array($row)) {
  1986. continue;
  1987. }
  1988. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  1989. if ($one === null) {
  1990. continue;
  1991. }
  1992. $out[] = [
  1993. 'id' => $one['id'],
  1994. 'username' => $one['username'],
  1995. 'nickname' => $one['nickname'],
  1996. 'group_name' => $groupNameMap[$one['id']] ?? '',
  1997. 'mobile' => mask_phone($one['mobile']),
  1998. ];
  1999. }
  2000. return $out;
  2001. }
  2002. /**
  2003. * @param int[] $adminIds
  2004. * @return array<int, string>
  2005. */
  2006. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2007. {
  2008. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2009. if ($adminIds === []) {
  2010. return [];
  2011. }
  2012. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2013. try {
  2014. $rows = Db::name('auth_group_access')
  2015. ->alias('aga')
  2016. ->join('auth_group ag', 'aga.group_id = ag.id')
  2017. ->where('aga.uid', 'in', $adminIds)
  2018. ->where('aga.group_id', 'in', $groupIds)
  2019. ->field('aga.uid,ag.name')
  2020. ->order('aga.uid', 'asc')
  2021. ->order('aga.group_id', 'asc')
  2022. ->select();
  2023. } catch (\Throwable $e) {
  2024. return [];
  2025. }
  2026. if (!is_array($rows)) {
  2027. return [];
  2028. }
  2029. $out = [];
  2030. foreach ($rows as $row) {
  2031. if (!is_array($row)) {
  2032. continue;
  2033. }
  2034. $uid = (int)($row['uid'] ?? 0);
  2035. $name = trim((string)($row['name'] ?? ''));
  2036. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2037. continue;
  2038. }
  2039. $out[$uid] = $name;
  2040. }
  2041. return $out;
  2042. }
  2043. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2044. {
  2045. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2046. }
  2047. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2048. {
  2049. return 'procuremen_bidopen_wait_' . $adminId;
  2050. }
  2051. protected function renderBidOpenVerifySms(string $code): string
  2052. {
  2053. $tpl = '';
  2054. try {
  2055. $row = $this->loadNotifyTemplateRow('bid_open');
  2056. if (is_array($row)) {
  2057. $tpl = trim((string)($row['content'] ?? ''));
  2058. }
  2059. } catch (\Throwable $e) {
  2060. $tpl = '';
  2061. }
  2062. if ($tpl === '') {
  2063. $tpl = '【可集达】您的短信验证码是{code}';
  2064. }
  2065. return str_replace('{code}', $code, $tpl);
  2066. }
  2067. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2068. {
  2069. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2070. }
  2071. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2072. {
  2073. $code = trim($code);
  2074. if (!preg_match('/^\d{6}$/', $code)) {
  2075. return false;
  2076. }
  2077. $mock = Config::get('mproc.mock_sms_code');
  2078. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2079. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2080. return true;
  2081. }
  2082. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2083. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2084. return false;
  2085. }
  2086. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2087. return true;
  2088. }
  2089. /**
  2090. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2091. */
  2092. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2093. {
  2094. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2095. if ($ccydh === '') {
  2096. throw new \InvalidArgumentException('订单号无效');
  2097. }
  2098. $this->ensurePurchaseOrderBidOpenTable();
  2099. list($operatorId, $operatorName) = $this->GetUseName();
  2100. $now = date('Y-m-d H:i:s');
  2101. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2102. $payload = [
  2103. 'ccydh' => $ccydh,
  2104. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2105. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2106. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2107. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2108. 'operator_id' => (int)$operatorId,
  2109. 'operator_name' => trim((string)$operatorName),
  2110. 'createtime' => $now,
  2111. ];
  2112. if (is_array($exists)) {
  2113. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2114. } else {
  2115. Db::table('purchase_order_bid_open')->insert($payload);
  2116. }
  2117. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2118. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2119. $orderPart = '(订单' . $ccydh . ')';
  2120. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2121. $seenSid = [];
  2122. foreach ($bundle['pos'] ?? [] as $poRow) {
  2123. if (!is_array($poRow)) {
  2124. continue;
  2125. }
  2126. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2127. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2128. continue;
  2129. }
  2130. $seenSid[$sid] = true;
  2131. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2132. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2133. }
  2134. if ($seenSid === []) {
  2135. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2136. if ($this->isValidScydgyRowId($anchor)) {
  2137. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2138. }
  2139. }
  2140. }
  2141. /**
  2142. * 报价行展示字段默认值(模板安全访问)
  2143. *
  2144. * @param array<string, mixed> $line
  2145. * @return array<string, mixed>
  2146. */
  2147. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2148. {
  2149. if (!array_key_exists('amount_quote_pending', $line)) {
  2150. $line['amount_quote_pending'] = 0;
  2151. }
  2152. if (!array_key_exists('delivery_quote_pending', $line)) {
  2153. $line['delivery_quote_pending'] = 0;
  2154. }
  2155. if (!array_key_exists('quote_before_deadline', $line)) {
  2156. $line['quote_before_deadline'] = 0;
  2157. }
  2158. if (!array_key_exists('amount_filled', $line)) {
  2159. $line['amount_filled'] = 0;
  2160. }
  2161. if (!array_key_exists('delivery_filled', $line)) {
  2162. $line['delivery_filled'] = 0;
  2163. }
  2164. return $line;
  2165. }
  2166. /**
  2167. * 审核弹窗:按供应商汇总报价明细
  2168. *
  2169. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2170. * @return array<int, array<string, mixed>>
  2171. */
  2172. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2173. {
  2174. $sids = [];
  2175. foreach ($bundle['pos'] ?? [] as $po) {
  2176. if (!is_array($po)) {
  2177. continue;
  2178. }
  2179. $sid = (int)($po['scydgy_id'] ?? 0);
  2180. if ($this->isValidScydgyRowId($sid)) {
  2181. $sids[$sid] = true;
  2182. }
  2183. }
  2184. if ($sids === []) {
  2185. return [];
  2186. }
  2187. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2188. $gymcMap = [];
  2189. $qtyBySid = [];
  2190. $orderedSids = [];
  2191. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2192. if (!is_array($mr)) {
  2193. continue;
  2194. }
  2195. $gid = $this->extractScydgyRowId($mr);
  2196. if ($this->isValidScydgyRowId($gid)) {
  2197. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2198. $orderedSids[] = $gid;
  2199. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2200. if ($qty === '') {
  2201. $qty = trim((string)($mr['NGZL'] ?? ''));
  2202. }
  2203. $qtyBySid[$gid] = $qty;
  2204. }
  2205. }
  2206. foreach ($bundle['pos'] ?? [] as $po) {
  2207. if (!is_array($po)) {
  2208. continue;
  2209. }
  2210. $gid = (int)($po['scydgy_id'] ?? 0);
  2211. if ($this->isValidScydgyRowId($gid)) {
  2212. $nm = trim((string)($po['CGYMC'] ?? ''));
  2213. if ($nm !== '') {
  2214. $gymcMap[$gid] = $nm;
  2215. }
  2216. if (!in_array($gid, $orderedSids, true)) {
  2217. $orderedSids[] = $gid;
  2218. }
  2219. }
  2220. }
  2221. try {
  2222. $detailsQuery = Db::table('purchase_order_detail')
  2223. ->where('scydgy_id', 'in', array_keys($sids));
  2224. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2225. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2226. } catch (\Throwable $e) {
  2227. try {
  2228. $detailsQuery = Db::table('purchase_order_detail')
  2229. ->where('scydgy_id', 'in', array_keys($sids));
  2230. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2231. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2232. } catch (\Throwable $e2) {
  2233. $details = [];
  2234. }
  2235. }
  2236. if (!is_array($details)) {
  2237. $details = [];
  2238. }
  2239. $byCompany = [];
  2240. foreach ($details as $d) {
  2241. if (!is_array($d)) {
  2242. continue;
  2243. }
  2244. $cn = trim((string)($d['company_name'] ?? ''));
  2245. if ($cn === '') {
  2246. continue;
  2247. }
  2248. if (!isset($byCompany[$cn])) {
  2249. $ph = trim((string)($d['phone'] ?? ''));
  2250. $username = trim((string)($d['username'] ?? ''));
  2251. if ($username === '') {
  2252. $username = $this->resolveCustomerContactName($ph, $cn);
  2253. }
  2254. $byCompany[$cn] = [
  2255. 'name' => $cn,
  2256. 'email' => trim((string)($d['email'] ?? '')),
  2257. 'phone' => $ph,
  2258. 'username' => $username,
  2259. 'remark' => '',
  2260. 'has_quote' => false,
  2261. 'lines_map' => [],
  2262. ];
  2263. }
  2264. if ($byCompany[$cn]['remark'] === '') {
  2265. $rm = '';
  2266. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2267. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2268. $rm = trim((string)$d[$rk]);
  2269. break;
  2270. }
  2271. }
  2272. if ($rm !== '') {
  2273. $byCompany[$cn]['remark'] = $rm;
  2274. }
  2275. }
  2276. $sid = (int)($d['scydgy_id'] ?? 0);
  2277. $am = trim((string)($d['amount'] ?? ''));
  2278. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2279. if ($gymc === '') {
  2280. $gymc = '工序';
  2281. }
  2282. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2283. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2284. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2285. $deliveryShow = $deliveryRaw;
  2286. }
  2287. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2288. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2289. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2290. $subtotal = null;
  2291. if ($amountNum !== null) {
  2292. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2293. }
  2294. $unitPriceText = $amountFilled
  2295. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2296. : '未填写';
  2297. $lineRow = [
  2298. 'cgymc' => $gymc,
  2299. 'amount' => $am,
  2300. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2301. 'amount_filled' => $amountFilled,
  2302. 'unit_price_text' => $unitPriceText,
  2303. 'delivery' => $deliveryRaw,
  2304. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2305. 'delivery_filled' => $deliveryFilled,
  2306. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2307. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2308. 'subtotal_num' => $subtotal,
  2309. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2310. 'is_quoted' => $amountFilled,
  2311. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2312. ];
  2313. if (!$quoteVisible) {
  2314. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2315. }
  2316. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2317. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2318. }
  2319. foreach ($byCompany as $cn => $g) {
  2320. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2321. $lines = [];
  2322. $usedSids = [];
  2323. foreach ($orderedSids as $sid) {
  2324. if (!isset($linesMap[$sid])) {
  2325. continue;
  2326. }
  2327. $lines[] = $linesMap[$sid];
  2328. $usedSids[$sid] = true;
  2329. }
  2330. foreach ($linesMap as $sid => $ln) {
  2331. if (isset($usedSids[$sid])) {
  2332. continue;
  2333. }
  2334. $lines[] = $ln;
  2335. }
  2336. $total = count($lines);
  2337. $quoted = 0;
  2338. $groupTotal = 0.0;
  2339. $groupHasTotal = false;
  2340. if ($quoteVisible) {
  2341. foreach ($lines as $ln) {
  2342. $am = trim((string)($ln['amount'] ?? ''));
  2343. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2344. $quoted++;
  2345. }
  2346. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2347. $groupTotal += (float)$ln['subtotal_num'];
  2348. $groupHasTotal = true;
  2349. }
  2350. }
  2351. }
  2352. unset($byCompany[$cn]['lines_map']);
  2353. $byCompany[$cn]['lines'] = $lines;
  2354. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2355. $byCompany[$cn]['line_count'] = $total;
  2356. $byCompany[$cn]['has_total'] = $total > 0;
  2357. $byCompany[$cn]['has_remark'] = $total > 0;
  2358. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2359. // 工序行 + 备注行 + 总计行
  2360. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2361. }
  2362. return array_values($byCompany);
  2363. }
  2364. /**
  2365. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2366. *
  2367. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2368. * @return array<int, array<string, mixed>>
  2369. */
  2370. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2371. {
  2372. $sids = [];
  2373. $poIdMap = [];
  2374. foreach ($bundle['pos'] ?? [] as $po) {
  2375. if (!is_array($po)) {
  2376. continue;
  2377. }
  2378. $sid = (int)($po['scydgy_id'] ?? 0);
  2379. if ($this->isValidScydgyRowId($sid)) {
  2380. $sids[$sid] = true;
  2381. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2382. }
  2383. }
  2384. if ($sids === []) {
  2385. return [];
  2386. }
  2387. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2388. $gymcMap = [];
  2389. $qtyBySid = [];
  2390. $orderedSids = [];
  2391. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2392. if (!is_array($mr)) {
  2393. continue;
  2394. }
  2395. $gid = $this->extractScydgyRowId($mr);
  2396. if ($this->isValidScydgyRowId($gid)) {
  2397. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2398. $orderedSids[] = $gid;
  2399. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2400. if ($qty === '') {
  2401. $qty = trim((string)($mr['NGZL'] ?? ''));
  2402. }
  2403. $qtyBySid[$gid] = $qty;
  2404. }
  2405. }
  2406. foreach ($bundle['pos'] ?? [] as $po) {
  2407. if (!is_array($po)) {
  2408. continue;
  2409. }
  2410. $gid = (int)($po['scydgy_id'] ?? 0);
  2411. if ($this->isValidScydgyRowId($gid)) {
  2412. $nm = trim((string)($po['CGYMC'] ?? ''));
  2413. if ($nm !== '') {
  2414. $gymcMap[$gid] = $nm;
  2415. }
  2416. }
  2417. }
  2418. try {
  2419. $details = Db::table('purchase_order_detail')
  2420. ->where('scydgy_id', 'in', array_keys($sids))
  2421. ->order('company_name', 'asc')
  2422. ->order('id', 'asc')
  2423. ->select();
  2424. } catch (\Throwable $e) {
  2425. try {
  2426. $details = Db::table('purchase_order_detail')
  2427. ->where('scydgy_id', 'in', array_keys($sids))
  2428. ->order('company_name', 'asc')
  2429. ->order('ID', 'asc')
  2430. ->select();
  2431. } catch (\Throwable $e2) {
  2432. $details = [];
  2433. }
  2434. }
  2435. if (!is_array($details)) {
  2436. $details = [];
  2437. }
  2438. $byCompany = [];
  2439. foreach ($details as $d) {
  2440. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2441. continue;
  2442. }
  2443. $cn = trim((string)($d['company_name'] ?? ''));
  2444. if ($cn === '') {
  2445. continue;
  2446. }
  2447. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2448. $sid = (int)($d['scydgy_id'] ?? 0);
  2449. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2450. continue;
  2451. }
  2452. if (!isset($byCompany[$cn])) {
  2453. $ph = trim((string)($d['phone'] ?? ''));
  2454. $username = trim((string)($d['username'] ?? ''));
  2455. if ($username === '') {
  2456. $username = $this->resolveCustomerContactName($ph, $cn);
  2457. }
  2458. $byCompany[$cn] = [
  2459. 'name' => $cn,
  2460. 'email' => trim((string)($d['email'] ?? '')),
  2461. 'phone' => $ph,
  2462. 'username' => $username,
  2463. 'remark' => '',
  2464. 'pick_lines' => [],
  2465. 'detail_picks' => [],
  2466. ];
  2467. }
  2468. if ($byCompany[$cn]['remark'] === '') {
  2469. $rm = '';
  2470. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2471. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2472. $rm = trim((string)$d[$rk]);
  2473. break;
  2474. }
  2475. }
  2476. if ($rm !== '') {
  2477. $byCompany[$cn]['remark'] = $rm;
  2478. }
  2479. }
  2480. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2481. if ($gymc === '') {
  2482. $gymc = '工序';
  2483. }
  2484. $am = trim((string)($d['amount'] ?? ''));
  2485. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2486. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2487. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2488. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2489. $deliveryShow = $deliveryRaw;
  2490. }
  2491. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2492. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2493. $subtotal = null;
  2494. if ($amountNum !== null) {
  2495. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2496. }
  2497. $unitPriceText = $amountFilled
  2498. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2499. : '未填写';
  2500. $pickLine = [
  2501. 'cgymc' => $gymc,
  2502. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2503. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2504. 'amount_filled' => $amountFilled,
  2505. 'delivery_filled' => $deliveryFilled,
  2506. 'unit_price_text' => $unitPriceText,
  2507. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2508. 'subtotal_num' => $subtotal,
  2509. 'is_quoted' => $amountFilled,
  2510. ];
  2511. if (!$quoteVisible) {
  2512. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2513. }
  2514. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2515. $byCompany[$cn]['detail_picks'][$sid] = [
  2516. 'scydgy_id' => $sid,
  2517. 'detail_id' => $detailId,
  2518. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2519. 'cgymc' => $gymc,
  2520. ];
  2521. }
  2522. $out = [];
  2523. foreach ($byCompany as $g) {
  2524. $pickLinesMap = $g['pick_lines'] ?? [];
  2525. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2526. continue;
  2527. }
  2528. $pickLines = [];
  2529. $usedLineSids = [];
  2530. foreach ($orderedSids as $sid) {
  2531. if (!isset($pickLinesMap[$sid])) {
  2532. continue;
  2533. }
  2534. $pickLines[] = $pickLinesMap[$sid];
  2535. $usedLineSids[$sid] = true;
  2536. }
  2537. foreach ($pickLinesMap as $sid => $ln) {
  2538. if (isset($usedLineSids[$sid])) {
  2539. continue;
  2540. }
  2541. $pickLines[] = $ln;
  2542. }
  2543. $groupTotal = 0.0;
  2544. $groupHasTotal = false;
  2545. if ($quoteVisible) {
  2546. foreach ($pickLines as $ln) {
  2547. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2548. $groupTotal += (float)$ln['subtotal_num'];
  2549. $groupHasTotal = true;
  2550. }
  2551. }
  2552. }
  2553. $lineCount = count($pickLines);
  2554. $g['pick_lines'] = $pickLines;
  2555. $g['line_count'] = $lineCount;
  2556. $g['has_total'] = $lineCount > 0;
  2557. $g['has_remark'] = $lineCount > 0;
  2558. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2559. // 工序行 + 备注行 + 总计行
  2560. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2561. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2562. $detailPicks = [];
  2563. $usedPickSids = [];
  2564. foreach ($orderedSids as $sid) {
  2565. if (!isset($detailPicksMap[$sid])) {
  2566. continue;
  2567. }
  2568. $detailPicks[] = $detailPicksMap[$sid];
  2569. $usedPickSids[$sid] = true;
  2570. }
  2571. foreach ($detailPicksMap as $sid => $dp) {
  2572. if (isset($usedPickSids[$sid])) {
  2573. continue;
  2574. }
  2575. $detailPicks[] = $dp;
  2576. }
  2577. $g['detail_picks'] = $detailPicks;
  2578. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2579. unset($g['detail_picks']);
  2580. $out[] = $g;
  2581. }
  2582. return $out;
  2583. }
  2584. /**
  2585. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2586. * @return array<int, int[]> scydgy_id => detail_id[]
  2587. */
  2588. protected function mapDetailIdsByScydgyId(array $details): array
  2589. {
  2590. $out = [];
  2591. foreach ($details as $d) {
  2592. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2593. continue;
  2594. }
  2595. $sid = (int)($d['scydgy_id'] ?? 0);
  2596. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2597. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2598. continue;
  2599. }
  2600. if (!isset($out[$sid])) {
  2601. $out[$sid] = [];
  2602. }
  2603. $out[$sid][] = $pk;
  2604. }
  2605. foreach ($out as $sid => $ids) {
  2606. $out[$sid] = array_values(array_unique($ids));
  2607. }
  2608. return $out;
  2609. }
  2610. /**
  2611. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2612. *
  2613. * @param array<string, mixed> $dbRow
  2614. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2615. */
  2616. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2617. {
  2618. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2619. $r = [
  2620. 'ID' => $sid,
  2621. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2622. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2623. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2624. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2625. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2626. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2627. 'CDW' => $dbRow['CDW'] ?? '',
  2628. 'NGZL' => $dbRow['NGZL'] ?? '',
  2629. 'CDF' => $dbRow['CDF'] ?? '',
  2630. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2631. 'MBZ' => $dbRow['MBZ'] ?? '',
  2632. 'bwjg' => $dbRow['bwjg'] ?? '',
  2633. 'iStatus' => $dbRow['iStatus'] ?? '',
  2634. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2635. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2636. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2637. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2638. 'dStamp' => $dbRow['dStamp'] ?? '',
  2639. 'pick_time' => $dbRow['pick_time'] ?? '',
  2640. ];
  2641. if ($sid > 0 && isset($dStampMap[$sid])) {
  2642. $t = trim((string)$dStampMap[$sid]);
  2643. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2644. $r['dStamp'] = $dStampMap[$sid];
  2645. }
  2646. }
  2647. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2648. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2649. $ct = $dbRow['createtime'];
  2650. if (is_numeric($ct) && (int)$ct > 946684800) {
  2651. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2652. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2653. $r['dStamp'] = trim($ct);
  2654. }
  2655. }
  2656. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2657. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2658. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2659. $fallback = trim((string)($r['dStamp'] ?? ''));
  2660. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2661. $r['dputrecord'] = $fallback;
  2662. }
  2663. }
  2664. if (array_key_exists('id', $dbRow)) {
  2665. $r['purchase_order_id'] = (int)$dbRow['id'];
  2666. }
  2667. if ($sid < 0) {
  2668. $r['_is_manual'] = 1;
  2669. }
  2670. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2671. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2672. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2673. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2674. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2675. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2676. $r['pick_time'] = $pickFallback;
  2677. break;
  2678. }
  2679. }
  2680. }
  2681. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2682. if ($pickNm !== '') {
  2683. $r['pick_company_name'] = $pickNm;
  2684. $r['picked_supplier_name'] = $pickNm;
  2685. }
  2686. return $r;
  2687. }
  2688. /**
  2689. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2690. *
  2691. * @return array<int, array<string, mixed>>
  2692. */
  2693. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2694. {
  2695. $pool = [];
  2696. if (!is_array($dbRows) || $dbRows === []) {
  2697. return $pool;
  2698. }
  2699. $dStampMap = [];
  2700. $sidList = [];
  2701. foreach ($dbRows as $tmpRow) {
  2702. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2703. $sid = (int)$tmpRow['scydgy_id'];
  2704. if ($sid > 0) {
  2705. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2706. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2707. $sidList[$sid] = true;
  2708. }
  2709. }
  2710. }
  2711. }
  2712. if ($sidList !== []) {
  2713. try {
  2714. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2715. } catch (\Throwable $e) {
  2716. $dStampMap = [];
  2717. }
  2718. }
  2719. foreach ($dbRows as $dbRow) {
  2720. if (!is_array($dbRow)) {
  2721. continue;
  2722. }
  2723. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2724. }
  2725. return $pool;
  2726. }
  2727. /**
  2728. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2729. *
  2730. * @param int[] $scydgyIds
  2731. * @return array<int, array<string, mixed>>
  2732. */
  2733. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2734. {
  2735. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2736. if ($scydgyIds === []) {
  2737. return [];
  2738. }
  2739. try {
  2740. $list = Db::table('purchase_order_detail')
  2741. ->where('scydgy_id', 'in', $scydgyIds)
  2742. ->field('scydgy_id,company_name,amount,delivery')
  2743. ->select();
  2744. } catch (\Throwable $e) {
  2745. $list = [];
  2746. }
  2747. return is_array($list) ? $list : [];
  2748. }
  2749. /**
  2750. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2751. *
  2752. * @param int[] $scydgyIds
  2753. * @param array<int, array<string, mixed>> $allRows
  2754. * @return array{cnt:int, amt:int, deliv:int}
  2755. */
  2756. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2757. {
  2758. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2759. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2760. if ($scydgyIds === [] || $allRows === []) {
  2761. return $out;
  2762. }
  2763. $idSet = array_flip($scydgyIds);
  2764. $all = [];
  2765. $withAmt = [];
  2766. $withDeliv = [];
  2767. foreach ($allRows as $r) {
  2768. if (!is_array($r)) {
  2769. continue;
  2770. }
  2771. $sid = (int)($r['scydgy_id'] ?? 0);
  2772. if (!isset($idSet[$sid])) {
  2773. continue;
  2774. }
  2775. $cn = trim((string)($r['company_name'] ?? ''));
  2776. if ($cn === '') {
  2777. continue;
  2778. }
  2779. $all[$cn] = true;
  2780. $am = $r['amount'] ?? null;
  2781. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2782. $withAmt[$cn] = true;
  2783. }
  2784. $dv = $r['delivery'] ?? null;
  2785. if ($dv !== null && trim((string)$dv) !== '') {
  2786. $withDeliv[$cn] = true;
  2787. }
  2788. }
  2789. return [
  2790. 'cnt' => count($all),
  2791. 'amt' => count($withAmt),
  2792. 'deliv' => count($withDeliv),
  2793. ];
  2794. }
  2795. /**
  2796. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2797. *
  2798. * @param int[] $scydgyIds
  2799. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2800. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2801. */
  2802. protected function OrderDetailSummary(array $scydgyIds)
  2803. {
  2804. $out = [];
  2805. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2806. if ($scydgyIds === []) {
  2807. return $out;
  2808. }
  2809. $list = [];
  2810. try {
  2811. $list = Db::table('purchase_order_detail')
  2812. ->where('scydgy_id', 'in', $scydgyIds)
  2813. ->field('id,scydgy_id,amount,delivery')
  2814. ->select();
  2815. } catch (\Throwable $e) {
  2816. $list = [];
  2817. }
  2818. if (!is_array($list)) {
  2819. return $out;
  2820. }
  2821. foreach ($list as $r) {
  2822. if (!is_array($r)) {
  2823. continue;
  2824. }
  2825. $ids = (int)($r['scydgy_id'] ?? 0);
  2826. if (!$this->isValidScydgyRowId($ids)) {
  2827. continue;
  2828. }
  2829. if (!isset($out[$ids])) {
  2830. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2831. }
  2832. $out[$ids]['cnt']++;
  2833. $am = $r['amount'] ?? null;
  2834. if ($am !== null && $am !== '') {
  2835. if (!(is_string($am) && trim($am) === '')) {
  2836. $out[$ids]['amt']++;
  2837. }
  2838. }
  2839. $dv = $r['delivery'] ?? null;
  2840. if ($dv !== null && trim((string)$dv) !== '') {
  2841. $out[$ids]['deliv']++;
  2842. }
  2843. }
  2844. return $out;
  2845. }
  2846. /**
  2847. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2848. *
  2849. * @return array
  2850. */
  2851. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2852. {
  2853. $strContains = function ($haystack, $needle) {
  2854. if ($needle === '') {
  2855. return false;
  2856. }
  2857. $haystack = (string)$haystack;
  2858. if (function_exists('mb_stripos')) {
  2859. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2860. }
  2861. return stripos($haystack, $needle) !== false;
  2862. };
  2863. $stripAlias = function ($f) {
  2864. return preg_replace('/^[ab]\./i', '', (string)$f);
  2865. };
  2866. $searchColNames = [];
  2867. foreach (explode(',', $this->searchFields) as $colRaw) {
  2868. $c = $stripAlias(trim($colRaw));
  2869. if ($c !== '') {
  2870. $searchColNames[] = $c;
  2871. }
  2872. }
  2873. $filtered = [];
  2874. foreach ($pool as $r) {
  2875. if (!is_array($r)) {
  2876. continue;
  2877. }
  2878. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2879. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2880. if (!$isManual) {
  2881. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2882. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2883. continue;
  2884. }
  2885. if ($applyMonthRange) {
  2886. $mo = (int)$m[2];
  2887. if ($mo < 1 || $mo > 12) {
  2888. continue;
  2889. }
  2890. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2891. $rowMonthStart = $ymRow . '-01 00:00:00';
  2892. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2893. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2894. continue;
  2895. }
  2896. }
  2897. } elseif ($applyMonthRange) {
  2898. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2899. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2900. $ds = $listTime;
  2901. }
  2902. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2903. continue;
  2904. }
  2905. $mo = (int)$m[2];
  2906. if ($mo < 1 || $mo > 12) {
  2907. continue;
  2908. }
  2909. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2910. $rowMonthStart = $ymRow . '-01 00:00:00';
  2911. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2912. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2913. continue;
  2914. }
  2915. }
  2916. if ($search !== '') {
  2917. $hitSearch = false;
  2918. foreach ($searchColNames as $c) {
  2919. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2920. if ($cell !== '' && $strContains($cell, $search)) {
  2921. $hitSearch = true;
  2922. break;
  2923. }
  2924. }
  2925. if (!$hitSearch) {
  2926. continue;
  2927. }
  2928. }
  2929. foreach ($filterArr as $fk => $fv) {
  2930. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2931. continue;
  2932. }
  2933. if (is_array($fv)) {
  2934. continue;
  2935. }
  2936. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2937. continue;
  2938. }
  2939. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2940. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2941. $field = $stripAlias($fk);
  2942. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2943. $cellStr = trim((string)$cell);
  2944. switch ($sym) {
  2945. case '=':
  2946. if ((string)$cell !== (string)$fv) {
  2947. continue 3;
  2948. }
  2949. break;
  2950. case '<>':
  2951. if ((string)$cell === (string)$fv) {
  2952. continue 3;
  2953. }
  2954. break;
  2955. case 'LIKE':
  2956. case 'NOT LIKE':
  2957. $needle = trim((string)$fv);
  2958. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2959. if ($sym === 'LIKE' && !$hit) {
  2960. continue 3;
  2961. }
  2962. if ($sym === 'NOT LIKE' && $hit) {
  2963. continue 3;
  2964. }
  2965. break;
  2966. case '>':
  2967. case '>=':
  2968. case '<':
  2969. case '<=':
  2970. if (!is_numeric($cell) && $cellStr === '') {
  2971. continue 3;
  2972. }
  2973. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2974. $vv = (float)$fv;
  2975. if ($sym === '>' && !($cv > $vv)) {
  2976. continue 3;
  2977. }
  2978. if ($sym === '>=' && !($cv >= $vv)) {
  2979. continue 3;
  2980. }
  2981. if ($sym === '<' && !($cv < $vv)) {
  2982. continue 3;
  2983. }
  2984. if ($sym === '<=' && !($cv <= $vv)) {
  2985. continue 3;
  2986. }
  2987. break;
  2988. case 'RANGE':
  2989. case 'NOT RANGE':
  2990. case 'BETWEEN':
  2991. case 'NOT BETWEEN':
  2992. case 'BETWEEN TIME':
  2993. case 'NOT BETWEEN TIME':
  2994. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2995. $rawR = str_replace(' - ', ',', $rawR);
  2996. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2997. if (count($arr) < 2) {
  2998. break;
  2999. }
  3000. $lo = $arr[0];
  3001. $hi = $arr[1];
  3002. if ($lo === '' && $hi === '') {
  3003. break;
  3004. }
  3005. $isNot = (strpos($sym, 'NOT') !== false);
  3006. if ($lo === '') {
  3007. $in = ($cellStr !== '' && $cellStr <= $hi);
  3008. if ($isNot ? $in : !$in) {
  3009. continue 3;
  3010. }
  3011. break;
  3012. }
  3013. if ($hi === '') {
  3014. $in = ($cellStr !== '' && $cellStr >= $lo);
  3015. if ($isNot ? $in : !$in) {
  3016. continue 3;
  3017. }
  3018. break;
  3019. }
  3020. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3021. if ($isNot ? $in : !$in) {
  3022. continue 3;
  3023. }
  3024. break;
  3025. case 'NULL':
  3026. case 'IS NULL':
  3027. if ($cell !== null && $cell !== '') {
  3028. continue 3;
  3029. }
  3030. break;
  3031. case 'NOT NULL':
  3032. case 'IS NOT NULL':
  3033. if ($cell === null || $cell === '') {
  3034. continue 3;
  3035. }
  3036. break;
  3037. default:
  3038. break;
  3039. }
  3040. }
  3041. $filtered[] = $r;
  3042. }
  3043. return $filtered;
  3044. }
  3045. /**
  3046. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3047. */
  3048. public function snapshotToProcure()
  3049. {
  3050. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3051. $this->error(__('Invalid parameters'));
  3052. }
  3053. $row = json_decode($this->request->post('row_json', ''), true);
  3054. if (!is_array($row)) {
  3055. $this->error(__('Invalid parameters'));
  3056. }
  3057. try {
  3058. $ids = $this->extractScydgyRowId($row);
  3059. if (!$this->isValidScydgyRowId($ids)) {
  3060. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3061. }
  3062. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3063. $data = [
  3064. 'scydgy_id' => $ids,
  3065. 'CCYDH' => $row['CCYDH'] ?? null,
  3066. 'CYJMC' => $row['CYJMC'] ?? null,
  3067. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3068. 'CDXMC' => $row['CDXMC'] ?? null,
  3069. 'CGYBH' => $row['CGYBH'] ?? null,
  3070. 'CGYMC' => $row['CGYMC'] ?? null,
  3071. 'CDW' => $row['CDW'] ?? null,
  3072. 'NGZL' => $row['NGZL'] ?? null,
  3073. 'CDF' => $row['CDF'] ?? null,
  3074. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3075. 'MBZ' => $row['MBZ'] ?? null,
  3076. 'bwjg' => $row['bwjg'] ?? null,
  3077. 'iStatus' => $row['iStatus'] ?? null,
  3078. 'dStamp' => $row['dStamp'] ?? null,
  3079. 'dputrecord' => $row['dputrecord'] ?? null,
  3080. 'cywyxm' => $row['cywyxm'] ?? null,
  3081. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3082. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3083. ];
  3084. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3085. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3086. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3087. $this->success('操作成功');
  3088. return;
  3089. }
  3090. if ($exists) {
  3091. $upd = $data;
  3092. unset($upd['scydgy_id'], $upd['status']);
  3093. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3094. } else {
  3095. // 新增:不写 status(空/走库默认);仅写创建时间
  3096. $data['createtime'] = date('Y-m-d H:i:s');
  3097. Db::table('purchase_order')->insert($data);
  3098. }
  3099. } catch (\Throwable $e) {
  3100. $this->error($e->getMessage());
  3101. }
  3102. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3103. $this->success('操作成功');
  3104. }
  3105. /**
  3106. * 未发列表
  3107. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3108. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3109. */
  3110. public function completeDirectly()
  3111. {
  3112. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3113. $this->error(__('参数错误'));
  3114. }
  3115. if (!$this->procuremenCanComplete()) {
  3116. $this->error(__('You have no permission'));
  3117. }
  3118. $row = json_decode($this->request->post('row_json', ''), true);
  3119. if (!is_array($row)) {
  3120. $this->error(__('Invalid parameters'));
  3121. }
  3122. $finishRaw = $this->request->post('finish', '1');
  3123. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3124. $poIdLog = null;
  3125. try {
  3126. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3127. $ids = $this->extractScydgyRowId($row);
  3128. if (!$this->isValidScydgyRowId($ids)) {
  3129. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3130. }
  3131. if ($asComplete) {
  3132. $this->assertPickRowCanComplete($ids, $row);
  3133. }
  3134. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3135. $data = [
  3136. 'scydgy_id' => $ids,
  3137. 'CCYDH' => $row['CCYDH'] ?? null,
  3138. 'CYJMC' => $row['CYJMC'] ?? null,
  3139. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3140. 'CDXMC' => $row['CDXMC'] ?? null,
  3141. 'CGYBH' => $row['CGYBH'] ?? null,
  3142. 'CGYMC' => $row['CGYMC'] ?? null,
  3143. 'CDW' => $row['CDW'] ?? null,
  3144. 'NGZL' => $row['NGZL'] ?? null,
  3145. 'CDF' => $row['CDF'] ?? null,
  3146. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3147. 'MBZ' => $row['MBZ'] ?? null,
  3148. 'bwjg' => $row['bwjg'] ?? null,
  3149. 'iStatus' => $row['iStatus'] ?? null,
  3150. 'dStamp' => $row['dStamp'] ?? null,
  3151. 'dputrecord' => $row['dputrecord'] ?? null,
  3152. 'cywyxm' => $row['cywyxm'] ?? null,
  3153. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3154. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3155. ];
  3156. if ($asComplete) {
  3157. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3158. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3159. }
  3160. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3161. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3162. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3163. $this->success('操作成功');
  3164. return;
  3165. }
  3166. if ($exists) {
  3167. $upd = $data;
  3168. unset($upd['scydgy_id']);
  3169. if (!$asComplete) {
  3170. unset($upd['status']);
  3171. }
  3172. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3173. } else {
  3174. // 新增:不写 status;完结时 $data 已含 status=1
  3175. $data['createtime'] = date('Y-m-d H:i:s');
  3176. Db::table('purchase_order')->insert($data);
  3177. }
  3178. } catch (\Throwable $e) {
  3179. $this->error($e->getMessage());
  3180. }
  3181. try {
  3182. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3183. if (is_array($rpo)) {
  3184. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3185. $poIdLog = $tid > 0 ? $tid : null;
  3186. }
  3187. } catch (\Throwable $e) {
  3188. $poIdLog = null;
  3189. }
  3190. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3191. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3192. if ($asComplete) {
  3193. $this->addOrderLog(
  3194. $ids,
  3195. 'mark_complete',
  3196. '点击「完结」,已标记为已完结',
  3197. $poIdLog
  3198. );
  3199. try {
  3200. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3201. if ($pdfPublicPath === '') {
  3202. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3203. }
  3204. } catch (\Throwable $e) {
  3205. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3206. }
  3207. } else {
  3208. $this->addOrderLog(
  3209. $ids,
  3210. 'save_qty_price',
  3211. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3212. $poIdLog
  3213. );
  3214. }
  3215. $this->pickHiddenScydgySetCache = null;
  3216. $this->success("操作成功");
  3217. }
  3218. /**
  3219. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3220. *
  3221. * @param array<int, array> $rows 引用传递当前页行
  3222. */
  3223. protected function mergePurchaseOrder(array &$rows)
  3224. {
  3225. if ($rows === []) {
  3226. return;
  3227. }
  3228. $ids = [];
  3229. foreach ($rows as $rw) {
  3230. if (!is_array($rw)) {
  3231. continue;
  3232. }
  3233. $id = (int)($rw['ID'] ?? 0);
  3234. if ($id > 0) {
  3235. $ids[$id] = true;
  3236. }
  3237. }
  3238. $idList = array_keys($ids);
  3239. if ($idList === []) {
  3240. return;
  3241. }
  3242. try {
  3243. $list = Db::table('purchase_order')
  3244. ->where('scydgy_id', 'in', $idList)
  3245. ->field('scydgy_id,This_quantity,ceilingPrice')
  3246. ->select();
  3247. } catch (\Throwable $e) {
  3248. return;
  3249. }
  3250. if (!is_array($list)) {
  3251. return;
  3252. }
  3253. $byId = [];
  3254. foreach ($list as $dbRow) {
  3255. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3256. continue;
  3257. }
  3258. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3259. }
  3260. foreach ($rows as &$rw) {
  3261. if (!is_array($rw)) {
  3262. continue;
  3263. }
  3264. $sid = (int)($rw['ID'] ?? 0);
  3265. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3266. continue;
  3267. }
  3268. $db = $byId[$sid];
  3269. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3270. if (array_key_exists('This_quantity', $db)) {
  3271. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3272. }
  3273. if (array_key_exists('ceilingPrice', $db)) {
  3274. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3275. } elseif (array_key_exists('ceiling_price', $db)) {
  3276. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3277. }
  3278. }
  3279. unset($rw);
  3280. }
  3281. /**
  3282. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3283. */
  3284. public function purchaseConfirmPick()
  3285. {
  3286. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3287. $this->error(__('Invalid parameters'));
  3288. }
  3289. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3290. $this->error(__('You have no permission'));
  3291. }
  3292. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3293. if ($batchRaw !== '') {
  3294. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3295. return;
  3296. }
  3297. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3298. $sid = (int)$scydgyId;
  3299. if (!$this->isValidScydgyRowId($sid)) {
  3300. $this->error('参数无效');
  3301. }
  3302. $parseIdList = function ($raw) {
  3303. if (is_array($raw)) {
  3304. $arr = $raw;
  3305. } else {
  3306. $decoded = json_decode((string)$raw, true);
  3307. $arr = is_array($decoded) ? $decoded : [];
  3308. }
  3309. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3310. };
  3311. $selectedRaw = $this->request->post('selected_ids', null);
  3312. if ($selectedRaw === null || $selectedRaw === '') {
  3313. $legacy = (int)$this->request->post('selected_id', 0);
  3314. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3315. } else {
  3316. $selectedIds = $parseIdList($selectedRaw);
  3317. }
  3318. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3319. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3320. try {
  3321. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3322. } catch (\InvalidArgumentException $e) {
  3323. $this->error($e->getMessage());
  3324. } catch (\Throwable $e) {
  3325. $this->error($e->getMessage());
  3326. }
  3327. $this->pickHiddenScydgySetCache = null;
  3328. $this->success('操作成功', '', $result);
  3329. }
  3330. /**
  3331. * 整单采购确认(多道工序一次提交)
  3332. */
  3333. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3334. {
  3335. $decoded = json_decode($batchRaw, true);
  3336. if (!is_array($decoded) || $decoded === []) {
  3337. $this->error('提交数据无效');
  3338. }
  3339. $picks = [];
  3340. foreach ($decoded as $item) {
  3341. if (!is_array($item)) {
  3342. continue;
  3343. }
  3344. $sid = (int)($item['scydgy_id'] ?? 0);
  3345. if (!$this->isValidScydgyRowId($sid)) {
  3346. continue;
  3347. }
  3348. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3349. if (!is_array($sel)) {
  3350. $sel = [(int)$sel];
  3351. }
  3352. $unsel = $item['unselected_ids'] ?? [];
  3353. if (!is_array($unsel)) {
  3354. $unsel = json_decode((string)$unsel, true);
  3355. $unsel = is_array($unsel) ? $unsel : [];
  3356. }
  3357. $picks[] = [
  3358. 'scydgy_id' => $sid,
  3359. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3360. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3361. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3362. ];
  3363. }
  3364. if ($picks === []) {
  3365. $this->error('提交数据无效');
  3366. }
  3367. Db::startTrans();
  3368. $results = [];
  3369. try {
  3370. foreach ($picks as $pick) {
  3371. $results[] = $this->runPurchaseConfirmPick(
  3372. (int)$pick['scydgy_id'],
  3373. $pick['selected_ids'],
  3374. $pick['unselected_ids'],
  3375. (int)$pick['purchase_order_id'],
  3376. false,
  3377. false
  3378. );
  3379. }
  3380. Db::commit();
  3381. } catch (\Throwable $e) {
  3382. Db::rollback();
  3383. $msg = $e->getMessage();
  3384. $this->error($msg !== '' ? $msg : '提交失败');
  3385. }
  3386. try {
  3387. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3388. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3389. } catch (\Throwable $e) {
  3390. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3391. }
  3392. $this->pickHiddenScydgySetCache = null;
  3393. $this->success('操作成功', '', ['batch' => $results]);
  3394. }
  3395. /**
  3396. * @return array<string, mixed>
  3397. */
  3398. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3399. {
  3400. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3401. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3402. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3403. $scydgyId = (string)$sid;
  3404. if ($selectedIds === []) {
  3405. throw new \InvalidArgumentException('请至少勾选一条明细');
  3406. }
  3407. $inter = array_intersect($selectedIds, $unselectedIds);
  3408. if ($inter !== []) {
  3409. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3410. }
  3411. $allIds = $this->purchaseOrderDetail($sid);
  3412. if ($allIds === []) {
  3413. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3414. }
  3415. foreach ($selectedIds as $id) {
  3416. if (!in_array($id, $allIds, true)) {
  3417. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3418. }
  3419. }
  3420. foreach ($unselectedIds as $id) {
  3421. if (!in_array($id, $allIds, true)) {
  3422. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3423. }
  3424. }
  3425. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3426. sort($union, SORT_NUMERIC);
  3427. $expect = $allIds;
  3428. sort($expect, SORT_NUMERIC);
  3429. if ($union !== $expect) {
  3430. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3431. }
  3432. if ($manageTransaction) {
  3433. Db::startTrans();
  3434. }
  3435. try {
  3436. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3437. $aff = 0;
  3438. try {
  3439. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3440. } catch (\Throwable $e) {
  3441. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3442. }
  3443. if ($aff < 1) {
  3444. throw new \Exception('更新选中状态失败');
  3445. }
  3446. $poPayload = [
  3447. 'status' => ProcuremenStatus::PO_COMPLETED,
  3448. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3449. ];
  3450. if ($purchaseOrderId > 0) {
  3451. $poAff = (int)Db::table('purchase_order')
  3452. ->where('id', $purchaseOrderId)
  3453. ->where('scydgy_id', $sid)
  3454. ->update($poPayload);
  3455. if ($poAff < 1) {
  3456. throw new \Exception('主表订单不存在或与工序行不匹配');
  3457. }
  3458. } else {
  3459. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3460. if ($poAff < 1) {
  3461. throw new \Exception('未找到');
  3462. }
  3463. }
  3464. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3465. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3466. if ($manageTransaction) {
  3467. Db::commit();
  3468. }
  3469. } catch (\Throwable $e) {
  3470. if ($manageTransaction) {
  3471. Db::rollback();
  3472. }
  3473. throw $e;
  3474. }
  3475. $poIdFinal = $purchaseOrderId;
  3476. if ($poIdFinal <= 0) {
  3477. try {
  3478. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3479. if (is_array($rpo)) {
  3480. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3481. }
  3482. } catch (\Throwable $e) {
  3483. $poIdFinal = 0;
  3484. }
  3485. }
  3486. $pickNames = [];
  3487. foreach ($selectedIds as $pid) {
  3488. $dr = $this->purchaseOrderDetai($sid, $pid);
  3489. $nm = trim((string)($dr['company_name'] ?? ''));
  3490. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3491. }
  3492. $this->addOrderLog(
  3493. $sid,
  3494. 'purchase_confirm',
  3495. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3496. $poIdFinal > 0 ? $poIdFinal : null
  3497. );
  3498. if ($sendNotifications) {
  3499. try {
  3500. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3501. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3502. 'scydgy_id' => $sid,
  3503. 'selected_ids' => $selectedIds,
  3504. 'unselected_ids' => $unselectedIds,
  3505. 'purchase_order_id' => $purchaseOrderId,
  3506. ]]);
  3507. } catch (\Throwable $e) {
  3508. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3509. }
  3510. }
  3511. Log::write(sprintf(
  3512. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3513. $scydgyId,
  3514. $purchaseOrderId,
  3515. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3516. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3517. ), 'notice');
  3518. $pdfPublicPath = '';
  3519. try {
  3520. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3521. } catch (\Throwable $e) {
  3522. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3523. }
  3524. return [
  3525. 'scydgy_id' => $scydgyId,
  3526. 'purchase_order_id' => $purchaseOrderId,
  3527. 'selected_ids' => $selectedIds,
  3528. 'unselected_ids' => $unselectedIds,
  3529. 'purchase_confirm_pdf' => $pdfPublicPath,
  3530. ];
  3531. }
  3532. /**
  3533. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3534. *
  3535. * @param int[]|string[] $scydgyIds
  3536. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3537. */
  3538. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3539. {
  3540. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3541. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3542. if ($scydgyIds === []) {
  3543. return $empty;
  3544. }
  3545. $pos = [];
  3546. try {
  3547. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3548. } catch (\Throwable $e) {
  3549. $rows = [];
  3550. }
  3551. if (is_array($rows)) {
  3552. foreach ($rows as $po) {
  3553. if (is_array($po)) {
  3554. $pos[] = $po;
  3555. }
  3556. }
  3557. }
  3558. if ($pos === []) {
  3559. return $empty;
  3560. }
  3561. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3562. return [
  3563. 'ccydh' => $ccydh,
  3564. 'pos' => $pos,
  3565. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3566. ];
  3567. }
  3568. /**
  3569. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3570. *
  3571. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3572. * @param array<int, array<string, mixed>> $picks
  3573. */
  3574. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3575. {
  3576. if ($picks === []) {
  3577. return;
  3578. }
  3579. $fallbackDetailId = 0;
  3580. $winners = [];
  3581. $losers = [];
  3582. foreach ($picks as $pick) {
  3583. if (!is_array($pick)) {
  3584. continue;
  3585. }
  3586. $sid = (int)($pick['scydgy_id'] ?? 0);
  3587. if (!$this->isValidScydgyRowId($sid)) {
  3588. continue;
  3589. }
  3590. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3591. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3592. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3593. $fallbackDetailId = (int)$selectedIds[0];
  3594. }
  3595. foreach ($selectedIds as $pid) {
  3596. $dr = $this->purchaseOrderDetai($sid, $pid);
  3597. if (!is_array($dr)) {
  3598. continue;
  3599. }
  3600. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3601. }
  3602. foreach ($unselectedIds as $pid) {
  3603. $dr = $this->purchaseOrderDetai($sid, $pid);
  3604. if (!is_array($dr)) {
  3605. continue;
  3606. }
  3607. $key = $this->notifySupplierDedupeKey($dr);
  3608. if (!isset($winners[$key])) {
  3609. $losers[$key] = $dr;
  3610. }
  3611. }
  3612. }
  3613. if ($winners === [] && $losers === []) {
  3614. return;
  3615. }
  3616. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3617. $sendSmsSafe = function ($phone, $content) {
  3618. $phone = trim((string)$phone);
  3619. if ($phone === '') {
  3620. return;
  3621. }
  3622. try {
  3623. $this->smsbao($phone, $content);
  3624. } catch (\Throwable $e) {
  3625. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3626. }
  3627. };
  3628. foreach ($winners as $dr) {
  3629. $cname = trim((string)($dr['company_name'] ?? ''));
  3630. $ph = trim((string)($dr['phone'] ?? ''));
  3631. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3632. 'company_name' => $cname,
  3633. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3634. 'phone' => $ph,
  3635. ]));
  3636. $sendSmsSafe($ph, $sms);
  3637. }
  3638. foreach ($losers as $dr) {
  3639. $cname = trim((string)($dr['company_name'] ?? ''));
  3640. $ph = trim((string)($dr['phone'] ?? ''));
  3641. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3642. 'company_name' => $cname,
  3643. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3644. 'phone' => $ph,
  3645. ]));
  3646. $sendSmsSafe($ph, $sms);
  3647. }
  3648. }
  3649. /**
  3650. * 短信去重键:优先手机号,否则公司名
  3651. */
  3652. protected function notifySupplierDedupeKey(array $detailRow): string
  3653. {
  3654. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3655. if ($ph !== '') {
  3656. return 'p:' . $ph;
  3657. }
  3658. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3659. return 'c:' . $cn;
  3660. }
  3661. /**
  3662. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3663. *
  3664. * @param int[] $detailIds
  3665. */
  3666. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3667. {
  3668. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3669. if ($detailIds === []) {
  3670. return;
  3671. }
  3672. $payload = ['status_name' => $statusName];
  3673. try {
  3674. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3675. } catch (\Throwable $e) {
  3676. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3677. }
  3678. }
  3679. /**
  3680. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3681. */
  3682. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3683. {
  3684. try {
  3685. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3686. } catch (\Throwable $e) {
  3687. return;
  3688. }
  3689. if (!is_array($rows)) {
  3690. return;
  3691. }
  3692. foreach ($rows as $dr) {
  3693. if (!is_array($dr)) {
  3694. continue;
  3695. }
  3696. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3697. if ($id <= 0) {
  3698. continue;
  3699. }
  3700. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3701. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3702. try {
  3703. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3704. } catch (\Throwable $e) {
  3705. }
  3706. }
  3707. }
  3708. /**
  3709. * @param array<string, mixed> $detailRow
  3710. */
  3711. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3712. {
  3713. $am = $detailRow['amount'] ?? null;
  3714. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3715. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3716. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3717. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3718. }
  3719. /**
  3720. * @return int[]
  3721. */
  3722. protected function purchaseOrderDetail(int $scydgyId): array
  3723. {
  3724. if (!$this->isValidScydgyRowId($scydgyId)) {
  3725. return [];
  3726. }
  3727. try {
  3728. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3729. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3730. $list = $listQuery->select();
  3731. } catch (\Throwable $e) {
  3732. return [];
  3733. }
  3734. if (!is_array($list)) {
  3735. return [];
  3736. }
  3737. $ids = [];
  3738. foreach ($list as $r) {
  3739. if (!is_array($r)) {
  3740. continue;
  3741. }
  3742. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3743. if ($pk > 0) {
  3744. $ids[] = $pk;
  3745. }
  3746. }
  3747. return array_values(array_unique($ids));
  3748. }
  3749. /**
  3750. * 获取当前登录用户信息 [id, 展示名]
  3751. */
  3752. protected function GetUseName(): array
  3753. {
  3754. $id = 0;
  3755. $name = '';
  3756. try {
  3757. if ($this->auth && $this->auth->isLogin()) {
  3758. $u = $this->auth->getUserInfo();
  3759. if (is_array($u)) {
  3760. $id = (int)($u['id'] ?? 0);
  3761. $name = trim((string)($u['nickname'] ?? ''));
  3762. if ($name === '') {
  3763. $name = trim((string)($u['username'] ?? ''));
  3764. }
  3765. }
  3766. }
  3767. } catch (\Throwable $e) {
  3768. }
  3769. if ($name === '') {
  3770. $name = '未知用户';
  3771. }
  3772. return [$id, $name];
  3773. }
  3774. /**
  3775. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3776. */
  3777. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3778. {
  3779. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3780. }
  3781. /**
  3782. * 按主键取一条
  3783. */
  3784. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3785. {
  3786. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3787. return [];
  3788. }
  3789. try {
  3790. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3791. if (is_array($one)) {
  3792. return $one;
  3793. }
  3794. } catch (\Throwable $e) {
  3795. }
  3796. try {
  3797. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3798. if (is_array($one)) {
  3799. return $one;
  3800. }
  3801. } catch (\Throwable $e) {
  3802. }
  3803. return [];
  3804. }
  3805. /**
  3806. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3807. */
  3808. protected function formatProcuremenDetailTime($v): string
  3809. {
  3810. if ($v === null || $v === '') {
  3811. return '';
  3812. }
  3813. if (is_numeric($v) && (int)$v > 946684800) {
  3814. return date('Y-m-d H:i:s', (int)$v);
  3815. }
  3816. return ProcuremenTime::formatDisplayDateTime($v);
  3817. }
  3818. /**
  3819. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3820. */
  3821. protected function formatDeliveryYmd($v): string
  3822. {
  3823. if ($v === null || $v === '') {
  3824. return '';
  3825. }
  3826. $s = trim((string)$v);
  3827. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3828. return '';
  3829. }
  3830. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3831. return $m[1];
  3832. }
  3833. $ts = strtotime($s);
  3834. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3835. }
  3836. /**
  3837. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3838. */
  3839. protected function detailRowSupplierOperated(array $r): bool
  3840. {
  3841. $am = $r['amount'] ?? null;
  3842. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3843. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3844. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3845. return $okAmt || $okDel;
  3846. }
  3847. /**
  3848. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3849. */
  3850. protected function resolveDetailSupplierOperTime(array $r): string
  3851. {
  3852. if (!$this->detailRowSupplierOperated($r)) {
  3853. return '';
  3854. }
  3855. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3856. if ($t !== '') {
  3857. return $t;
  3858. }
  3859. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3860. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3861. continue;
  3862. }
  3863. $t = $this->formatProcuremenDetailTime($r[$col]);
  3864. if ($t !== '') {
  3865. return $t;
  3866. }
  3867. }
  3868. return '';
  3869. }
  3870. /**
  3871. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3872. */
  3873. protected function detailRowSupplierAccepted(array $r): bool
  3874. {
  3875. $am = $r['amount'] ?? null;
  3876. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3877. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3878. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3879. return $okAmt && $okDel;
  3880. }
  3881. /**
  3882. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3883. */
  3884. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3885. {
  3886. if ($detailCount > 0) {
  3887. return true;
  3888. }
  3889. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3890. return true;
  3891. }
  3892. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3893. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3894. return true;
  3895. }
  3896. return false;
  3897. }
  3898. /**
  3899. * 下发时间:优先 pick_time,其次首条下发明细时间
  3900. */
  3901. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3902. {
  3903. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3904. if ($issueTime !== '') {
  3905. return $issueTime;
  3906. }
  3907. foreach ($details as $dr) {
  3908. if (!is_array($dr)) {
  3909. continue;
  3910. }
  3911. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3912. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3913. $issueTime = $t;
  3914. }
  3915. }
  3916. if ($issueTime !== '') {
  3917. return $issueTime;
  3918. }
  3919. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3920. }
  3921. /**
  3922. * 直接点「完结」时间:优先操作记录 mark_complete
  3923. */
  3924. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3925. {
  3926. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  3927. }
  3928. /**
  3929. * 操作记录时间(取指定 action 最近一条)
  3930. *
  3931. * @param string|array<int, string> $actions
  3932. */
  3933. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3934. {
  3935. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  3936. }
  3937. /**
  3938. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3939. *
  3940. * @param array $main purchase_order 一行
  3941. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3942. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3943. */
  3944. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3945. {
  3946. $issueCnt = count($details);
  3947. $acceptCnt = 0;
  3948. $pickedName = '';
  3949. $pickedTime = '';
  3950. foreach ($details as $dr) {
  3951. if (!is_array($dr)) {
  3952. continue;
  3953. }
  3954. if ($this->detailRowSupplierAccepted($dr)) {
  3955. $acceptCnt++;
  3956. }
  3957. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3958. if ($pickedName === '') {
  3959. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3960. }
  3961. if ($pickedTime === '') {
  3962. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3963. if ($pickedTime === '') {
  3964. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3965. }
  3966. }
  3967. }
  3968. }
  3969. $hasMain = $main !== [];
  3970. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3971. if ($poTime === '') {
  3972. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3973. }
  3974. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3975. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3976. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3977. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3978. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3979. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3980. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3981. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3982. $supplierTime = '';
  3983. if ($acceptCnt > 0) {
  3984. foreach ($details as $dr) {
  3985. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3986. continue;
  3987. }
  3988. $t = $this->resolveDetailSupplierOperTime($dr);
  3989. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3990. $supplierTime = $t;
  3991. }
  3992. }
  3993. }
  3994. $directComplete = ($mainCompleted && !$issued);
  3995. $doneTime = '';
  3996. if ($mainCompleted) {
  3997. if ($directComplete) {
  3998. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3999. }
  4000. if ($doneTime === '') {
  4001. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4002. }
  4003. if ($doneTime === '') {
  4004. foreach ($details as $dr) {
  4005. if (!is_array($dr)) {
  4006. continue;
  4007. }
  4008. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4009. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4010. $doneTime = $t;
  4011. }
  4012. }
  4013. }
  4014. if ($doneTime === '') {
  4015. $doneTime = $poTime;
  4016. }
  4017. if ($confirmApproveTime !== '') {
  4018. $doneTime = $confirmApproveTime;
  4019. }
  4020. }
  4021. if ($directComplete) {
  4022. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4023. $step1Done = $hasMain;
  4024. $step2Done = false;
  4025. $step3Done = false;
  4026. $step4Done = false;
  4027. $step5Done = false;
  4028. $step6Done = true;
  4029. } else {
  4030. $step1Done = $issued;
  4031. $step2Done = $issued;
  4032. $step3Done = $acceptCnt > 0;
  4033. $step4Done = $wflowPendingApproval;
  4034. if (!$step4Done) {
  4035. foreach ($details as $dr) {
  4036. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4037. $step4Done = true;
  4038. break;
  4039. }
  4040. }
  4041. }
  4042. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4043. $step6Done = $mainCompleted;
  4044. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4045. if ($mainCompleted && $issued) {
  4046. $step3Done = true;
  4047. $step4Done = true;
  4048. $step5Done = true;
  4049. if ($supplierTime === '') {
  4050. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4051. if ($fillT !== '') {
  4052. $supplierTime = $fillT;
  4053. }
  4054. }
  4055. if ($pickedTime === '') {
  4056. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4057. if ($fillT !== '') {
  4058. $pickedTime = $fillT;
  4059. }
  4060. }
  4061. if ($auditSelectTime === '') {
  4062. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4063. if ($fillT !== '') {
  4064. $auditSelectTime = $fillT;
  4065. }
  4066. }
  4067. if ($confirmApproveTime === '') {
  4068. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4069. if ($fillT !== '') {
  4070. $confirmApproveTime = $fillT;
  4071. }
  4072. }
  4073. }
  4074. }
  4075. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4076. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4077. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4078. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4079. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4080. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4081. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4082. $deadlineText = '';
  4083. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4084. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4085. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4086. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4087. $deadlineText = '截止 ' . $deadlineDisp;
  4088. }
  4089. }
  4090. $steps = [
  4091. [
  4092. 'title' => '未发',
  4093. 'subtitle' => '',
  4094. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4095. 'done' => $step1Done,
  4096. ],
  4097. [
  4098. 'title' => '下发',
  4099. 'subtitle' => $deadlineText,
  4100. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4101. 'done' => $step2Done,
  4102. ],
  4103. [
  4104. 'title' => '供应商接单',
  4105. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4106. 'time' => '',
  4107. 'done' => $step3Done,
  4108. ],
  4109. [
  4110. 'title' => '待确认',
  4111. 'subtitle' => $step4Done
  4112. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4113. : ($issued ? '待选供应商' : ''),
  4114. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4115. 'done' => $step4Done,
  4116. ],
  4117. [
  4118. 'title' => '待审批',
  4119. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4120. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4121. 'done' => $step5Done,
  4122. ],
  4123. [
  4124. 'title' => '已完结',
  4125. 'subtitle' => '',
  4126. 'time' => $step6Done ? $doneTime : '',
  4127. 'done' => $step6Done,
  4128. ],
  4129. ];
  4130. $currentIdx = count($steps) - 1;
  4131. if (!$directComplete) {
  4132. foreach ($steps as $i => $s) {
  4133. if (!$s['done']) {
  4134. $currentIdx = $i;
  4135. break;
  4136. }
  4137. }
  4138. }
  4139. $nSteps = count($steps);
  4140. foreach ($steps as $idx => &$s) {
  4141. $s['current'] = ($idx === $currentIdx);
  4142. if ($idx === 0) {
  4143. $s['pdf_left_bg'] = '';
  4144. } else {
  4145. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4146. }
  4147. if ($idx >= $nSteps - 1) {
  4148. $s['pdf_right_bg'] = '';
  4149. } else {
  4150. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4151. }
  4152. }
  4153. unset($s);
  4154. $labelMap = [
  4155. 'CCYDH' => '订单号',
  4156. 'CYJMC' => '印件名称',
  4157. 'CCLBMMC' => '承揽部门',
  4158. 'CGYMC' => '工序名称',
  4159. 'CDW' => '单位',
  4160. 'NGZL' => '工作量',
  4161. 'CDF' => '单价',
  4162. 'cGzzxMc' => '工作中心',
  4163. 'MBZ' => '备注',
  4164. 'This_quantity' => '本次数量',
  4165. 'ceilingPrice' => '最高限价',
  4166. ];
  4167. $orderSummary = [];
  4168. foreach ($labelMap as $key => $lab) {
  4169. if (!array_key_exists($key, $main)) {
  4170. continue;
  4171. }
  4172. $val = $main[$key];
  4173. if ($val === null) {
  4174. $val = '';
  4175. } elseif (!is_scalar($val)) {
  4176. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4177. } else {
  4178. $val = (string)$val;
  4179. }
  4180. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4181. }
  4182. $orderSummaryGrid = [];
  4183. $n = count($orderSummary);
  4184. for ($i = 0; $i < $n; $i += 2) {
  4185. $left = $orderSummary[$i];
  4186. $hasRight = ($i + 1) < $n;
  4187. $orderSummaryGrid[] = [
  4188. 'l1' => $left['label'],
  4189. 'v1' => $left['value'],
  4190. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4191. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4192. ];
  4193. }
  4194. return [
  4195. 'steps' => $steps,
  4196. 'orderSummary' => $orderSummary,
  4197. 'orderSummaryGrid' => $orderSummaryGrid,
  4198. 'detailRows' => $details,
  4199. ];
  4200. }
  4201. /**
  4202. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4203. *
  4204. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4205. */
  4206. protected function prepareProcuremenDetailsView(string $ids): array
  4207. {
  4208. $main = [];
  4209. try {
  4210. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4211. $main = is_array($one) ? $one : [];
  4212. } catch (\Throwable $e) {
  4213. $main = [];
  4214. }
  4215. $details = [];
  4216. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4217. if ($mergeRows === []) {
  4218. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4219. if ($mergeRows === [] && $main !== []) {
  4220. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4221. }
  4222. }
  4223. $detailSidList = [];
  4224. $anchorSid = (int)$ids;
  4225. if ($anchorSid !== 0) {
  4226. $detailSidList[$anchorSid] = true;
  4227. }
  4228. foreach ($mergeRows as $mr) {
  4229. if (!is_array($mr)) {
  4230. continue;
  4231. }
  4232. $sid = $this->extractScydgyRowId($mr);
  4233. if ($sid !== 0) {
  4234. $detailSidList[$sid] = true;
  4235. }
  4236. }
  4237. try {
  4238. if ($detailSidList !== []) {
  4239. $details = Db::table('purchase_order_detail')
  4240. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4241. ->order('id', 'asc')
  4242. ->select();
  4243. }
  4244. } catch (\Throwable $e) {
  4245. $details = [];
  4246. }
  4247. if (!is_array($details)) {
  4248. $details = [];
  4249. }
  4250. foreach ($details as &$r) {
  4251. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4252. $r['id'] = $r['ID'];
  4253. }
  4254. if (isset($r['createtime'])) {
  4255. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4256. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4257. } else {
  4258. $r['createtime_text'] = (string)$r['createtime'];
  4259. }
  4260. } else {
  4261. $r['createtime_text'] = '';
  4262. }
  4263. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4264. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4265. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4266. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4267. if (is_array($r)) {
  4268. $r = $this->maskSupplierContactFields($r);
  4269. }
  4270. }
  4271. unset($r);
  4272. $activeDetails = [];
  4273. foreach ($details as $r) {
  4274. if (is_array($r) && empty($r['is_void'])) {
  4275. $activeDetails[] = $r;
  4276. }
  4277. }
  4278. $operLogs = [];
  4279. try {
  4280. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4281. } catch (\Throwable $e) {
  4282. $operLogs = [];
  4283. }
  4284. if (!is_array($operLogs)) {
  4285. $operLogs = [];
  4286. }
  4287. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4288. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4289. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4290. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4291. if ($ccydh === '') {
  4292. foreach ($details as $r) {
  4293. if (!is_array($r)) {
  4294. continue;
  4295. }
  4296. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4297. if ($ccydh !== '') {
  4298. break;
  4299. }
  4300. }
  4301. }
  4302. $this->view->assign('ccydh', $ccydh);
  4303. $this->view->assign('steps', $bundle['steps']);
  4304. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4305. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4306. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4307. $this->view->assign('processCount', count($mergeRows));
  4308. $this->view->assign('detailRows', $details);
  4309. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4310. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4311. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4312. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4313. $showSupplierBidResult = (trim((string)($quoteView['selected_company'] ?? '')) !== '')
  4314. || ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4315. if (!$showSupplierBidResult) {
  4316. foreach ($details as $dr) {
  4317. if (is_array($dr) && !empty($dr['is_picked'])) {
  4318. $showSupplierBidResult = true;
  4319. break;
  4320. }
  4321. }
  4322. }
  4323. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4324. $this->view->assign('operLogs', $operLogs);
  4325. return [
  4326. 'ok' => $main !== [] || $details !== [],
  4327. 'ccydh' => $ccydh,
  4328. ];
  4329. }
  4330. /**
  4331. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4332. */
  4333. public function details()
  4334. {
  4335. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4336. if (is_array($ids)) {
  4337. $ids = isset($ids[0]) ? $ids[0] : '';
  4338. }
  4339. $ids = trim((string)$ids);
  4340. if ($ids === '') {
  4341. $this->error(__('Invalid parameters'));
  4342. }
  4343. $this->assertManualOrderDetailsViewable((int)$ids);
  4344. $this->prepareProcuremenDetailsView($ids);
  4345. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4346. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4347. $this->view->engine->layout(false);
  4348. try {
  4349. return $this->view->fetch('procuremen/details_dialog_shell');
  4350. } finally {
  4351. if ($restoreLayout) {
  4352. $this->view->engine->layout($restoreLayout);
  4353. }
  4354. }
  4355. }
  4356. /**
  4357. * 解析合并审核工序行(订单号须一致,且均未协助)
  4358. *
  4359. * @return array<int, array<string, mixed>>
  4360. */
  4361. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4362. {
  4363. $primary = json_decode($rowJson, true);
  4364. if (!is_array($primary)) {
  4365. $this->error(__('Invalid parameters'));
  4366. }
  4367. $merge = json_decode($mergeRowsJson, true);
  4368. if (!is_array($merge) || $merge === []) {
  4369. $merge = [$primary];
  4370. }
  4371. $seen = [];
  4372. $out = [];
  4373. foreach ($merge as $r) {
  4374. if (!is_array($r)) {
  4375. continue;
  4376. }
  4377. $id = $this->extractScydgyRowId($r);
  4378. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4379. continue;
  4380. }
  4381. $seen[$id] = true;
  4382. $out[] = $r;
  4383. }
  4384. if ($out === []) {
  4385. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4386. }
  4387. $ccydh = null;
  4388. foreach ($out as $r) {
  4389. $dh = trim((string)($r['CCYDH'] ?? ''));
  4390. if ($ccydh === null) {
  4391. $ccydh = $dh;
  4392. } elseif ($dh !== $ccydh) {
  4393. $this->error('合并审核要求所选行的订单号一致');
  4394. }
  4395. }
  4396. $ids = [];
  4397. foreach ($out as $r) {
  4398. $id = $this->extractScydgyRowId($r);
  4399. if ($this->isValidScydgyRowId($id)) {
  4400. $ids[$id] = true;
  4401. }
  4402. }
  4403. $poBySid = [];
  4404. $detCntBySid = [];
  4405. if ($ids !== []) {
  4406. $idList = array_keys($ids);
  4407. try {
  4408. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4409. if (is_array($poList)) {
  4410. foreach ($poList as $po) {
  4411. if (!is_array($po)) {
  4412. continue;
  4413. }
  4414. $sid = (int)($po['scydgy_id'] ?? 0);
  4415. if ($this->isValidScydgyRowId($sid)) {
  4416. $poBySid[$sid] = $po;
  4417. }
  4418. }
  4419. }
  4420. } catch (\Throwable $e) {
  4421. }
  4422. try {
  4423. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4424. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4425. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4426. if (is_array($detRows)) {
  4427. foreach ($detRows as $dr) {
  4428. if (!is_array($dr)) {
  4429. continue;
  4430. }
  4431. $sid = (int)($dr['scydgy_id'] ?? 0);
  4432. if ($this->isValidScydgyRowId($sid)) {
  4433. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4434. }
  4435. }
  4436. }
  4437. } catch (\Throwable $e) {
  4438. }
  4439. }
  4440. foreach ($out as $r) {
  4441. $id = $this->extractScydgyRowId($r);
  4442. if (!$this->isValidScydgyRowId($id)) {
  4443. continue;
  4444. }
  4445. $po = $poBySid[$id] ?? null;
  4446. if (!is_array($po)) {
  4447. continue;
  4448. }
  4449. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4450. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4451. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4452. }
  4453. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4454. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4455. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4456. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4457. }
  4458. }
  4459. return $out;
  4460. }
  4461. /**
  4462. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4463. */
  4464. protected function maskSupplierContactFields(array $item): array
  4465. {
  4466. if (array_key_exists('email', $item)) {
  4467. $item['email'] = mask_email((string)$item['email']);
  4468. }
  4469. if (array_key_exists('phone', $item)) {
  4470. $item['phone'] = mask_phone((string)$item['phone']);
  4471. }
  4472. return $item;
  4473. }
  4474. /**
  4475. * @param array<int, array<string, mixed>> $list
  4476. * @return array<int, array<string, mixed>>
  4477. */
  4478. protected function maskSupplierContactList(array $list): array
  4479. {
  4480. $out = [];
  4481. foreach ($list as $item) {
  4482. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4483. }
  4484. return $out;
  4485. }
  4486. /**
  4487. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4488. *
  4489. * @return array<string, string>|null
  4490. */
  4491. protected function buildCustomerContactPayloadFromRow($row): ?array
  4492. {
  4493. if (!is_array($row)) {
  4494. return null;
  4495. }
  4496. $norm = [];
  4497. foreach ($row as $k => $v) {
  4498. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4499. }
  4500. $row = $norm;
  4501. $st = $row['status'] ?? '';
  4502. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4503. return null;
  4504. }
  4505. $companyName = '';
  4506. foreach (['company_name', 'name'] as $nk) {
  4507. if (!empty($row[$nk])) {
  4508. $companyName = trim((string)$row[$nk]);
  4509. break;
  4510. }
  4511. }
  4512. if ($companyName === '') {
  4513. return null;
  4514. }
  4515. $username = '';
  4516. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4517. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4518. $username = trim((string)$row[$uk]);
  4519. break;
  4520. }
  4521. }
  4522. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4523. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4524. if ($phone === '' && isset($row['account'])) {
  4525. $phone = trim((string)$row['account']);
  4526. }
  4527. if ($phone === '' && isset($row['mobile'])) {
  4528. $phone = trim((string)$row['mobile']);
  4529. }
  4530. if ($email === '' && $phone === '') {
  4531. return null;
  4532. }
  4533. $category = '';
  4534. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4535. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4536. $category = trim((string)$row[$ck]);
  4537. break;
  4538. }
  4539. }
  4540. return [
  4541. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4542. 'name' => $companyName,
  4543. 'company_name' => $companyName,
  4544. 'username' => $username,
  4545. 'email' => $email,
  4546. 'phone' => $phone,
  4547. 'category' => $category,
  4548. 'company_type' => $category,
  4549. ];
  4550. }
  4551. /**
  4552. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4553. */
  4554. protected function resolveCustomerContactById(string $id): ?array
  4555. {
  4556. $id = trim($id);
  4557. if ($id === '' || !ctype_digit($id)) {
  4558. return null;
  4559. }
  4560. try {
  4561. $row = Db::table('customer')->where('id', (int)$id)->find();
  4562. } catch (\Throwable $e) {
  4563. return null;
  4564. }
  4565. return $this->buildCustomerContactPayloadFromRow($row);
  4566. }
  4567. /**
  4568. * 按供应商名称解析联系信息(兼容旧提交数据)
  4569. */
  4570. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4571. {
  4572. $name = trim($name);
  4573. if ($name === '') {
  4574. return null;
  4575. }
  4576. try {
  4577. $row = Db::table('customer')
  4578. ->where(function ($q) use ($name) {
  4579. $q->where('company_name', $name)->whereOr('name', $name);
  4580. })
  4581. ->order('id', 'desc')
  4582. ->find();
  4583. } catch (\Throwable $e) {
  4584. return null;
  4585. }
  4586. return $this->buildCustomerContactPayloadFromRow($row);
  4587. }
  4588. /**
  4589. * 规范化下发/确认时勾选的供应商
  4590. *
  4591. * @param array<int, mixed> $companies
  4592. * @return array<int, array<string, string>>
  4593. */
  4594. protected function normalizePickCompanies(array $companies): array
  4595. {
  4596. $out = [];
  4597. foreach ($companies as $c) {
  4598. if (!is_array($c)) {
  4599. continue;
  4600. }
  4601. $resolved = null;
  4602. $cid = trim((string)($c['id'] ?? ''));
  4603. if ($cid !== '') {
  4604. $resolved = $this->resolveCustomerContactById($cid);
  4605. }
  4606. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4607. if ($resolved === null && $name !== '') {
  4608. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4609. }
  4610. if ($resolved === null) {
  4611. continue;
  4612. }
  4613. $out[] = $resolved;
  4614. }
  4615. return $out;
  4616. }
  4617. /**
  4618. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4619. *
  4620. * @param array<int, array<string, mixed>> $pool
  4621. * @return array<int, array<string, mixed>>
  4622. */
  4623. protected function collapseProcuremenPoolByOrder(array $pool): array
  4624. {
  4625. if ($pool === []) {
  4626. return [];
  4627. }
  4628. $groups = [];
  4629. foreach ($pool as $row) {
  4630. if (!is_array($row)) {
  4631. continue;
  4632. }
  4633. $dh = trim((string)($row['CCYDH'] ?? ''));
  4634. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4635. if (!isset($groups[$key])) {
  4636. $groups[$key] = [];
  4637. }
  4638. $groups[$key][] = $row;
  4639. }
  4640. $out = [];
  4641. foreach ($groups as $ccydh => $rows) {
  4642. if ($rows === []) {
  4643. continue;
  4644. }
  4645. usort($rows, function ($a, $b) {
  4646. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4647. });
  4648. $head = $rows[0];
  4649. $gymcList = [];
  4650. foreach ($rows as $r) {
  4651. $g = trim((string)($r['CGYMC'] ?? ''));
  4652. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4653. $gymcList[] = $g;
  4654. }
  4655. }
  4656. $merged = $head;
  4657. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4658. $merged['process_count'] = count($rows);
  4659. $merged['_order_merge_rows'] = $rows;
  4660. if (count($rows) > 1) {
  4661. $merged['CGYMC'] = implode('、', $gymcList);
  4662. }
  4663. $mergedPickTime = '';
  4664. foreach ($rows as $r) {
  4665. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4666. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4667. $mergedPickTime = $t;
  4668. }
  4669. }
  4670. if ($mergedPickTime !== '') {
  4671. $merged['pick_time'] = $mergedPickTime;
  4672. }
  4673. $out[] = $merged;
  4674. }
  4675. usort($out, function ($a, $b) {
  4676. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4677. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4678. if ($ta === $tb) {
  4679. $ida = (int)($a['purchase_order_id'] ?? 0);
  4680. $idb = (int)($b['purchase_order_id'] ?? 0);
  4681. if ($ida !== $idb) {
  4682. return $idb <=> $ida;
  4683. }
  4684. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4685. }
  4686. if ($ta === '') {
  4687. return 1;
  4688. }
  4689. if ($tb === '') {
  4690. return -1;
  4691. }
  4692. return strcmp($tb, $ta);
  4693. });
  4694. return $out;
  4695. }
  4696. /**
  4697. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4698. *
  4699. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4700. */
  4701. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4702. {
  4703. $scydgyId = trim($scydgyId);
  4704. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4705. if ($scydgyId === '') {
  4706. return $empty;
  4707. }
  4708. try {
  4709. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4710. } catch (\Throwable $e) {
  4711. $anchor = null;
  4712. }
  4713. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4714. return $empty;
  4715. }
  4716. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4717. if ($ccydh === '') {
  4718. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4719. }
  4720. try {
  4721. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4722. } catch (\Throwable $e) {
  4723. $pos = [$anchor];
  4724. }
  4725. if (!is_array($pos) || $pos === []) {
  4726. $pos = [$anchor];
  4727. }
  4728. return [
  4729. 'ccydh' => $ccydh,
  4730. 'pos' => $pos,
  4731. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4732. ];
  4733. }
  4734. /**
  4735. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4736. */
  4737. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4738. {
  4739. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4740. return false;
  4741. }
  4742. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4743. return false;
  4744. }
  4745. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4746. return true;
  4747. }
  4748. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4749. $sid = (int)($po['scydgy_id'] ?? 0);
  4750. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4751. }
  4752. return false;
  4753. }
  4754. /**
  4755. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4756. *
  4757. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4758. */
  4759. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4760. {
  4761. $scydgyId = trim($scydgyId);
  4762. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4763. if ($scydgyId === '') {
  4764. return $empty;
  4765. }
  4766. try {
  4767. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4768. } catch (\Throwable $e) {
  4769. $anchor = null;
  4770. }
  4771. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4772. return $empty;
  4773. }
  4774. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4775. if ($ccydh === '') {
  4776. return [
  4777. 'ccydh' => '',
  4778. 'pos' => [$anchor],
  4779. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4780. ];
  4781. }
  4782. try {
  4783. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4784. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4785. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4786. } catch (\Throwable $e) {
  4787. $pos = [$anchor];
  4788. }
  4789. if (!is_array($pos) || $pos === []) {
  4790. $pos = [$anchor];
  4791. }
  4792. $pos = array_values(array_filter($pos, function ($po) {
  4793. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4794. }));
  4795. if ($pos === []) {
  4796. $pos = [$anchor];
  4797. }
  4798. return [
  4799. 'ccydh' => $ccydh,
  4800. 'pos' => $pos,
  4801. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4802. ];
  4803. }
  4804. /**
  4805. * @param array<int, array<string, mixed>> $purchaseOrders
  4806. * @return array<int, array<string, mixed>>
  4807. */
  4808. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4809. {
  4810. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4811. $byId = [];
  4812. foreach ($pool as $r) {
  4813. if (!is_array($r)) {
  4814. continue;
  4815. }
  4816. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4817. if ($this->isValidScydgyRowId($sid)) {
  4818. $byId[$sid] = $r;
  4819. }
  4820. }
  4821. $out = [];
  4822. foreach ($purchaseOrders as $po) {
  4823. if (!is_array($po)) {
  4824. continue;
  4825. }
  4826. $sid = (int)($po['scydgy_id'] ?? 0);
  4827. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4828. $out[] = $byId[$sid];
  4829. }
  4830. }
  4831. return $out;
  4832. }
  4833. /**
  4834. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4835. *
  4836. * @return array<int, array<string, mixed>>
  4837. */
  4838. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4839. {
  4840. $scydgyId = trim($scydgyId);
  4841. if ($scydgyId === '') {
  4842. return [];
  4843. }
  4844. try {
  4845. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4846. } catch (\Throwable $e) {
  4847. $anchor = null;
  4848. }
  4849. if (!is_array($anchor)) {
  4850. return [];
  4851. }
  4852. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4853. return [];
  4854. }
  4855. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4856. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4857. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4858. try {
  4859. $q = Db::table('purchase_order');
  4860. if ($ccydh !== '') {
  4861. $q->where('CCYDH', $ccydh);
  4862. } else {
  4863. $q->where('scydgy_id', $scydgyId);
  4864. }
  4865. if ($isValidPick) {
  4866. $q->where('pick_time', $pickTime);
  4867. }
  4868. $pos = $q->order('scydgy_id', 'asc')->select();
  4869. } catch (\Throwable $e) {
  4870. $pos = [$anchor];
  4871. }
  4872. if (!is_array($pos) || $pos === []) {
  4873. $pos = [$anchor];
  4874. }
  4875. $pos = array_values(array_filter($pos, function ($po) {
  4876. if (!is_array($po)) {
  4877. return false;
  4878. }
  4879. $mr = $po['mod_rq'] ?? null;
  4880. if ($mr === null || $mr === '') {
  4881. return true;
  4882. }
  4883. $mrs = trim((string)$mr);
  4884. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4885. }));
  4886. if ($pos === []) {
  4887. $pos = [$anchor];
  4888. }
  4889. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4890. if ($rows === []) {
  4891. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4892. }
  4893. return $rows;
  4894. }
  4895. /**
  4896. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4897. *
  4898. * @param array<int, array<string, mixed>> $mergeRows
  4899. * @return array<int, array<string, mixed>>
  4900. */
  4901. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4902. {
  4903. $list = array_values($mergeRows);
  4904. $n = count($list);
  4905. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4906. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4907. $mergeSame = $n > 1 && $orderKey0 !== '';
  4908. if ($mergeSame) {
  4909. foreach ($list as $rr) {
  4910. if (!is_array($rr)) {
  4911. $mergeSame = false;
  4912. break;
  4913. }
  4914. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4915. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4916. $mergeSame = false;
  4917. break;
  4918. }
  4919. }
  4920. }
  4921. $out = [];
  4922. foreach ($list as $idx => $r) {
  4923. if (!is_array($r)) {
  4924. continue;
  4925. }
  4926. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4927. if (is_scalar($qty)) {
  4928. $qty = trim((string)$qty);
  4929. } else {
  4930. $qty = '';
  4931. }
  4932. if ($qty === '') {
  4933. $gzl = $r['NGZL'] ?? '';
  4934. if (is_scalar($gzl)) {
  4935. $qty = trim((string)$gzl);
  4936. }
  4937. }
  4938. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4939. $sid = $this->extractScydgyRowId($r);
  4940. $out[] = [
  4941. 'seq' => $idx + 1,
  4942. 'scydgy_id' => $sid,
  4943. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4944. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4945. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4946. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4947. 'NGZL' => $r['NGZL'] ?? '',
  4948. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4949. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4950. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4951. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4952. 'show_order_cells' => !$mergeSame || $idx === 0,
  4953. 'order_rowspan' => $mergeSame ? $n : 1,
  4954. ];
  4955. }
  4956. return $out;
  4957. }
  4958. /**
  4959. * 解析金额/数量(去千分位等非数字字符)
  4960. */
  4961. protected function parseProcuremenMoneyNumber($value): ?float
  4962. {
  4963. if ($value === null || $value === '') {
  4964. return null;
  4965. }
  4966. if (is_numeric($value)) {
  4967. return (float)$value;
  4968. }
  4969. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4970. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4971. }
  4972. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4973. {
  4974. if ($amount === null) {
  4975. return '';
  4976. }
  4977. return (string)(int)round($amount);
  4978. }
  4979. /**
  4980. * 列表/详情展示:工作量为 0 时显示空
  4981. */
  4982. protected function formatProcuremenWorkloadDisplay($value): string
  4983. {
  4984. if ($value === null || $value === '') {
  4985. return '';
  4986. }
  4987. $s = trim((string)$value);
  4988. if ($s === '') {
  4989. return '';
  4990. }
  4991. if (is_numeric($s) && (float)$s == 0) {
  4992. return '';
  4993. }
  4994. return $s;
  4995. }
  4996. /**
  4997. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4998. */
  4999. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5000. {
  5001. foreach ($details as $d) {
  5002. if (!is_array($d)) {
  5003. continue;
  5004. }
  5005. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5006. $cn = trim((string)($d['company_name'] ?? ''));
  5007. if ($cn !== '') {
  5008. return $cn;
  5009. }
  5010. }
  5011. }
  5012. return trim((string)($main['pick_company_name'] ?? ''));
  5013. }
  5014. /**
  5015. * 详情报价小计:单价 × 本工序本次数量
  5016. */
  5017. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5018. {
  5019. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5020. if ($unit === null) {
  5021. return null;
  5022. }
  5023. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5024. if ($qty === null || $qty <= 0) {
  5025. return null;
  5026. }
  5027. return $unit * $qty;
  5028. }
  5029. /**
  5030. * 详情页:工序小计 + 供应商分组报价与总计
  5031. *
  5032. * @param array<int, array<string, mixed>> $mergeRows
  5033. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5034. * @return array{
  5035. * process_rows: array,
  5036. * supplier_groups: array,
  5037. * order_total_text: string,
  5038. * order_total_has: bool,
  5039. * selected_company: string
  5040. * }
  5041. */
  5042. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5043. {
  5044. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5045. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5046. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5047. $qtyBySid = [];
  5048. $gymcBySid = [];
  5049. $orderedSids = [];
  5050. foreach ($mergeRows as $mr) {
  5051. if (!is_array($mr)) {
  5052. continue;
  5053. }
  5054. $sid = $this->extractScydgyRowId($mr);
  5055. if ($this->isValidScydgyRowId($sid)) {
  5056. $orderedSids[] = $sid;
  5057. }
  5058. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5059. if ($qty === '') {
  5060. $qty = trim((string)($mr['NGZL'] ?? ''));
  5061. }
  5062. $qtyBySid[$sid] = $qty;
  5063. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5064. }
  5065. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5066. $detailByCompanySid = [];
  5067. foreach ($details as $d) {
  5068. if (!is_array($d)) {
  5069. continue;
  5070. }
  5071. $cn = trim((string)($d['company_name'] ?? ''));
  5072. $sid = (int)($d['scydgy_id'] ?? 0);
  5073. if ($cn === '' || $sid === 0) {
  5074. continue;
  5075. }
  5076. if (!isset($detailByCompanySid[$cn])) {
  5077. $detailByCompanySid[$cn] = [];
  5078. }
  5079. $detailByCompanySid[$cn][$sid] = $d;
  5080. }
  5081. $supplierGroups = [];
  5082. foreach ($detailByCompanySid as $cn => $bySid) {
  5083. $lines = [];
  5084. $groupTotal = 0.0;
  5085. $groupHas = false;
  5086. $groupVoid = true;
  5087. $usedSids = [];
  5088. $appendLine = function (int $sid, array $d) use (
  5089. &$lines,
  5090. &$groupTotal,
  5091. &$groupHas,
  5092. &$groupVoid,
  5093. $qtyBySid,
  5094. $gymcBySid,
  5095. $quoteVisible
  5096. ) {
  5097. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5098. if (!$isVoid) {
  5099. $groupVoid = false;
  5100. }
  5101. $qtyStr = $qtyBySid[$sid] ?? '';
  5102. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5103. $am = trim((string)($d['amount'] ?? ''));
  5104. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5105. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5106. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5107. $sub = null;
  5108. if (!$isVoid && $amountNum !== null) {
  5109. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5110. }
  5111. $ct = $this->resolveDetailSupplierOperTime($d);
  5112. $line = [
  5113. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5114. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  5115. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5116. 'delivery_ymd' => $deliveryYmd,
  5117. 'amount_filled' => $amountFilled,
  5118. 'delivery_filled' => $deliveryFilled,
  5119. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5120. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5121. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5122. 'is_void' => $isVoid,
  5123. 'oper_time_text' => $ct,
  5124. ];
  5125. if (!$quoteVisible && !$isVoid) {
  5126. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5127. } elseif ($sub !== null) {
  5128. $groupTotal += $sub;
  5129. $groupHas = true;
  5130. }
  5131. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5132. };
  5133. foreach ($orderedSids as $sid) {
  5134. if (!isset($bySid[$sid])) {
  5135. continue;
  5136. }
  5137. $usedSids[$sid] = true;
  5138. $appendLine($sid, $bySid[$sid]);
  5139. }
  5140. foreach ($bySid as $sid => $d) {
  5141. if (isset($usedSids[$sid])) {
  5142. continue;
  5143. }
  5144. $appendLine((int)$sid, $d);
  5145. }
  5146. $firstDetail = null;
  5147. foreach ($bySid as $d) {
  5148. if (is_array($d)) {
  5149. $firstDetail = $d;
  5150. break;
  5151. }
  5152. }
  5153. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5154. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5155. if ($username === '' && $ph !== '') {
  5156. $username = $this->resolveCustomerContactName($ph, $cn);
  5157. }
  5158. $remark = '';
  5159. foreach ($bySid as $d) {
  5160. if (!is_array($d)) {
  5161. continue;
  5162. }
  5163. $rm = '';
  5164. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5165. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5166. $rm = trim((string)$d[$rk]);
  5167. break;
  5168. }
  5169. }
  5170. if ($rm !== '') {
  5171. $remark = $rm;
  5172. break;
  5173. }
  5174. }
  5175. $lineCount = count($lines);
  5176. $hasRemark = $lineCount > 0;
  5177. $supplierGroups[] = [
  5178. 'company_name' => $cn,
  5179. 'username' => $username,
  5180. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5181. 'phone' => $ph,
  5182. 'remark' => $remark,
  5183. 'has_remark' => $hasRemark,
  5184. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5185. 'is_void' => $groupVoid,
  5186. 'lines' => $lines,
  5187. 'line_count' => $lineCount,
  5188. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5189. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5190. 'has_total' => $lineCount > 0,
  5191. ];
  5192. }
  5193. usort($supplierGroups, function ($a, $b) {
  5194. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5195. return ($a['is_void'] ?? false) ? 1 : -1;
  5196. }
  5197. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5198. return ($a['is_selected'] ?? false) ? -1 : 1;
  5199. }
  5200. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5201. });
  5202. return [
  5203. 'process_rows' => $processRows,
  5204. 'supplier_groups' => $supplierGroups,
  5205. 'order_total_text' => '',
  5206. 'order_total_has' => false,
  5207. 'selected_company' => $selectedCompany,
  5208. ];
  5209. }
  5210. /**
  5211. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5212. */
  5213. protected function buildProcessLinesPlain(array $mergeRows): string
  5214. {
  5215. $lines = [];
  5216. $i = 1;
  5217. foreach ($mergeRows as $r) {
  5218. if (!is_array($r)) {
  5219. continue;
  5220. }
  5221. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5222. $dw = trim((string)($r['CDW'] ?? ''));
  5223. $gzl = trim((string)($r['NGZL'] ?? ''));
  5224. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5225. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5226. if ($dw !== '') {
  5227. $parts[] = '单位:' . $dw;
  5228. }
  5229. if ($gzl !== '') {
  5230. $parts[] = '工作量:' . $gzl;
  5231. }
  5232. if ($qty !== '') {
  5233. $parts[] = '本次数量:' . $qty;
  5234. }
  5235. $lines[] = implode(' ', $parts);
  5236. $i++;
  5237. }
  5238. return implode("\n", $lines);
  5239. }
  5240. /**
  5241. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5242. *
  5243. * @return array<string, string>
  5244. */
  5245. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5246. {
  5247. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5248. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5249. }
  5250. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5251. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5252. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5253. $cyjmc = '';
  5254. foreach ($mergeRows as $mr) {
  5255. if (!is_array($mr)) {
  5256. continue;
  5257. }
  5258. if ($ccydh === '') {
  5259. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5260. }
  5261. if ($cyjmc === '') {
  5262. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5263. }
  5264. }
  5265. if ($pos !== []) {
  5266. $firstPo = $pos[0];
  5267. if (is_array($firstPo)) {
  5268. if ($ccydh === '') {
  5269. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5270. }
  5271. if ($cyjmc === '') {
  5272. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5273. }
  5274. }
  5275. }
  5276. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5277. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5278. if (is_array($any)) {
  5279. if ($ccydh === '') {
  5280. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5281. }
  5282. if ($cyjmc === '') {
  5283. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5284. }
  5285. }
  5286. }
  5287. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5288. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5289. $cgymc = '';
  5290. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5291. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5292. }
  5293. return [
  5294. 'ccydh' => $ccydh,
  5295. 'cyjmc' => $cyjmc,
  5296. 'cgymc' => $cgymc,
  5297. 'process_lines' => $processLines,
  5298. 'process_lines_html' => '',
  5299. ];
  5300. }
  5301. /**
  5302. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5303. */
  5304. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5305. {
  5306. $lines = [];
  5307. if ($ccydh !== '') {
  5308. $lines[] = '订单号:' . $ccydh;
  5309. }
  5310. if ($cyjmc !== '') {
  5311. $lines[] = '印件名称:' . $cyjmc;
  5312. }
  5313. if ($processPlain !== '') {
  5314. $lines[] = $processPlain;
  5315. }
  5316. return implode("\n", $lines);
  5317. }
  5318. /**
  5319. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5320. *
  5321. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5322. */
  5323. protected function buildPlatformLinksPlain(array $detailLinks): string
  5324. {
  5325. $lines = [];
  5326. $i = 1;
  5327. foreach ($detailLinks as $lk) {
  5328. if (!is_array($lk)) {
  5329. continue;
  5330. }
  5331. $url = trim((string)($lk['url'] ?? ''));
  5332. if ($url === '') {
  5333. continue;
  5334. }
  5335. $label = trim((string)($lk['cgymc'] ?? ''));
  5336. if ($label === '') {
  5337. $label = '工序' . $i;
  5338. }
  5339. $lines[] = $label . ':' . $url;
  5340. $i++;
  5341. }
  5342. return implode("\n", $lines);
  5343. }
  5344. /**
  5345. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5346. *
  5347. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5348. */
  5349. protected function buildPlatformLinksHtml(array $detailLinks): string
  5350. {
  5351. $parts = [];
  5352. $i = 1;
  5353. foreach ($detailLinks as $lk) {
  5354. if (!is_array($lk)) {
  5355. continue;
  5356. }
  5357. $url = trim((string)($lk['url'] ?? ''));
  5358. if ($url === '') {
  5359. continue;
  5360. }
  5361. $label = trim((string)($lk['cgymc'] ?? ''));
  5362. if ($label === '') {
  5363. $label = '工序' . $i;
  5364. }
  5365. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5366. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5367. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5368. $i++;
  5369. }
  5370. return implode("<br>\n", $parts);
  5371. }
  5372. /**
  5373. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5374. *
  5375. * @return array<string, mixed>
  5376. */
  5377. protected function loadMailerConfig(): array
  5378. {
  5379. try {
  5380. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5381. } catch (\Throwable $e) {
  5382. $cfg = [];
  5383. }
  5384. return is_array($cfg) ? $cfg : [];
  5385. }
  5386. protected function loadNotifyTemplateRow(string $scene): ?array
  5387. {
  5388. try {
  5389. $row = Db::table('purchase_sms_template')
  5390. ->where('scene', $scene)
  5391. ->where(function ($q) {
  5392. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5393. })
  5394. ->order('id', 'asc')
  5395. ->find();
  5396. } catch (\Throwable $e) {
  5397. return null;
  5398. }
  5399. if (!is_array($row) || $row === []) {
  5400. return null;
  5401. }
  5402. return [
  5403. 'title' => trim((string)($row['title'] ?? '')),
  5404. 'content' => trim((string)($row['content'] ?? '')),
  5405. ];
  5406. }
  5407. /**
  5408. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5409. */
  5410. protected function buildProcessLinesHtml(array $mergeRows): string
  5411. {
  5412. if (count($mergeRows) <= 1) {
  5413. $r = $mergeRows[0] ?? [];
  5414. if (!is_array($r)) {
  5415. return '';
  5416. }
  5417. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5418. $dw = trim((string)($r['CDW'] ?? ''));
  5419. $gzl = trim((string)($r['NGZL'] ?? ''));
  5420. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5421. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5422. if ($dw !== '') {
  5423. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5424. }
  5425. if ($gzl !== '') {
  5426. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5427. }
  5428. if ($qty !== '') {
  5429. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5430. }
  5431. return $html;
  5432. }
  5433. $rows = '';
  5434. $i = 1;
  5435. foreach ($mergeRows as $r) {
  5436. if (!is_array($r)) {
  5437. continue;
  5438. }
  5439. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5440. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5441. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5442. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5443. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5444. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5445. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5446. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5447. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5448. $i++;
  5449. }
  5450. if ($rows === '') {
  5451. return '';
  5452. }
  5453. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5454. . '<thead><tr style="background:#f5f5f5;">'
  5455. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5456. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5457. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5458. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5459. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5460. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5461. }
  5462. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5463. {
  5464. $sysRq = trim($sysRq);
  5465. if ($sysRq === '') {
  5466. if ($required) {
  5467. $this->error('请选择截止时间');
  5468. }
  5469. return '';
  5470. }
  5471. $ts = strtotime($sysRq);
  5472. if ($ts === false || $ts <= 0) {
  5473. $this->error('截止时间格式无效');
  5474. }
  5475. return date('Y-m-d H:i:s', $ts);
  5476. }
  5477. protected function formatProcuremenSysRqForInput($sysRq): string
  5478. {
  5479. $sr = trim((string)$sysRq);
  5480. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5481. return '';
  5482. }
  5483. $ts = strtotime($sr);
  5484. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5485. }
  5486. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5487. {
  5488. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5489. if ($sr === '') {
  5490. return '—';
  5491. }
  5492. $ts = strtotime($sr);
  5493. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5494. }
  5495. /**
  5496. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5497. *
  5498. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5499. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5500. */
  5501. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5502. {
  5503. return $bundle;
  5504. }
  5505. /**
  5506. * 写入/更新 purchase_order(单道工序行)
  5507. */
  5508. protected function upsertPurchaseOrderFromRow(
  5509. array $row,
  5510. string $sysRqDb,
  5511. $wflowStatus = null,
  5512. ?string $pickTime = null,
  5513. ?array $exists = null
  5514. ): void {
  5515. $ids = $this->extractScydgyRowId($row);
  5516. if (!$this->isValidScydgyRowId($ids)) {
  5517. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5518. }
  5519. if ($exists === null) {
  5520. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5521. }
  5522. $data = [
  5523. 'scydgy_id' => $ids,
  5524. 'CCYDH' => $row['CCYDH'] ?? null,
  5525. 'CYJMC' => $row['CYJMC'] ?? null,
  5526. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5527. 'CDXMC' => $row['CDXMC'] ?? null,
  5528. 'CGYBH' => $row['CGYBH'] ?? null,
  5529. 'CGYMC' => $row['CGYMC'] ?? null,
  5530. 'CDW' => $row['CDW'] ?? null,
  5531. 'NGZL' => $row['NGZL'] ?? null,
  5532. 'CDF' => $row['CDF'] ?? null,
  5533. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5534. 'MBZ' => $row['MBZ'] ?? null,
  5535. 'bwjg' => $row['bwjg'] ?? null,
  5536. 'iStatus' => $row['iStatus'] ?? null,
  5537. 'dStamp' => $row['dStamp'] ?? null,
  5538. 'dputrecord' => $row['dputrecord'] ?? null,
  5539. 'cywyxm' => $row['cywyxm'] ?? null,
  5540. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5541. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5542. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5543. 'sys_rq' => $sysRqDb,
  5544. ];
  5545. if ($wflowStatus !== null && $wflowStatus !== '') {
  5546. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5547. }
  5548. if ($pickTime !== null && $pickTime !== '') {
  5549. $data['pick_time'] = $pickTime;
  5550. $data['pick_company_name'] = '';
  5551. }
  5552. if ($exists) {
  5553. $upd = $data;
  5554. unset($upd['scydgy_id']);
  5555. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5556. } else {
  5557. $data['createtime'] = date('Y-m-d H:i:s');
  5558. Db::table('purchase_order')->insert($data);
  5559. }
  5560. }
  5561. /**
  5562. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5563. *
  5564. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5565. */
  5566. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5567. {
  5568. $toDb = function ($value) {
  5569. if ($value === null) {
  5570. return null;
  5571. }
  5572. if (is_scalar($value)) {
  5573. return $value;
  5574. }
  5575. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5576. };
  5577. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5578. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5579. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5580. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5581. if ($username === '') {
  5582. $username = $this->resolveCustomerContactName($phone, $companyName);
  5583. }
  5584. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5585. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5586. }
  5587. if ($phone === '') {
  5588. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5589. }
  5590. $detailLinks = [];
  5591. foreach ($mergeRows as $row) {
  5592. if (!is_array($row)) {
  5593. continue;
  5594. }
  5595. $sid = $this->extractScydgyRowId($row);
  5596. $detailId = 0;
  5597. if ($skipExisting) {
  5598. try {
  5599. $existsQuery = Db::table('purchase_order_detail')
  5600. ->where('scydgy_id', $sid)
  5601. ->where('company_name', $companyName);
  5602. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5603. $exists = $existsQuery->find();
  5604. } catch (\Throwable $e) {
  5605. $exists = null;
  5606. }
  5607. if (is_array($exists)) {
  5608. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5609. }
  5610. }
  5611. if ($detailId <= 0) {
  5612. $one = [
  5613. 'scydgy_id' => $toDb($sid),
  5614. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5615. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5616. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5617. 'username' => $username !== '' ? $username : null,
  5618. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5619. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5620. 'createtime' => date('Y-m-d H:i:s'),
  5621. 'status' => ProcuremenStatus::POD_UNPICKED,
  5622. 'status_name' => '未提交',
  5623. ];
  5624. Db::table('purchase_order_detail')->insert($one);
  5625. $detailId = (int)Db::getLastInsID();
  5626. }
  5627. $mprocUrl = '';
  5628. if ($buildMobileLinks && $detailId > 0) {
  5629. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5630. }
  5631. $detailLinks[] = [
  5632. 'detail_id' => $detailId,
  5633. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5634. 'url' => $mprocUrl,
  5635. ];
  5636. }
  5637. return $detailLinks;
  5638. }
  5639. /**
  5640. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5641. * @return array<string, mixed>
  5642. */
  5643. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5644. {
  5645. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5646. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5647. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5648. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5649. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5650. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5651. $isMerge = !empty($ctx['is_merge']);
  5652. $contactName = trim((string)($c['username'] ?? ''));
  5653. if ($contactName === '') {
  5654. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5655. }
  5656. $notifyVars = [
  5657. 'company_name' => $companyName,
  5658. 'contact_name' => $contactName,
  5659. 'phone' => $phone,
  5660. 'email' => $toEmail,
  5661. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5662. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5663. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5664. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5665. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5666. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5667. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5668. 'platform_url' => $platformUrl,
  5669. 'platform_links' => $platformLinksPlain,
  5670. 'platform_links_html' => $platformLinksHtml,
  5671. ];
  5672. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5673. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5674. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5675. return [
  5676. 'company_name' => $companyName,
  5677. 'phone' => $phone,
  5678. 'email' => $toEmail,
  5679. 'sms_content' => $smsContent,
  5680. 'mail_plain' => $mailPlain,
  5681. 'mail_body' => $mailBody,
  5682. 'notify_vars' => $notifyVars,
  5683. 'detail_links' => $detailLinks,
  5684. ];
  5685. }
  5686. /**
  5687. * @param array<string, mixed> $chosen
  5688. * @param array<int, array<string, mixed>> $mergeRows
  5689. * @param array{ccydh:string, pos:array} $bundle
  5690. */
  5691. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5692. {
  5693. if (!$sendSms && !$sendEmail) {
  5694. return;
  5695. }
  5696. $companyName = trim((string)($chosen['name'] ?? ''));
  5697. $phone = trim((string)($chosen['phone'] ?? ''));
  5698. $toEmail = trim((string)($chosen['email'] ?? ''));
  5699. if ($companyName === '') {
  5700. throw new \Exception('供应商名称无效');
  5701. }
  5702. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5703. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5704. }
  5705. if ($sendSms && $phone === '') {
  5706. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5707. }
  5708. $sids = [];
  5709. foreach ($mergeRows as $mr) {
  5710. if (!is_array($mr)) {
  5711. continue;
  5712. }
  5713. $sid = $this->extractScydgyRowId($mr);
  5714. if ($this->isValidScydgyRowId($sid)) {
  5715. $sids[$sid] = true;
  5716. }
  5717. }
  5718. if ($sids === []) {
  5719. throw new \Exception('未找到工序行,无法发送通知');
  5720. }
  5721. $sysRqNotify = '';
  5722. $pos = $bundle['pos'] ?? [];
  5723. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5724. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5725. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5726. $ts = strtotime($sr);
  5727. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5728. }
  5729. }
  5730. try {
  5731. $detailsQuery = Db::table('purchase_order_detail')
  5732. ->where('scydgy_id', 'in', array_keys($sids))
  5733. ->where('company_name', $companyName);
  5734. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5735. $details = $detailsQuery->order('id', 'asc')->select();
  5736. } catch (\Throwable $e) {
  5737. $details = [];
  5738. }
  5739. if (!is_array($details) || $details === []) {
  5740. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5741. try {
  5742. $detailsQuery = Db::table('purchase_order_detail')
  5743. ->where('scydgy_id', 'in', array_keys($sids))
  5744. ->where('company_name', $companyName);
  5745. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5746. $details = $detailsQuery->order('id', 'asc')->select();
  5747. } catch (\Throwable $e) {
  5748. $details = [];
  5749. }
  5750. }
  5751. if (!is_array($details) || $details === []) {
  5752. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5753. }
  5754. $detailLinks = [];
  5755. foreach ($details as $d) {
  5756. if (!is_array($d)) {
  5757. continue;
  5758. }
  5759. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5760. if ($detailId <= 0) {
  5761. continue;
  5762. }
  5763. $sid = (int)($d['scydgy_id'] ?? 0);
  5764. $gymc = '';
  5765. foreach ($mergeRows as $mr) {
  5766. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5767. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5768. break;
  5769. }
  5770. }
  5771. $detailLinks[] = [
  5772. 'detail_id' => $detailId,
  5773. 'cgymc' => $gymc,
  5774. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5775. ];
  5776. }
  5777. if ($detailLinks === []) {
  5778. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5779. }
  5780. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5781. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5782. $notifyBundle['email_log_scene'] = $emailLogScene;
  5783. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  5784. $poIdLog = 0;
  5785. $pos = $bundle['pos'] ?? [];
  5786. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5787. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5788. }
  5789. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  5790. if ($sendEmail) {
  5791. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5792. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5793. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5794. }
  5795. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5796. $mailConfig = $this->loadMailerConfig();
  5797. if (!$this->isProcuremenNotifyDryRun()) {
  5798. if (empty($mailConfig['host'])) {
  5799. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5800. }
  5801. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5802. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5803. }
  5804. }
  5805. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5806. }
  5807. if ($sendSms) {
  5808. $this->issueSendSupplierSms($notifyBundle);
  5809. }
  5810. }
  5811. /**
  5812. * @param array<int, array<string, mixed>> $quoteGroups
  5813. * @return array<int, array<string, mixed>>
  5814. */
  5815. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5816. {
  5817. $names = [];
  5818. if (is_string($companiesJson) && $companiesJson !== '') {
  5819. $decoded = json_decode($companiesJson, true);
  5820. if (is_array($decoded)) {
  5821. foreach ($decoded as $nm) {
  5822. $nm = trim((string)$nm);
  5823. if ($nm !== '') {
  5824. $names[] = $nm;
  5825. }
  5826. }
  5827. }
  5828. }
  5829. $names = array_values(array_unique($names));
  5830. if ($names === [] && $selectedCompany !== '') {
  5831. $names = [$selectedCompany];
  5832. }
  5833. if ($names === []) {
  5834. return $quoteGroups;
  5835. }
  5836. $targets = [];
  5837. foreach ($quoteGroups as $g) {
  5838. if (!is_array($g)) {
  5839. continue;
  5840. }
  5841. $cn = trim((string)($g['name'] ?? ''));
  5842. if ($cn !== '' && in_array($cn, $names, true)) {
  5843. $targets[] = $g;
  5844. }
  5845. }
  5846. return $targets;
  5847. }
  5848. /**
  5849. * @return array{pos:array, merge_rows:array, bundle:array}
  5850. */
  5851. protected function loadAuditResendBundle(string $scydgyId): array
  5852. {
  5853. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5854. $pos = $bundle['pos'];
  5855. $mergeRows = $bundle['merge_rows'];
  5856. if ($pos === [] || $mergeRows === []) {
  5857. $this->error('该订单不在待确认供应商状态');
  5858. }
  5859. $sysRqDb = '';
  5860. if (isset($pos[0]) && is_array($pos[0])) {
  5861. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5862. }
  5863. foreach ($pos as $i => $poRow) {
  5864. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5865. $pos[$i]['sys_rq'] = $sysRqDb;
  5866. }
  5867. }
  5868. $bundle['pos'] = $pos;
  5869. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5870. }
  5871. /**
  5872. * @param array<int, array<string, mixed>> $targets
  5873. */
  5874. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5875. {
  5876. if ($targets === []) {
  5877. $this->error('未找到可通知的供应商');
  5878. }
  5879. $notifyErrors = [];
  5880. try {
  5881. $this->notifyDryRunPreview = [];
  5882. foreach ($targets as $g) {
  5883. if (!is_array($g)) {
  5884. continue;
  5885. }
  5886. $cname = trim((string)($g['name'] ?? ''));
  5887. if ($cname === '') {
  5888. continue;
  5889. }
  5890. $chosen = [
  5891. 'name' => $cname,
  5892. 'company_name' => $cname,
  5893. 'email' => trim((string)($g['email'] ?? '')),
  5894. 'phone' => trim((string)($g['phone'] ?? '')),
  5895. 'username' => trim((string)($g['username'] ?? '')),
  5896. ];
  5897. try {
  5898. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  5899. } catch (\Throwable $e) {
  5900. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5901. }
  5902. }
  5903. } catch (\Throwable $e) {
  5904. $this->error('通知发送失败:' . $e->getMessage());
  5905. }
  5906. if ($notifyErrors !== []) {
  5907. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5908. }
  5909. if ($this->isProcuremenNotifyDryRun()) {
  5910. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5911. 'notify_dry_run' => true,
  5912. 'notify_preview' => $this->notifyDryRunPreview,
  5913. ]);
  5914. }
  5915. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5916. }
  5917. /**
  5918. * 协助下发 — 发送短信(一家供应商)
  5919. *
  5920. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5921. */
  5922. protected function issueSendSupplierSms(array $bundle): void
  5923. {
  5924. $companyName = (string)($bundle['company_name'] ?? '');
  5925. $phone = (string)($bundle['phone'] ?? '');
  5926. $smsContent = (string)($bundle['sms_content'] ?? '');
  5927. $this->logIssueNotifyDebug('短信', [
  5928. 'company' => $companyName,
  5929. 'phone' => $phone,
  5930. 'sms_content' => $smsContent,
  5931. ]);
  5932. if ($this->isProcuremenNotifyDryRun()) {
  5933. $this->recordNotifyDryRunPreview([
  5934. 'scene' => 'issue_sms',
  5935. 'company_name' => $companyName,
  5936. 'phone' => $phone,
  5937. 'sms_content' => $smsContent,
  5938. ]);
  5939. return;
  5940. }
  5941. $this->smsbao($phone, $smsContent);
  5942. }
  5943. /**
  5944. * 协助下发 — 发送邮件(一家供应商)
  5945. *
  5946. * @param array<string, mixed> $bundle
  5947. * @param array<string, mixed> $mailConfig
  5948. */
  5949. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5950. {
  5951. $companyName = (string)($bundle['company_name'] ?? '');
  5952. $toEmail = (string)($bundle['email'] ?? '');
  5953. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5954. $mailBody = (string)($bundle['mail_body'] ?? '');
  5955. $this->logIssueNotifyDebug('邮件', [
  5956. 'company' => $companyName,
  5957. 'email' => $toEmail,
  5958. 'mail_subject' => $mailSubject,
  5959. 'mail_body' => $mailPlain,
  5960. ]);
  5961. if ($this->isProcuremenNotifyDryRun()) {
  5962. $this->recordNotifyDryRunPreview([
  5963. 'scene' => 'issue_email',
  5964. 'company_name' => $companyName,
  5965. 'email' => $toEmail,
  5966. 'mail_subject' => $mailSubject,
  5967. 'mail_body' => $mailPlain,
  5968. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5969. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5970. 'detail_links' => $bundle['detail_links'] ?? [],
  5971. ]);
  5972. return;
  5973. }
  5974. $mail = new PHPMailer(true);
  5975. $mail->isSMTP();
  5976. $mail->Host = $mailConfig['host'];
  5977. $mail->SMTPAuth = true;
  5978. $mail->Username = $mailConfig['addr'];
  5979. $mail->Password = $mailConfig['pass'];
  5980. $mail->SMTPSecure = $mailConfig['security'];
  5981. $mail->Port = $mailConfig['port'];
  5982. $mail->CharSet = $mailConfig['charset'];
  5983. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5984. $mail->addAddress($toEmail, $companyName);
  5985. $mail->isHTML(true);
  5986. $mail->Subject = $mailSubject;
  5987. $mail->Body = $mailBody;
  5988. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  5989. $sendOk = true;
  5990. $failReason = '';
  5991. try {
  5992. $mail->send();
  5993. } catch (\Throwable $e) {
  5994. $sendOk = false;
  5995. $failReason = $e->getMessage();
  5996. $this->persistEmailSendLog([
  5997. 'from_email' => $fromEmail,
  5998. 'to_email' => $toEmail,
  5999. 'send_time' => date('Y-m-d H:i:s'),
  6000. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6001. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6002. 'company_name' => $companyName,
  6003. 'mail_subject' => $mailSubject,
  6004. 'status' => 0,
  6005. 'fail_reason' => $failReason,
  6006. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6007. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6008. ]);
  6009. throw $e;
  6010. }
  6011. $this->persistEmailSendLog([
  6012. 'from_email' => $fromEmail,
  6013. 'to_email' => $toEmail,
  6014. 'send_time' => date('Y-m-d H:i:s'),
  6015. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6016. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6017. 'company_name' => $companyName,
  6018. 'mail_subject' => $mailSubject,
  6019. 'status' => 1,
  6020. 'fail_reason' => '',
  6021. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6022. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6023. ]);
  6024. }
  6025. /**
  6026. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6027. *
  6028. * @param array<int, array<string, mixed>> $mergeRows
  6029. * @return array<string, mixed>
  6030. */
  6031. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6032. {
  6033. $head = $mergeRows[0] ?? [];
  6034. $isMerge = count($mergeRows) > 1;
  6035. return [
  6036. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6037. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6038. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6039. 'is_merge' => $isMerge,
  6040. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6041. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6042. 'deadline' => $sysRqNotify,
  6043. ];
  6044. }
  6045. /**
  6046. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6047. *
  6048. * @param array<string, mixed> $data
  6049. */
  6050. protected function logIssueNotifyDebug(string $type, array $data): void
  6051. {
  6052. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6053. return;
  6054. }
  6055. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6056. }
  6057. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6058. {
  6059. try {
  6060. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6061. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6062. return;
  6063. } catch (\Throwable $e) {
  6064. }
  6065. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6066. if (is_file($sqlFile)) {
  6067. $sql = file_get_contents($sqlFile);
  6068. if (is_string($sql) && $sql !== '') {
  6069. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6070. $stmt = trim($stmt);
  6071. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6072. continue;
  6073. }
  6074. try {
  6075. Db::execute($stmt);
  6076. } catch (\Throwable $ignore) {
  6077. }
  6078. }
  6079. }
  6080. }
  6081. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6082. }
  6083. /**
  6084. * @param array<string, mixed> $row
  6085. */
  6086. protected function persistEmailSendLog(array $row): void
  6087. {
  6088. try {
  6089. $this->ensurePurchaseEmailSendLogTableOnce();
  6090. } catch (\Throwable $e) {
  6091. return;
  6092. }
  6093. list($adminId, $adminName) = $this->GetUseName();
  6094. $cut = function ($s, $max) {
  6095. $s = (string)$s;
  6096. if (function_exists('mb_substr')) {
  6097. return mb_substr($s, 0, $max, 'UTF-8');
  6098. }
  6099. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6100. };
  6101. $data = [
  6102. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6103. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6104. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6105. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6106. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6107. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6108. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6109. 'status' => !empty($row['status']) ? 1 : 0,
  6110. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6111. 'admin_id' => (int)$adminId,
  6112. 'admin_name' => $cut($adminName, 64),
  6113. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6114. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6115. 'createtime' => date('Y-m-d H:i:s'),
  6116. ];
  6117. try {
  6118. Db::table('purchase_email_send_log')->insert($data);
  6119. } catch (\Throwable $e) {
  6120. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6121. }
  6122. }
  6123. protected function formatEmailLogSceneText(string $scene): string
  6124. {
  6125. $map = [
  6126. 'pick_issue' => '初选下发',
  6127. 'audit_resend' => '确认页重发',
  6128. ];
  6129. return $map[$scene] ?? $scene;
  6130. }
  6131. /**
  6132. * 邮件发送日志列表
  6133. */
  6134. public function emailLog()
  6135. {
  6136. $this->relationSearch = false;
  6137. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6138. $this->request->filter(['strip_tags', 'trim']);
  6139. $bakModel = $this->model;
  6140. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6141. if ($this->request->isAjax()) {
  6142. $this->ensurePurchaseEmailSendLogTableOnce();
  6143. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6144. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6145. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6146. $list = $this->model
  6147. ->where($where)
  6148. ->order($sortField, $orderDir)
  6149. ->paginate($limit);
  6150. $rows = [];
  6151. foreach ($list->items() as $item) {
  6152. $row = is_array($item) ? $item : $item->toArray();
  6153. $scene = trim((string)($row['scene'] ?? ''));
  6154. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6155. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6156. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6157. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6158. $rows[] = $row;
  6159. }
  6160. $this->model = $bakModel;
  6161. return json(['total' => $list->total(), 'rows' => $rows]);
  6162. }
  6163. $this->model = $bakModel;
  6164. return $this->view->fetch('procuremen/emaillog');
  6165. }
  6166. /**
  6167. * 协助下发弹窗(选多家供应商并通知)
  6168. */
  6169. public function pickReview()
  6170. {
  6171. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6172. $this->error(__('You have no permission'));
  6173. }
  6174. if ($this->request->isPost()) {
  6175. $this->error('请使用弹窗内「确认下发」提交');
  6176. }
  6177. $this->view->assign('pickMode', 1);
  6178. return $this->view->fetch('procuremen/review');
  6179. }
  6180. /**
  6181. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6182. */
  6183. public function add()
  6184. {
  6185. if ($this->request->isPost()) {
  6186. $params = $this->request->post('row/a');
  6187. if (!is_array($params)) {
  6188. $this->error(__('Parameter %s can not be empty', ''));
  6189. }
  6190. [, $adminName] = $this->GetUseName();
  6191. $params['cywyxm'] = $adminName;
  6192. try {
  6193. $sid = $this->saveManualPickOrder($params);
  6194. } catch (\InvalidArgumentException $e) {
  6195. $this->error($e->getMessage());
  6196. } catch (\Throwable $e) {
  6197. $this->error($e->getMessage());
  6198. }
  6199. $this->success('新增成功', '', [
  6200. 'scydgy_id' => $sid,
  6201. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6202. ]);
  6203. }
  6204. [, $adminName] = $this->GetUseName();
  6205. $this->view->assign('adminNickname', $adminName);
  6206. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6207. $this->view->assign('defaultCclbmmc', '营销中心');
  6208. return $this->view->fetch();
  6209. }
  6210. /**
  6211. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6212. */
  6213. public function rfqlist()
  6214. {
  6215. $this->relationSearch = false;
  6216. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6217. $this->request->filter(['strip_tags', 'trim']);
  6218. if ($this->request->isAjax()) {
  6219. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6220. $limit = max(10, min(500, (int)$limit));
  6221. $applyFilters = function ($query) use ($where) {
  6222. $query->where('scydgy_id', '<', 0);
  6223. $query->whereRaw(
  6224. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6225. );
  6226. if (!$this->auth->isSuperAdmin()) {
  6227. [, $adminName] = $this->GetUseName();
  6228. $query->where('cywyxm', $adminName);
  6229. }
  6230. if (!empty($where)) {
  6231. $query->where($where);
  6232. }
  6233. };
  6234. $countQuery = Db::table('purchase_order');
  6235. $applyFilters($countQuery);
  6236. $total = (int)$countQuery->count();
  6237. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6238. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6239. $listQuery = Db::table('purchase_order');
  6240. $applyFilters($listQuery);
  6241. $rows = $listQuery
  6242. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6243. ->order($sortField, $orderDir)
  6244. ->limit($offset, $limit)
  6245. ->select();
  6246. if (!is_array($rows)) {
  6247. $rows = [];
  6248. }
  6249. $out = [];
  6250. foreach ($rows as $r) {
  6251. if (!is_array($r)) {
  6252. continue;
  6253. }
  6254. $sid = (int)($r['scydgy_id'] ?? 0);
  6255. if ($sid >= 0) {
  6256. continue;
  6257. }
  6258. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6259. if ($createdText === '') {
  6260. $createdText = trim((string)($r['dStamp'] ?? ''));
  6261. }
  6262. $out[] = [
  6263. 'id' => (int)($r['id'] ?? 0),
  6264. 'scydgy_id' => $sid,
  6265. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6266. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6267. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6268. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6269. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6270. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6271. 'createtime' => $r['createtime'] ?? null,
  6272. 'createtime_text' => $createdText,
  6273. ];
  6274. }
  6275. return json(['total' => $total, 'rows' => $out]);
  6276. }
  6277. [, $adminName] = $this->GetUseName();
  6278. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6279. $this->view->assign('adminNickname', $adminName);
  6280. return $this->view->fetch('procuremen/rfqlist');
  6281. }
  6282. /**
  6283. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6284. */
  6285. public function rfqlistDetails()
  6286. {
  6287. return $this->details();
  6288. }
  6289. /**
  6290. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6291. */
  6292. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6293. {
  6294. if ($scydgyId >= 0) {
  6295. return;
  6296. }
  6297. try {
  6298. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6299. } catch (\Throwable $e) {
  6300. $po = null;
  6301. }
  6302. if (!is_array($po)) {
  6303. $this->error('订单不存在');
  6304. }
  6305. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6306. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6307. $this->error('订单不存在');
  6308. }
  6309. if ($this->auth->isSuperAdmin()) {
  6310. return;
  6311. }
  6312. [, $adminName] = $this->GetUseName();
  6313. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6314. if ($cywy !== '' && $cywy === $adminName) {
  6315. return;
  6316. }
  6317. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6318. try {
  6319. if ($this->auth->check($rule)) {
  6320. return;
  6321. }
  6322. } catch (\Throwable $e) {
  6323. }
  6324. }
  6325. $this->error('无权查看该订单');
  6326. }
  6327. /**
  6328. * 手工新增协助工序进度文案
  6329. */
  6330. protected function formatProcuremenRfqProgressText(array $row): string
  6331. {
  6332. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6333. return ProcuremenStatus::PO_COMPLETED;
  6334. }
  6335. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6336. return '待采购确认';
  6337. }
  6338. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6339. return '待确认供应商';
  6340. }
  6341. $sid = (int)($row['scydgy_id'] ?? 0);
  6342. if ($sid < 0) {
  6343. try {
  6344. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6345. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6346. $detCnt = (int)$detCntQuery->count();
  6347. if ($detCnt > 0) {
  6348. return '已下发待确认';
  6349. }
  6350. } catch (\Throwable $e) {
  6351. }
  6352. }
  6353. return '待协助下发';
  6354. }
  6355. /**
  6356. * 协助初选列表 — 批量软删除
  6357. */
  6358. public function pickDelete()
  6359. {
  6360. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6361. $this->error(__('Invalid parameters'));
  6362. }
  6363. if (!$this->procuremenCanPickDelete()) {
  6364. $this->error(__('You have no permission'));
  6365. }
  6366. $rowsRaw = $this->request->post('rows_json', '[]');
  6367. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6368. if (!is_array($rows) || $rows === []) {
  6369. $this->error('请至少勾选一条工序');
  6370. }
  6371. $done = 0;
  6372. Db::startTrans();
  6373. try {
  6374. foreach ($rows as $row) {
  6375. if (!is_array($row)) {
  6376. continue;
  6377. }
  6378. $this->softDeleteProcuremenPickRow($row);
  6379. $done++;
  6380. }
  6381. if ($done < 1) {
  6382. throw new \Exception('没有可删除的工序');
  6383. }
  6384. Db::commit();
  6385. } catch (\InvalidArgumentException $e) {
  6386. Db::rollback();
  6387. $this->error($e->getMessage());
  6388. } catch (\Throwable $e) {
  6389. Db::rollback();
  6390. $this->error($e->getMessage());
  6391. }
  6392. $this->pickHiddenScydgySetCache = null;
  6393. $this->success('已删除 ' . $done . ' 条工序');
  6394. }
  6395. /**
  6396. * 下发 — 手工新增工序(弹窗)
  6397. */
  6398. public function pickAdd()
  6399. {
  6400. if ($this->request->isPost()) {
  6401. $params = $this->request->post('row/a');
  6402. if (!is_array($params)) {
  6403. $this->error(__('Parameter %s can not be empty', ''));
  6404. }
  6405. try {
  6406. $sid = $this->saveManualPickOrder($params);
  6407. } catch (\InvalidArgumentException $e) {
  6408. $this->error($e->getMessage());
  6409. } catch (\Throwable $e) {
  6410. $this->error($e->getMessage());
  6411. }
  6412. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6413. }
  6414. return $this->view->fetch('procuremen/pick_add');
  6415. }
  6416. /**
  6417. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6418. */
  6419. public function pickSubmit()
  6420. {
  6421. if (!$this->request->isPost()) {
  6422. $this->error(__('Invalid parameters'));
  6423. }
  6424. // ---------- 接口订单数据 ----------
  6425. $rowJson = $this->request->post('row_json', '');
  6426. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6427. $companiesJson = $this->request->post('companies_json', '[]');
  6428. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6429. $companies = json_decode($companiesJson, true);
  6430. if (!is_array($companies)) {
  6431. $this->error('供应商数据无效');
  6432. }
  6433. $issueCompanies = $this->normalizePickCompanies($companies);
  6434. if ($issueCompanies === []) {
  6435. $this->error('请至少选择一家合作供应商');
  6436. }
  6437. $issueNameLabels = [];
  6438. foreach ($issueCompanies as $pc) {
  6439. $issueNameLabels[] = $pc['name'];
  6440. }
  6441. $issueNamesSummary = implode('、', $issueNameLabels);
  6442. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6443. if ($sysRq === '') {
  6444. $this->error('请选择截止时间');
  6445. }
  6446. $sysRqTs = strtotime($sysRq);
  6447. if ($sysRqTs === false || $sysRqTs <= 0) {
  6448. $this->error('截止时间格式无效');
  6449. }
  6450. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  6451. $isMerge = count($mergeRows) > 1;
  6452. $ccydhLog = '';
  6453. foreach ($mergeRows as $row) {
  6454. if (!is_array($row)) {
  6455. continue;
  6456. }
  6457. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6458. if ($ccydhLog !== '') {
  6459. break;
  6460. }
  6461. }
  6462. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6463. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6464. $logMsg = '下发' . $orderPart . $procPart
  6465. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6466. $issueTime = date('Y-m-d H:i:s');
  6467. $logSidList = [];
  6468. foreach ($mergeRows as $row) {
  6469. if (!is_array($row)) {
  6470. continue;
  6471. }
  6472. $sid = $this->extractScydgyRowId($row);
  6473. if ($this->isValidScydgyRowId($sid)) {
  6474. $logSidList[$sid] = true;
  6475. }
  6476. }
  6477. $existingBySid = [];
  6478. if ($logSidList !== []) {
  6479. try {
  6480. $existingRows = Db::table('purchase_order')
  6481. ->where('scydgy_id', 'in', array_keys($logSidList))
  6482. ->select();
  6483. if (is_array($existingRows)) {
  6484. foreach ($existingRows as $poRow) {
  6485. if (!is_array($poRow)) {
  6486. continue;
  6487. }
  6488. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6489. if ($this->isValidScydgyRowId($sid)) {
  6490. $existingBySid[$sid] = $poRow;
  6491. }
  6492. }
  6493. }
  6494. } catch (\Throwable $e) {
  6495. $existingBySid = [];
  6496. }
  6497. }
  6498. Db::startTrans();
  6499. try {
  6500. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6501. foreach ($mergeRows as $row) {
  6502. if (!is_array($row)) {
  6503. continue;
  6504. }
  6505. $sid = $this->extractScydgyRowId($row);
  6506. $this->upsertPurchaseOrderFromRow(
  6507. $row,
  6508. $sysRqDb,
  6509. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6510. $issueTime,
  6511. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  6512. );
  6513. }
  6514. foreach ($issueCompanies as $c) {
  6515. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6516. }
  6517. Db::commit();
  6518. } catch (\Throwable $e) {
  6519. Db::rollback();
  6520. $this->error($e->getMessage());
  6521. }
  6522. $poIdBySid = [];
  6523. if ($logSidList !== []) {
  6524. try {
  6525. $poIdBySid = Db::table('purchase_order')
  6526. ->where('scydgy_id', 'in', array_keys($logSidList))
  6527. ->column('id', 'scydgy_id');
  6528. } catch (\Throwable $e) {
  6529. $poIdBySid = [];
  6530. }
  6531. }
  6532. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6533. if ($logSidList !== []) {
  6534. list($adminId, $adminName) = $this->GetUseName();
  6535. $cut = function ($s, $max) {
  6536. if (function_exists('mb_substr')) {
  6537. return mb_substr($s, 0, $max, 'UTF-8');
  6538. }
  6539. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6540. };
  6541. $logRows = [];
  6542. $seenLogSid = [];
  6543. foreach ($mergeRows as $row) {
  6544. if (!is_array($row)) {
  6545. continue;
  6546. }
  6547. $ids = $this->extractScydgyRowId($row);
  6548. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6549. continue;
  6550. }
  6551. $seenLogSid[$ids] = true;
  6552. $poIdLog = null;
  6553. if (isset($poIdBySid[$ids])) {
  6554. $tid = (int)$poIdBySid[$ids];
  6555. $poIdLog = $tid > 0 ? $tid : null;
  6556. }
  6557. $logRows[] = [
  6558. 'scydgy_id' => $ids,
  6559. 'purchase_order_id' => $poIdLog,
  6560. 'admin_id' => $adminId,
  6561. 'admin_name' => $cut($adminName, 64),
  6562. 'action' => $cut('issue_submit', 64),
  6563. 'content' => $cut($logMsg, 1000),
  6564. 'createtime' => ProcuremenTime::nowDateTime(),
  6565. ];
  6566. }
  6567. if ($logRows !== []) {
  6568. try {
  6569. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6570. } catch (\Throwable $e) {
  6571. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6572. }
  6573. }
  6574. }
  6575. $notifyErrors = [];
  6576. $posNotify = [];
  6577. if ($logSidList !== []) {
  6578. try {
  6579. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6580. } catch (\Throwable $e) {
  6581. $posNotify = [];
  6582. }
  6583. }
  6584. if (!is_array($posNotify)) {
  6585. $posNotify = [];
  6586. }
  6587. foreach ($posNotify as $i => $prow) {
  6588. if (is_array($posNotify[$i])) {
  6589. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6590. }
  6591. }
  6592. $ccydhPick = '';
  6593. foreach ($mergeRows as $row) {
  6594. if (!is_array($row)) {
  6595. continue;
  6596. }
  6597. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6598. if ($ccydhPick !== '') {
  6599. break;
  6600. }
  6601. }
  6602. $notifyBundleBase = [
  6603. 'ccydh' => $ccydhPick,
  6604. 'pos' => $posNotify,
  6605. 'merge_rows' => $mergeRows,
  6606. ];
  6607. try {
  6608. $this->notifyDryRunPreview = [];
  6609. foreach ($issueCompanies as $c) {
  6610. if (!is_array($c)) {
  6611. continue;
  6612. }
  6613. $cname = trim((string)($c['name'] ?? ''));
  6614. if ($cname === '') {
  6615. continue;
  6616. }
  6617. try {
  6618. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6619. } catch (\Throwable $e) {
  6620. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6621. }
  6622. }
  6623. } catch (\Throwable $e) {
  6624. $this->error('通知发送失败:' . $e->getMessage());
  6625. }
  6626. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6627. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6628. }
  6629. if ($this->isProcuremenNotifyDryRun()) {
  6630. $this->success('【演练模式】已保存并生成通知预览', '', [
  6631. 'notify_dry_run' => true,
  6632. 'notify_preview' => $this->notifyDryRunPreview,
  6633. ]);
  6634. }
  6635. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6636. }
  6637. /**
  6638. * 确认供应商弹窗
  6639. */
  6640. public function auditIssue()
  6641. {
  6642. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6643. if (is_array($ids)) {
  6644. $ids = isset($ids[0]) ? $ids[0] : '';
  6645. }
  6646. $ids = trim((string)$ids);
  6647. if ($ids === '') {
  6648. $this->error(__('Invalid parameters'));
  6649. }
  6650. if ($this->request->isPost()) {
  6651. $this->error('请使用弹窗内「确认」提交');
  6652. }
  6653. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6654. $pos = $bundle['pos'];
  6655. if ($pos === []) {
  6656. $this->error('该订单不在待确认供应商状态');
  6657. }
  6658. $po = $pos[0];
  6659. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6660. if ($quoteGroups === []) {
  6661. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6662. }
  6663. $pickedName = '';
  6664. foreach ($pos as $poRow) {
  6665. if (!is_array($poRow)) {
  6666. continue;
  6667. }
  6668. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6669. if ($pn !== '') {
  6670. $pickedName = $pn;
  6671. break;
  6672. }
  6673. }
  6674. $this->view->assign('po', $po);
  6675. $this->view->assign('scydgyId', $ids);
  6676. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6677. $mergeRows = $bundle['merge_rows'];
  6678. $this->view->assign('processRows', $mergeRows);
  6679. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6680. $this->view->assign('processCount', count($mergeRows));
  6681. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6682. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6683. $this->view->assign('pickedCompanyName', $pickedName);
  6684. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  6685. if ($sysRqForView === '') {
  6686. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6687. }
  6688. $this->view->assign('sysRq', $sysRqForView);
  6689. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6690. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  6691. return $this->view->fetch('procuremen/audit_issue');
  6692. }
  6693. /**
  6694. * 开标双重验证 — 可选验证人列表
  6695. */
  6696. public function bidOpenUsers()
  6697. {
  6698. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6699. $this->error('无权限');
  6700. }
  6701. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  6702. if ($scydgyId !== '') {
  6703. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6704. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6705. $this->success('已完成开标验证', null, [
  6706. 'verified' => 1,
  6707. 'users' => [],
  6708. ]);
  6709. }
  6710. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6711. }
  6712. $this->success('', null, [
  6713. 'verified' => 0,
  6714. 'users' => $this->listBidOpenVerifierCandidates(),
  6715. ]);
  6716. }
  6717. /**
  6718. * 开标双重验证 — 向指定管理员发送短信验证码
  6719. */
  6720. public function bidOpenSendCode()
  6721. {
  6722. if (!$this->request->isPost()) {
  6723. $this->error(__('Invalid parameters'));
  6724. }
  6725. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6726. $this->error('无权限');
  6727. }
  6728. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6729. $adminId = (int)$this->request->post('admin_id', 0);
  6730. if ($scydgyId === '' || $adminId <= 0) {
  6731. $this->error('参数无效');
  6732. }
  6733. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6734. if ($bundle['pos'] === []) {
  6735. $this->error('该订单不在待确认供应商状态');
  6736. }
  6737. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6738. $this->success('已完成开标验证,无需重复发送');
  6739. }
  6740. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6741. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6742. if ($ccydh === '') {
  6743. $this->error('订单号无效');
  6744. }
  6745. $admin = $this->loadBidOpenAdminUser($adminId);
  6746. if ($admin === null) {
  6747. $this->error('验证人无效或未绑定手机号');
  6748. }
  6749. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  6750. $cd = max(30, min(120, $cd));
  6751. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  6752. $this->error('发送过于频繁,请稍后再试');
  6753. }
  6754. $code = (string)random_int(100000, 999999);
  6755. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  6756. $ttl = max(60, min(600, $ttl));
  6757. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  6758. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  6759. try {
  6760. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  6761. } catch (\Throwable $e) {
  6762. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  6763. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  6764. $this->error($e->getMessage());
  6765. }
  6766. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  6767. }
  6768. /**
  6769. * 开标双重验证 — 两人验证码校验并记录
  6770. */
  6771. public function bidOpenVerify()
  6772. {
  6773. if (!$this->request->isPost()) {
  6774. $this->error(__('Invalid parameters'));
  6775. }
  6776. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6777. $this->error('无权限');
  6778. }
  6779. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6780. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  6781. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  6782. $code1 = trim((string)$this->request->post('code1', ''));
  6783. $code2 = trim((string)$this->request->post('code2', ''));
  6784. if ($scydgyId === '') {
  6785. $this->error('参数无效');
  6786. }
  6787. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  6788. $this->error('请选择两位验证人');
  6789. }
  6790. if ($verifier1Id === $verifier2Id) {
  6791. $this->error('两位验证人不能相同');
  6792. }
  6793. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  6794. $this->error('请输入6位短信验证码');
  6795. }
  6796. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6797. if ($bundle['pos'] === []) {
  6798. $this->error('该订单不在待确认供应商状态');
  6799. }
  6800. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6801. if ($ccydh === '') {
  6802. $this->error('订单号无效');
  6803. }
  6804. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6805. $this->success('已完成开标验证');
  6806. }
  6807. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6808. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  6809. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  6810. if ($verifier1 === null || $verifier2 === null) {
  6811. $this->error('验证人无效或未绑定手机号');
  6812. }
  6813. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  6814. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  6815. }
  6816. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  6817. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  6818. }
  6819. try {
  6820. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  6821. } catch (\Throwable $e) {
  6822. $this->error($e->getMessage());
  6823. }
  6824. $this->success('开标验证成功,可查看供应商报价与交货日期');
  6825. }
  6826. /**
  6827. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  6828. */
  6829. public function auditSubmit()
  6830. {
  6831. if (!$this->request->isPost()) {
  6832. $this->error(__('Invalid parameters'));
  6833. }
  6834. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6835. if ($scydgyId === '') {
  6836. $this->error('参数无效');
  6837. }
  6838. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6839. $pos = $bundle['pos'];
  6840. $mergeRows = $bundle['merge_rows'];
  6841. if ($pos === [] || $mergeRows === []) {
  6842. $this->error('该订单不在待确认供应商状态');
  6843. }
  6844. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6845. if ($quoteGroups === []) {
  6846. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  6847. }
  6848. $companyName = trim((string)$this->request->post('selected_company', ''));
  6849. if ($companyName === '') {
  6850. $this->error('请选择一家供应商');
  6851. }
  6852. $matched = null;
  6853. foreach ($quoteGroups as $g) {
  6854. if (!is_array($g)) {
  6855. continue;
  6856. }
  6857. if (trim((string)($g['name'] ?? '')) === $companyName) {
  6858. $matched = $g;
  6859. break;
  6860. }
  6861. }
  6862. if ($matched === null) {
  6863. $this->error('所选供应商不在本单报价列表中');
  6864. }
  6865. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6866. if ($sysRqDb === '') {
  6867. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  6868. } else {
  6869. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  6870. }
  6871. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6872. $this->error('请先完成开标双重验证后再确认供应商');
  6873. }
  6874. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6875. $procCnt = count($mergeRows);
  6876. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6877. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  6878. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  6879. Db::startTrans();
  6880. try {
  6881. foreach ($pos as $poRow) {
  6882. if (!is_array($poRow)) {
  6883. continue;
  6884. }
  6885. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6886. if (!$this->isValidScydgyRowId($sid)) {
  6887. continue;
  6888. }
  6889. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6890. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6891. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6892. 'pick_company_name' => $companyName,
  6893. 'sys_rq' => $sysRqDb,
  6894. ]);
  6895. }
  6896. Db::commit();
  6897. } catch (\Throwable $e) {
  6898. Db::rollback();
  6899. $this->error($e->getMessage());
  6900. }
  6901. foreach ($pos as $poRow) {
  6902. if (!is_array($poRow)) {
  6903. continue;
  6904. }
  6905. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6906. if (!$this->isValidScydgyRowId($sid)) {
  6907. continue;
  6908. }
  6909. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6910. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6911. }
  6912. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6913. }
  6914. /**
  6915. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6916. */
  6917. public function auditResendSms()
  6918. {
  6919. if (!$this->request->isPost()) {
  6920. $this->error(__('Invalid parameters'));
  6921. }
  6922. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6923. if ($scydgyId === '') {
  6924. $this->error('参数无效');
  6925. }
  6926. $loaded = $this->loadAuditResendBundle($scydgyId);
  6927. $mergeRows = $loaded['merge_rows'];
  6928. $bundle = $loaded['bundle'];
  6929. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6930. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6931. if ($quoteGroups === []) {
  6932. $this->error('暂无可通知的供应商');
  6933. }
  6934. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6935. $companiesJson = (string)$this->request->post('companies_json', '');
  6936. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6937. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  6938. }
  6939. /**
  6940. * 确认供应商 — 二次发送邮件(可选单家/批量)
  6941. */
  6942. public function auditResendEmail()
  6943. {
  6944. if (!$this->request->isPost()) {
  6945. $this->error(__('Invalid parameters'));
  6946. }
  6947. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6948. if ($scydgyId === '') {
  6949. $this->error('参数无效');
  6950. }
  6951. $loaded = $this->loadAuditResendBundle($scydgyId);
  6952. $mergeRows = $loaded['merge_rows'];
  6953. $bundle = $loaded['bundle'];
  6954. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6955. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6956. if ($quoteGroups === []) {
  6957. $this->error('暂无可通知的供应商');
  6958. }
  6959. $companiesJson = (string)$this->request->post('companies_json', '');
  6960. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6961. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6962. if ($companiesJson === '' && $selectedCompany === '') {
  6963. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  6964. }
  6965. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  6966. }
  6967. /**
  6968. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  6969. *
  6970. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  6971. * @return array<int, true> 已处理的 scydgy_id 集合
  6972. */
  6973. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  6974. {
  6975. $pos = $bundle['pos'] ?? [];
  6976. if (!is_array($pos) || $pos === []) {
  6977. return [];
  6978. }
  6979. $sids = [];
  6980. foreach ($pos as $poRow) {
  6981. if (!is_array($poRow)) {
  6982. continue;
  6983. }
  6984. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6985. if ($this->isValidScydgyRowId($sid)) {
  6986. $sids[$sid] = true;
  6987. }
  6988. }
  6989. if ($sids === []) {
  6990. return [];
  6991. }
  6992. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6993. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  6994. $suffix = trim((string)$logSuffix, ',, ');
  6995. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  6996. $logMsg .= ':从历史存证退回协助初选';
  6997. } else {
  6998. $logMsg .= ':退回协助初选';
  6999. }
  7000. Db::table('purchase_order')
  7001. ->where('scydgy_id', 'in', array_keys($sids))
  7002. ->update([
  7003. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7004. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7005. 'pick_company_name' => '',
  7006. 'pick_time' => null,
  7007. 'sys_rq' => null,
  7008. 'mod_rq' => null,
  7009. ]);
  7010. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7011. foreach (array_keys($sids) as $sid) {
  7012. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7013. }
  7014. return $sids;
  7015. }
  7016. /**
  7017. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7018. *
  7019. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7020. */
  7021. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7022. {
  7023. $scydgyId = trim($scydgyId);
  7024. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7025. if ($scydgyId === '') {
  7026. return $empty;
  7027. }
  7028. try {
  7029. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7030. } catch (\Throwable $e) {
  7031. $anchor = null;
  7032. }
  7033. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7034. return $empty;
  7035. }
  7036. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7037. if ($ccydh === '') {
  7038. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7039. }
  7040. try {
  7041. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7042. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7043. $pos = $query->order('scydgy_id', 'asc')->select();
  7044. } catch (\Throwable $e) {
  7045. $pos = [$anchor];
  7046. }
  7047. if (!is_array($pos) || $pos === []) {
  7048. $pos = [$anchor];
  7049. }
  7050. return [
  7051. 'ccydh' => $ccydh,
  7052. 'pos' => $pos,
  7053. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7054. ];
  7055. }
  7056. protected function purchaseOrderRowIsCompleted(array $po): bool
  7057. {
  7058. $st = $po['status'] ?? null;
  7059. if ($st === 1 || $st === '1') {
  7060. return true;
  7061. }
  7062. if (is_string($st) && trim($st) === '1') {
  7063. return true;
  7064. }
  7065. return is_numeric($st) && (int)$st === 1;
  7066. }
  7067. /**
  7068. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7069. */
  7070. public function auditAbandon()
  7071. {
  7072. if (!$this->request->isPost()) {
  7073. $this->error(__('Invalid parameters'));
  7074. }
  7075. $anchorIds = [];
  7076. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7077. if ($batchRaw !== '') {
  7078. $decoded = json_decode($batchRaw, true);
  7079. if (is_array($decoded)) {
  7080. foreach ($decoded as $id) {
  7081. $s = trim((string)$id);
  7082. if ($s !== '') {
  7083. $anchorIds[] = $s;
  7084. }
  7085. }
  7086. }
  7087. }
  7088. if ($anchorIds === []) {
  7089. $single = trim((string)$this->request->post('scydgy_id', ''));
  7090. if ($single !== '') {
  7091. $anchorIds[] = $single;
  7092. }
  7093. }
  7094. if ($anchorIds === []) {
  7095. $this->error('请至少选择一条订单');
  7096. }
  7097. $processedCcydh = [];
  7098. $doneOrders = 0;
  7099. $allSids = [];
  7100. Db::startTrans();
  7101. try {
  7102. foreach ($anchorIds as $anchorId) {
  7103. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7104. if (($bundle['pos'] ?? []) === []) {
  7105. continue;
  7106. }
  7107. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7108. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7109. if (isset($processedCcydh[$dedupeKey])) {
  7110. continue;
  7111. }
  7112. $processedCcydh[$dedupeKey] = true;
  7113. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7114. if ($sids === []) {
  7115. continue;
  7116. }
  7117. $doneOrders++;
  7118. foreach (array_keys($sids) as $sid) {
  7119. $allSids[(int)$sid] = true;
  7120. }
  7121. }
  7122. if ($doneOrders < 1) {
  7123. throw new \Exception('所选订单均不在待确认供应商状态');
  7124. }
  7125. Db::commit();
  7126. } catch (\Throwable $e) {
  7127. Db::rollback();
  7128. $this->error($e->getMessage());
  7129. }
  7130. $this->pickHiddenScydgySetCache = null;
  7131. $msg = $doneOrders > 1
  7132. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7133. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7134. $this->success($msg);
  7135. }
  7136. /**
  7137. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7138. */
  7139. public function archiveAbandon()
  7140. {
  7141. if (!$this->request->isPost()) {
  7142. $this->error(__('Invalid parameters'));
  7143. }
  7144. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7145. $this->error(__('You have no permission'));
  7146. }
  7147. $anchorIds = [];
  7148. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7149. if ($batchRaw !== '') {
  7150. $decoded = json_decode($batchRaw, true);
  7151. if (is_array($decoded)) {
  7152. foreach ($decoded as $id) {
  7153. $s = trim((string)$id);
  7154. if ($s !== '') {
  7155. $anchorIds[] = $s;
  7156. }
  7157. }
  7158. }
  7159. }
  7160. if ($anchorIds === []) {
  7161. $single = trim((string)$this->request->post('scydgy_id', ''));
  7162. if ($single !== '') {
  7163. $anchorIds[] = $single;
  7164. }
  7165. }
  7166. if ($anchorIds === []) {
  7167. $this->error('请至少选择一条订单');
  7168. }
  7169. $processedCcydh = [];
  7170. $doneOrders = 0;
  7171. Db::startTrans();
  7172. try {
  7173. foreach ($anchorIds as $anchorId) {
  7174. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7175. if (($bundle['pos'] ?? []) === []) {
  7176. continue;
  7177. }
  7178. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7179. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7180. if (isset($processedCcydh[$dedupeKey])) {
  7181. continue;
  7182. }
  7183. $processedCcydh[$dedupeKey] = true;
  7184. $sids = $this->abandonOrderBundleToPick(
  7185. $bundle,
  7186. 'archive_abandon',
  7187. ',从历史存证退回协助初选'
  7188. );
  7189. if ($sids === []) {
  7190. continue;
  7191. }
  7192. $doneOrders++;
  7193. }
  7194. if ($doneOrders < 1) {
  7195. throw new \Exception('所选订单均不是已完结状态');
  7196. }
  7197. Db::commit();
  7198. } catch (\Throwable $e) {
  7199. Db::rollback();
  7200. $this->error($e->getMessage());
  7201. }
  7202. $this->pickHiddenScydgySetCache = null;
  7203. $msg = $doneOrders > 1
  7204. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7205. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7206. $this->success($msg);
  7207. }
  7208. /**
  7209. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7210. */
  7211. public function purchaseApprovalReject()
  7212. {
  7213. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7214. $this->error(__('Invalid parameters'));
  7215. }
  7216. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7217. $this->error(__('You have no permission'));
  7218. }
  7219. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7220. $decoded = json_decode($batchRaw, true);
  7221. if (!is_array($decoded) || $decoded === []) {
  7222. $this->error('提交数据无效');
  7223. }
  7224. $done = 0;
  7225. Db::startTrans();
  7226. try {
  7227. foreach ($decoded as $item) {
  7228. if (!is_array($item)) {
  7229. continue;
  7230. }
  7231. $sid = (int)($item['scydgy_id'] ?? 0);
  7232. if (!$this->isValidScydgyRowId($sid)) {
  7233. continue;
  7234. }
  7235. $this->runPurchaseApprovalRejectForSid($sid);
  7236. $done++;
  7237. }
  7238. if ($done < 1) {
  7239. throw new \Exception('所选订单均不在待审批状态');
  7240. }
  7241. Db::commit();
  7242. } catch (\Throwable $e) {
  7243. Db::rollback();
  7244. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7245. }
  7246. $this->pickHiddenScydgySetCache = null;
  7247. $this->success('已驳回并退回「协助审批下发」');
  7248. }
  7249. /**
  7250. * @throws \Exception
  7251. */
  7252. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7253. {
  7254. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7255. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7256. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7257. $allIds = $this->purchaseOrderDetail($sid);
  7258. if ($allIds === []) {
  7259. throw new \Exception('未找到下发明细');
  7260. }
  7261. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7262. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7263. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7264. 'pick_company_name' => '',
  7265. ]);
  7266. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7267. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7268. $poId = 0;
  7269. try {
  7270. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7271. if (is_array($po)) {
  7272. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7273. }
  7274. } catch (\Throwable $e) {
  7275. }
  7276. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7277. }
  7278. /**
  7279. * 审核弹窗(旧入口,POST 已关闭)
  7280. */
  7281. public function review()
  7282. {
  7283. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7284. $this->error(__('You have no permission'));
  7285. }
  7286. if ($this->request->isPost()) {
  7287. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7288. }
  7289. $this->view->assign('pickMode', 0);
  7290. return $this->view->fetch('procuremen/review');
  7291. }
  7292. /**
  7293. * 审核弹窗获取公司列表
  7294. */
  7295. public function reviewCompanies()
  7296. {
  7297. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  7298. $this->error(__('You have no permission'));
  7299. }
  7300. if (!$this->request->isAjax()) {
  7301. $this->error(__('Invalid parameters'));
  7302. }
  7303. $list = [];
  7304. try {
  7305. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7306. $rows = Db::table('customer')
  7307. ->where(function ($q) {
  7308. $q->where('status', 1)
  7309. ->whereOr('status', '1')
  7310. ->whereOr('status', '')
  7311. ->whereNull('status');
  7312. })
  7313. ->order('id', 'desc')
  7314. ->select();
  7315. } catch (\Throwable $e) {
  7316. $this->success('', '', []);
  7317. return;
  7318. }
  7319. if (!is_array($rows)) {
  7320. $this->success('', '', []);
  7321. return;
  7322. }
  7323. $detailColCandidates = [
  7324. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7325. 'company_detail', 'company_desc', 'address',
  7326. ];
  7327. foreach ($rows as $row) {
  7328. if (!is_array($row)) {
  7329. continue;
  7330. }
  7331. $norm = [];
  7332. foreach ($row as $k => $v) {
  7333. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7334. }
  7335. $row = $norm;
  7336. $st = $row['status'] ?? '';
  7337. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7338. continue;
  7339. }
  7340. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7341. if ($payload === null) {
  7342. continue;
  7343. }
  7344. $detail = '';
  7345. foreach ($detailColCandidates as $dk) {
  7346. if (!isset($row[$dk])) {
  7347. continue;
  7348. }
  7349. $dv = trim((string)$row[$dk]);
  7350. if ($dv !== '') {
  7351. $detail = $dv;
  7352. break;
  7353. }
  7354. }
  7355. $payload['detail'] = $detail;
  7356. $list[] = $this->maskSupplierContactFields($payload);
  7357. }
  7358. $this->success('', '', $list);
  7359. }
  7360. /**
  7361. * 采购确认-下发明细弹窗:
  7362. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7363. */
  7364. public function outward_detail()
  7365. {
  7366. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7367. if (is_array($ids)) {
  7368. $ids = isset($ids[0]) ? $ids[0] : '';
  7369. }
  7370. $ids = trim((string)$ids);
  7371. if ($ids === '') {
  7372. $this->error(__('Invalid parameters'));
  7373. }
  7374. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7375. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7376. $wffTab = 'all';
  7377. }
  7378. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7379. $purchaseOrderId = 0;
  7380. $po = null;
  7381. try {
  7382. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7383. if (is_array($po)) {
  7384. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7385. }
  7386. } catch (\Throwable $e) {
  7387. $purchaseOrderId = 0;
  7388. $po = null;
  7389. }
  7390. if (!$isPurchaseConfirm && is_array($po)) {
  7391. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7392. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7393. $isPurchaseConfirm = true;
  7394. }
  7395. }
  7396. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7397. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7398. $confirmProcessCount = 1;
  7399. $confirmPickGroups = [];
  7400. $processDisplayRows = [];
  7401. $allDetailsBySid = [];
  7402. $requiredSidList = [];
  7403. $sidList = [$ids];
  7404. if ($isPurchaseConfirm) {
  7405. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7406. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7407. if ($mergeRows !== []) {
  7408. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7409. }
  7410. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7411. if ($confirmBundle['pos'] !== []) {
  7412. $sidList = [];
  7413. foreach ($confirmBundle['pos'] as $poRow) {
  7414. if (!is_array($poRow)) {
  7415. continue;
  7416. }
  7417. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7418. if (!$this->isValidScydgyRowId($sid)) {
  7419. continue;
  7420. }
  7421. $sidList[] = (string)$sid;
  7422. $requiredSidList[] = $sid;
  7423. }
  7424. }
  7425. if ($sidList === []) {
  7426. $sidList = [$ids];
  7427. $requiredSidList = [(int)$ids];
  7428. }
  7429. $confirmProcessCount = max(1, count($requiredSidList));
  7430. if (is_array($po) && $purchaseOrderId <= 0) {
  7431. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7432. }
  7433. }
  7434. $rows = [];
  7435. try {
  7436. if (count($sidList) === 1) {
  7437. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7438. } else {
  7439. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7440. }
  7441. } catch (\Throwable $e) {
  7442. $rows = [];
  7443. }
  7444. if ($isPurchaseConfirm) {
  7445. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7446. }
  7447. foreach ($rows as &$r) {
  7448. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7449. $r['id'] = $r['ID'];
  7450. }
  7451. if (isset($r['createtime'])) {
  7452. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7453. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7454. } else {
  7455. $r['createtime_text'] = (string)$r['createtime'];
  7456. }
  7457. } else {
  7458. $r['createtime_text'] = '';
  7459. }
  7460. if (is_array($r)) {
  7461. $r = $this->maskSupplierContactFields($r);
  7462. }
  7463. }
  7464. unset($r);
  7465. $pickedCompanyName = '';
  7466. if ($isPurchaseConfirm) {
  7467. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7468. if (!is_array($poRow)) {
  7469. continue;
  7470. }
  7471. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7472. if ($pn !== '') {
  7473. $pickedCompanyName = $pn;
  7474. break;
  7475. }
  7476. }
  7477. }
  7478. $this->view->assign('rows', $rows ?: []);
  7479. $this->view->assign('rowCount', count($rows ?: []));
  7480. $this->view->assign('scydgyId', $ids);
  7481. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7482. $this->view->assign('headTitle', $headTitle);
  7483. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7484. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7485. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7486. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7487. $this->view->assign('processDisplayRows', $processDisplayRows);
  7488. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  7489. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  7490. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  7491. $sysRqDisplay = '—';
  7492. if ($isPurchaseConfirm) {
  7493. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  7494. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  7495. );
  7496. }
  7497. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  7498. $this->view->assign('sysRq', $isPurchaseConfirm
  7499. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  7500. : '');
  7501. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  7502. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  7503. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  7504. if ($isPurchaseConfirm) {
  7505. return $this->view->fetch();
  7506. }
  7507. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7508. $this->view->engine->layout(false);
  7509. try {
  7510. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  7511. $this->view->assign('dialogBody', $bodyHtml);
  7512. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  7513. } finally {
  7514. if ($restoreLayout) {
  7515. $this->view->engine->layout($restoreLayout);
  7516. }
  7517. }
  7518. }
  7519. /**
  7520. * 月度导出记录表(不存在时自动创建)
  7521. */
  7522. protected function ensurePurchaseMonthExportLogTable(): void
  7523. {
  7524. try {
  7525. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  7526. } catch (\Throwable $e) {
  7527. Db::execute(
  7528. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  7529. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  7530. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  7531. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  7532. `admin_name` varchar(64) NOT NULL DEFAULT '',
  7533. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  7534. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  7535. `createtime` int(10) unsigned DEFAULT NULL,
  7536. PRIMARY KEY (`id`),
  7537. KEY `idx_ym` (`ym`),
  7538. KEY `idx_ct` (`createtime`)
  7539. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  7540. );
  7541. }
  7542. }
  7543. /**
  7544. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  7545. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  7546. */
  7547. public function export_month_outward()
  7548. {
  7549. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  7550. $this->error(__('You have no permission'));
  7551. }
  7552. $this->request->filter(['strip_tags', 'trim']);
  7553. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  7554. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  7555. $ym = date('Y-m');
  7556. }
  7557. $dbRows = [];
  7558. try {
  7559. $query = Db::table('purchase_order');
  7560. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7561. $dbRows = $query->select();
  7562. } catch (\Throwable $e) {
  7563. $dbRows = [];
  7564. }
  7565. if (!is_array($dbRows)) {
  7566. $dbRows = [];
  7567. }
  7568. $completeTsMap = [];
  7569. $sidList = [];
  7570. foreach ($dbRows as $dbRow) {
  7571. if (!is_array($dbRow)) {
  7572. continue;
  7573. }
  7574. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  7575. if ($sid > 0) {
  7576. $sidList[$sid] = true;
  7577. }
  7578. }
  7579. if ($sidList !== []) {
  7580. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  7581. }
  7582. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  7583. if (!is_array($dbRow)) {
  7584. return false;
  7585. }
  7586. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  7587. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  7588. }));
  7589. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  7590. $filtered = $pool;
  7591. $mainBySid = [];
  7592. foreach ($filtered as $rw) {
  7593. if (!is_array($rw)) {
  7594. continue;
  7595. }
  7596. $rid = (int)($rw['ID'] ?? 0);
  7597. if ($rid > 0) {
  7598. $mainBySid[$rid] = $rw;
  7599. }
  7600. }
  7601. if ($mainBySid === []) {
  7602. $detailRows = [];
  7603. } else {
  7604. try {
  7605. $detailRows = Db::table('purchase_order_detail')
  7606. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7607. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7608. ->order('status', 'desc')
  7609. ->order('CCYDH', 'asc')
  7610. ->order('company_name', 'asc')
  7611. ->order('id', 'asc')
  7612. ->select();
  7613. } catch (\Throwable $e) {
  7614. try {
  7615. $detailRows = Db::table('purchase_order_detail')
  7616. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7617. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7618. ->order('status', 'desc')
  7619. ->order('CCYDH', 'asc')
  7620. ->order('company_name', 'asc')
  7621. ->order('ID', 'asc')
  7622. ->select();
  7623. } catch (\Throwable $e2) {
  7624. $detailRows = [];
  7625. }
  7626. }
  7627. }
  7628. if (!is_array($detailRows)) {
  7629. $detailRows = [];
  7630. }
  7631. $exportLines = [];
  7632. $detailSidSeen = [];
  7633. foreach ($detailRows as $dr) {
  7634. if (!is_array($dr)) {
  7635. continue;
  7636. }
  7637. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7638. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7639. continue;
  7640. }
  7641. if (isset($detailSidSeen[$sid])) {
  7642. continue;
  7643. }
  7644. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  7645. continue;
  7646. }
  7647. $detailSidSeen[$sid] = true;
  7648. $m = $mainBySid[$sid];
  7649. $exportLines[] = [
  7650. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7651. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7652. 'company_name' => (string)($dr['company_name'] ?? ''),
  7653. 'CDF' => (string)($m['CDF'] ?? ''),
  7654. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7655. 'gx' => $this->procuremenExportGxText($m),
  7656. 'detail' => $dr,
  7657. ];
  7658. }
  7659. foreach ($detailRows as $dr) {
  7660. if (!is_array($dr)) {
  7661. continue;
  7662. }
  7663. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7664. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  7665. continue;
  7666. }
  7667. $detailSidSeen[$sid] = true;
  7668. $m = $mainBySid[$sid];
  7669. $exportLines[] = [
  7670. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7671. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7672. 'company_name' => (string)($dr['company_name'] ?? ''),
  7673. 'CDF' => (string)($m['CDF'] ?? ''),
  7674. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7675. 'gx' => $this->procuremenExportGxText($m),
  7676. 'detail' => $dr,
  7677. ];
  7678. }
  7679. foreach ($mainBySid as $sid => $m) {
  7680. if (isset($detailSidSeen[$sid])) {
  7681. continue;
  7682. }
  7683. $company = trim((string)($m['pick_company_name'] ?? ''));
  7684. $exportLines[] = [
  7685. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  7686. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  7687. 'company_name' => $company,
  7688. 'CDF' => (string)($m['CDF'] ?? ''),
  7689. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7690. 'gx' => $this->procuremenExportGxText($m),
  7691. 'detail' => [],
  7692. ];
  7693. }
  7694. $groups = [];
  7695. foreach ($exportLines as $line) {
  7696. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  7697. if (!isset($groups[$k])) {
  7698. $groups[$k] = [];
  7699. }
  7700. $groups[$k][] = $line;
  7701. }
  7702. ksort($groups, SORT_STRING);
  7703. $spreadsheet = new Spreadsheet();
  7704. $sheet = $spreadsheet->getActiveSheet();
  7705. $sheet->setTitle('外协加工明细');
  7706. $mon = (int)substr($ym, 5, 2);
  7707. $sheet->mergeCells('A1:H1');
  7708. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  7709. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  7710. $sheet->getStyle('A1')->getAlignment()
  7711. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7712. ->setVertical(Alignment::VERTICAL_CENTER);
  7713. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  7714. $col = 'A';
  7715. foreach ($headers as $h) {
  7716. $sheet->setCellValue($col . '2', $h);
  7717. $col++;
  7718. }
  7719. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  7720. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7721. $rowNum = 3;
  7722. $sumSubtotalCounts = 0;
  7723. $grandAmount = 0.0;
  7724. $globalSeq = 0;
  7725. if ($groups === []) {
  7726. $sheet->mergeCells('A3:H3');
  7727. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  7728. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7729. $rowNum = 4;
  7730. } else {
  7731. foreach ($groups as $items) {
  7732. if ($items === []) {
  7733. continue;
  7734. }
  7735. $groupLineCount = count($items);
  7736. $subAmount = 0.0;
  7737. foreach ($items as $line) {
  7738. $globalSeq++;
  7739. $dr = $line['detail'];
  7740. $amt = $this->procuremenExportAmount($dr);
  7741. $subAmount += $amt;
  7742. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  7743. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  7744. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  7745. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  7746. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  7747. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  7748. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  7749. $sheet->setCellValue('H' . $rowNum, $amt);
  7750. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  7751. $rowNum++;
  7752. }
  7753. $sumSubtotalCounts += $groupLineCount;
  7754. $grandAmount += $subAmount;
  7755. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7756. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  7757. $sheet->getStyle('G' . $rowNum)->getAlignment()
  7758. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7759. ->setVertical(Alignment::VERTICAL_CENTER);
  7760. $rowNum++;
  7761. }
  7762. }
  7763. $sheet->setCellValue('A' . $rowNum, '总计');
  7764. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  7765. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7766. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  7767. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7768. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  7769. $lastRow = $rowNum;
  7770. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  7771. 'borders' => [
  7772. 'allBorders' => [
  7773. 'borderStyle' => Border::BORDER_THIN,
  7774. 'color' => ['rgb' => '000000'],
  7775. ],
  7776. ],
  7777. ]);
  7778. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7779. if ($lastRow >= 3) {
  7780. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7781. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7782. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7783. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7784. }
  7785. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  7786. $sheet->getColumnDimension('A')->setWidth(7);
  7787. $sheet->getColumnDimension('B')->setWidth(16);
  7788. $sheet->getColumnDimension('C')->setWidth(52);
  7789. $sheet->getColumnDimension('D')->setWidth(32);
  7790. $sheet->getColumnDimension('E')->setWidth(12);
  7791. $sheet->getColumnDimension('F')->setWidth(44);
  7792. $sheet->getColumnDimension('G')->setWidth(26);
  7793. $sheet->getColumnDimension('H')->setWidth(13);
  7794. $sheet->getRowDimension(1)->setRowHeight(28);
  7795. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  7796. $quoteStartRow = $lastRow + 3;
  7797. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  7798. if ($quoteLastRow >= $quoteStartRow) {
  7799. $sheet->getColumnDimension('E')->setWidth(28);
  7800. }
  7801. $ymCompact = str_replace('-', '', $ym);
  7802. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  7803. $filename = $fileBase . '.xlsx';
  7804. try {
  7805. $this->ensurePurchaseMonthExportLogTable();
  7806. list($adminId, $adminName) = $this->GetUseName();
  7807. Db::table('purchase_month_export_log')->insert([
  7808. 'ym' => $ym,
  7809. 'admin_id' => (int)$adminId,
  7810. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  7811. 'row_count' => count($exportLines),
  7812. 'total_amount' => round($grandAmount, 2),
  7813. 'createtime' => time(),
  7814. ]);
  7815. } catch (\Throwable $e) {
  7816. Log::write('month export log: ' . $e->getMessage(), 'error');
  7817. }
  7818. if (ob_get_length()) {
  7819. ob_end_clean();
  7820. }
  7821. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  7822. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  7823. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  7824. header('Cache-Control: max-age=0');
  7825. $writer = new Xlsx($spreadsheet);
  7826. $writer->save('php://output');
  7827. $spreadsheet->disconnectWorksheets();
  7828. unset($spreadsheet);
  7829. exit;
  7830. }
  7831. /**
  7832. * 导出用:工序列文案
  7833. */
  7834. protected function procuremenExportGxText(array $r)
  7835. {
  7836. $a = trim((string)($r['CDXMC'] ?? ''));
  7837. $b = trim((string)($r['CGYMC'] ?? ''));
  7838. if ($a !== '' && $b !== '') {
  7839. return $a . ':' . $b;
  7840. }
  7841. return $a !== '' ? $a : $b;
  7842. }
  7843. /**
  7844. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  7845. */
  7846. protected function procuremenExportAmount(array $r)
  7847. {
  7848. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  7849. if (!array_key_exists($k, $r)) {
  7850. continue;
  7851. }
  7852. $v = $r[$k];
  7853. if ($v === null || $v === '') {
  7854. continue;
  7855. }
  7856. if (is_numeric($v)) {
  7857. return (float)$v;
  7858. }
  7859. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  7860. if ($v !== '' && is_numeric($v)) {
  7861. return (float)$v;
  7862. }
  7863. }
  7864. return 0.0;
  7865. }
  7866. /**
  7867. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  7868. *
  7869. * @param array<int, array<string, mixed>> $detailRows
  7870. * @param array<int, array<string, mixed>> $mainBySid
  7871. * @return array<int, array<string, mixed>>
  7872. */
  7873. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  7874. {
  7875. $lines = [];
  7876. foreach ($detailRows as $dr) {
  7877. if (!is_array($dr)) {
  7878. continue;
  7879. }
  7880. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7881. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7882. continue;
  7883. }
  7884. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  7885. continue;
  7886. }
  7887. $cn = trim((string)($dr['company_name'] ?? ''));
  7888. if ($cn === '') {
  7889. continue;
  7890. }
  7891. $m = $mainBySid[$sid];
  7892. $am = trim((string)($dr['amount'] ?? ''));
  7893. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7894. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  7895. $amountText = $amountFilled
  7896. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7897. : '未填写';
  7898. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  7899. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  7900. if ($deliveryShow === '' && $deliveryRaw !== '') {
  7901. $deliveryShow = $deliveryRaw;
  7902. }
  7903. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  7904. ? $deliveryShow
  7905. : '未填写';
  7906. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  7907. $lines[] = [
  7908. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7909. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7910. 'gx' => $this->procuremenExportGxText($m),
  7911. 'company_name' => $cn,
  7912. 'amount_text' => $amountText,
  7913. 'amount_num' => $amountFilled ? $amountNum : null,
  7914. 'delivery_text' => $deliveryText,
  7915. 'picked_text' => $picked ? '中标' : '未中标',
  7916. 'picked' => $picked,
  7917. ];
  7918. }
  7919. $winnerSupplierByOrder = [];
  7920. foreach ($lines as $line) {
  7921. $dh = trim((string)($line['CCYDH'] ?? ''));
  7922. $cn = trim((string)($line['company_name'] ?? ''));
  7923. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  7924. $winnerSupplierByOrder[$dh][$cn] = true;
  7925. }
  7926. }
  7927. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  7928. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  7929. if ($c !== 0) {
  7930. return $c;
  7931. }
  7932. $dh = trim((string)($a['CCYDH'] ?? ''));
  7933. $aCn = trim((string)($a['company_name'] ?? ''));
  7934. $bCn = trim((string)($b['company_name'] ?? ''));
  7935. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  7936. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  7937. if ($aSupplierWin !== $bSupplierWin) {
  7938. return $aSupplierWin ? -1 : 1;
  7939. }
  7940. $c = strcmp($aCn, $bCn);
  7941. if ($c !== 0) {
  7942. return $c;
  7943. }
  7944. if (!empty($a['picked']) !== !empty($b['picked'])) {
  7945. return !empty($a['picked']) ? -1 : 1;
  7946. }
  7947. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  7948. if ($c !== 0) {
  7949. return $c;
  7950. }
  7951. return 0;
  7952. });
  7953. return $lines;
  7954. }
  7955. /**
  7956. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  7957. *
  7958. * @param array<int, array<string, mixed>> $quoteLines
  7959. */
  7960. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  7961. {
  7962. $mon = (int)substr($ym, 5, 2);
  7963. $titleRow = $startRow;
  7964. $headerRow = $startRow + 1;
  7965. $dataStartRow = $startRow + 2;
  7966. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  7967. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  7968. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  7969. $sheet->getStyle('A' . $titleRow)->getAlignment()
  7970. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7971. ->setVertical(Alignment::VERTICAL_CENTER);
  7972. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  7973. $col = 'A';
  7974. foreach ($headers as $h) {
  7975. $sheet->setCellValue($col . $headerRow, $h);
  7976. $col++;
  7977. }
  7978. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  7979. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7980. $rowNum = $dataStartRow;
  7981. if ($quoteLines === []) {
  7982. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  7983. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  7984. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7985. $rowNum = $dataStartRow + 1;
  7986. } else {
  7987. $i = 0;
  7988. foreach ($quoteLines as $line) {
  7989. $i++;
  7990. $sheet->setCellValue('A' . $rowNum, $i);
  7991. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  7992. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  7993. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  7994. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  7995. if ($line['amount_num'] !== null) {
  7996. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  7997. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  7998. } else {
  7999. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8000. }
  8001. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8002. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8003. if (!empty($line['picked'])) {
  8004. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8005. }
  8006. $rowNum++;
  8007. }
  8008. }
  8009. $lastRow = $rowNum - 1;
  8010. if ($lastRow >= $headerRow) {
  8011. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8012. 'borders' => [
  8013. 'allBorders' => [
  8014. 'borderStyle' => Border::BORDER_THIN,
  8015. 'color' => ['rgb' => '000000'],
  8016. ],
  8017. ],
  8018. ]);
  8019. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8020. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8021. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8022. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8023. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8024. if ($lastRow >= $dataStartRow) {
  8025. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8026. }
  8027. }
  8028. return $lastRow;
  8029. }
  8030. /**
  8031. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8032. */
  8033. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8034. {
  8035. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8036. return;
  8037. }
  8038. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8039. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8040. ->setVertical(Alignment::VERTICAL_CENTER);
  8041. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8042. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8043. ->setVertical(Alignment::VERTICAL_CENTER);
  8044. if ($lastCol > 'B') {
  8045. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8046. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8047. ->setVertical(Alignment::VERTICAL_CENTER);
  8048. }
  8049. }
  8050. /**
  8051. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8052. */
  8053. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8054. {
  8055. $s = trim($ccydh);
  8056. if ($s === '') {
  8057. return 'ORDER';
  8058. }
  8059. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8060. $s = trim($s, '._-');
  8061. if ($s === '') {
  8062. return 'ORDER';
  8063. }
  8064. if (function_exists('mb_substr')) {
  8065. return mb_substr($s, 0, 80, 'UTF-8');
  8066. }
  8067. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8068. }
  8069. /**
  8070. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8071. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8072. *
  8073. * @return array{objectKey: string, webPath: string}
  8074. */
  8075. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8076. {
  8077. $sid = (int)$scydgyId;
  8078. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8079. $y = date('Y');
  8080. $m = date('m');
  8081. $d = date('d');
  8082. $basename = $safeOrder . '_' . $sid . '.pdf';
  8083. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8084. return [
  8085. 'objectKey' => $objectKey,
  8086. 'webPath' => '/' . $objectKey,
  8087. ];
  8088. }
  8089. /**
  8090. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8091. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8092. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8093. *
  8094. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8095. */
  8096. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8097. {
  8098. if (!$this->isValidScydgyRowId($scydgyId)) {
  8099. return '';
  8100. }
  8101. $ids = trim((string)$scydgyId);
  8102. $prep = $this->prepareProcuremenDetailsView($ids);
  8103. if (!$prep['ok']) {
  8104. return '';
  8105. }
  8106. $ccydh = $prep['ccydh'];
  8107. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8108. $objectKey = $paths['objectKey'];
  8109. $webPath = $paths['webPath'];
  8110. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8111. $this->view->assign([
  8112. 'pdf_export' => 1,
  8113. 'pdfMetaLine' => $meta,
  8114. ]);
  8115. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8116. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8117. $this->view->engine->layout(false);
  8118. try {
  8119. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8120. } catch (\Throwable $e) {
  8121. if ($restoreLayout) {
  8122. $this->view->engine->layout($restoreLayout);
  8123. }
  8124. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8125. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8126. return '';
  8127. }
  8128. if ($restoreLayout) {
  8129. $this->view->engine->layout($restoreLayout);
  8130. }
  8131. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8132. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8133. if (!is_dir($tempDir)) {
  8134. @mkdir($tempDir, 0755, true);
  8135. }
  8136. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8137. try {
  8138. $mpdf = new \Mpdf\Mpdf([
  8139. 'mode' => 'utf-8',
  8140. 'format' => 'A4',
  8141. 'margin_left' => 12,
  8142. 'margin_right' => 12,
  8143. 'margin_top' => 14,
  8144. 'margin_bottom' => 14,
  8145. 'tempDir' => $tempDir,
  8146. 'autoScriptToLang' => true,
  8147. 'autoLangToFont' => true,
  8148. ]);
  8149. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8150. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8151. $mpdf->SetBasePath('http://127.0.0.1/');
  8152. $mpdf->WriteHTML($html);
  8153. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8154. } catch (\Throwable $e) {
  8155. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8156. if (is_file($tempPdf)) {
  8157. @unlink($tempPdf);
  8158. }
  8159. return '';
  8160. }
  8161. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8162. if ($ossUrl !== '') {
  8163. @unlink($tempPdf);
  8164. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8165. return $ossUrl;
  8166. }
  8167. $pi = pathinfo($objectKey);
  8168. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8169. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8170. if ($baseFile === '') {
  8171. @unlink($tempPdf);
  8172. return '';
  8173. }
  8174. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8175. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8176. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8177. @unlink($tempPdf);
  8178. return '';
  8179. }
  8180. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8181. if (!@copy($tempPdf, $fullPath)) {
  8182. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8183. @unlink($tempPdf);
  8184. return '';
  8185. }
  8186. @unlink($tempPdf);
  8187. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8188. return $webPath;
  8189. }
  8190. /**
  8191. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8192. */
  8193. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8194. {
  8195. if ($scydgyId <= 0 || $webPath === '') {
  8196. return;
  8197. }
  8198. try {
  8199. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8200. } catch (\Throwable $e) {
  8201. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8202. }
  8203. }
  8204. /**
  8205. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8206. *
  8207. * @param array<string, string> $vars
  8208. * @return array<string, string>
  8209. */
  8210. protected function normalizeSmsTemplateVars(array $vars): array
  8211. {
  8212. $out = [];
  8213. foreach ($vars as $k => $v) {
  8214. $out[(string)$k] = trim((string)$v);
  8215. }
  8216. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8217. $out['contact_name'] = $out['company_name'];
  8218. }
  8219. return $out;
  8220. }
  8221. /**
  8222. * 按手机号或公司名称查 customer 表联系人姓名
  8223. */
  8224. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8225. {
  8226. $phone = trim($phone);
  8227. $companyName = trim($companyName);
  8228. try {
  8229. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8230. $row = Db::table('customer')
  8231. ->where(function ($q) use ($phone) {
  8232. $q->where('phone', $phone)->whereOr('account', $phone);
  8233. })
  8234. ->order('id', 'asc')
  8235. ->find();
  8236. if (is_array($row)) {
  8237. $nm = trim((string)($row['username'] ?? ''));
  8238. if ($nm !== '') {
  8239. return $nm;
  8240. }
  8241. }
  8242. }
  8243. if ($companyName !== '') {
  8244. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8245. if (is_array($row)) {
  8246. return trim((string)($row['username'] ?? ''));
  8247. }
  8248. }
  8249. } catch (\Throwable $e) {
  8250. }
  8251. return '';
  8252. }
  8253. /**
  8254. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8255. */
  8256. protected function plainTextToHtmlEmailBody(string $text): string
  8257. {
  8258. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8259. $parts = explode("\n", $text);
  8260. $out = [];
  8261. foreach ($parts as $line) {
  8262. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8263. $out[] = $line;
  8264. } else {
  8265. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8266. }
  8267. }
  8268. return implode("<br>\n", $out);
  8269. }
  8270. /**
  8271. * 短信场景:去掉链接类变量,避免误填 URL
  8272. *
  8273. * @param array<string, string> $vars
  8274. * @return array<string, string>
  8275. */
  8276. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8277. {
  8278. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8279. return $vars;
  8280. }
  8281. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8282. $vars[$k] = '';
  8283. }
  8284. return $vars;
  8285. }
  8286. /**
  8287. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8288. *
  8289. * @param array<string, string> $vars
  8290. */
  8291. protected function renderNotifyTemplate(string $scene, array $vars): string
  8292. {
  8293. $vars = $this->normalizeSmsTemplateVars($vars);
  8294. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8295. $row = $this->loadNotifyTemplateRow($scene);
  8296. if ($row === null) {
  8297. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8298. }
  8299. $tpl = trim((string)($row['content'] ?? ''));
  8300. if ($tpl === '') {
  8301. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8302. }
  8303. foreach ($vars as $k => $v) {
  8304. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8305. }
  8306. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8307. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8308. return $tpl;
  8309. }
  8310. protected function resolveProcuremenEmailSubject(string $scene): string
  8311. {
  8312. $map = [
  8313. 'review_email' => '您有新的协助加工订单',
  8314. ];
  8315. $subject = trim((string)($map[$scene] ?? ''));
  8316. if ($subject === '') {
  8317. $this->error('未配置邮件主题:' . $scene);
  8318. }
  8319. return $subject;
  8320. }
  8321. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8322. {
  8323. $map = [
  8324. 'review_email' => '协助下发-邮箱',
  8325. 'review_sms' => '协助下发-短信',
  8326. 'confirm_ok' => '采购确认-通过',
  8327. 'confirm_fail' => '采购确认-未通过',
  8328. 'bid_open' => '开标双重验证',
  8329. ];
  8330. $label = $map[$scene] ?? $scene;
  8331. if ($titleRequired) {
  8332. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8333. }
  8334. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8335. }
  8336. /**
  8337. * 是否开启协助通知演练(不发真实短信/邮件)
  8338. */
  8339. protected function isProcuremenNotifyDryRun(): bool
  8340. {
  8341. return (bool)Config::get('procuremen_notify_dry_run');
  8342. }
  8343. /**
  8344. * @param array<string, mixed> $payload
  8345. */
  8346. protected function recordNotifyDryRunPreview(array $payload): void
  8347. {
  8348. $this->notifyDryRunPreview[] = $payload;
  8349. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8350. }
  8351. /**
  8352. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8353. * @throws \Exception
  8354. */
  8355. protected function smsbao($phone, $content)
  8356. {
  8357. if ($this->isProcuremenNotifyDryRun()) {
  8358. $this->recordNotifyDryRunPreview([
  8359. 'scene' => 'sms_only',
  8360. 'phone' => $phone,
  8361. 'sms_content' => $content,
  8362. ]);
  8363. return;
  8364. }
  8365. $statusStr = [
  8366. '0' => '短信发送成功',
  8367. '-1' => '参数不全',
  8368. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8369. '30' => '密码错误',
  8370. '40' => '账号不存在',
  8371. '41' => '余额不足',
  8372. '42' => '帐户已过期',
  8373. '43' => 'IP地址限制',
  8374. '50' => '内容含有敏感词',
  8375. ];
  8376. $smsapi = 'http://api.smsbao.com/';
  8377. $user = 'zhuwei123';
  8378. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8379. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8380. $result = @file_get_contents($sendurl);
  8381. if ($result === false) {
  8382. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  8383. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  8384. }
  8385. $result = trim((string)$result);
  8386. if ($result !== '0') {
  8387. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  8388. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  8389. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  8390. }
  8391. }
  8392. }