Procuremen.php 363 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenTime;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use think\Config;
  11. use think\Cache;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Style\Border;
  15. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  17. use think\Db;
  18. use think\Log;
  19. class Procuremen extends Backend
  20. {
  21. /**
  22. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  23. */
  24. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  25. /**
  26. * Procuremen模型对象
  27. * @var \app\admin\model\Procuremen
  28. */
  29. protected $model = null;
  30. /**
  31. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  32. */
  33. protected $notifyDryRunPreview = [];
  34. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  35. protected $procuremenRedisCache = null;
  36. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  37. protected $pickHiddenScydgySetCache = null;
  38. /** 邮件发送日志表结构已就绪缓存键 */
  39. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  40. /**
  41. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  42. * @var array
  43. */
  44. protected $noNeedRight = [
  45. 'pickreview', 'review', 'reviewcompanies',
  46. ];
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \app\admin\model\Procuremen;
  51. $this->maybeMigrateLegacyWflowStatusText();
  52. $this->assignProcuremenAuthConfig();
  53. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  54. $this->ensurePurchaseEmailSendLogTableOnce();
  55. }
  56. }
  57. /**
  58. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  59. */
  60. protected function maybeMigrateLegacyWflowStatusText(): void
  61. {
  62. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  63. if (is_file($flagFile)) {
  64. return;
  65. }
  66. $map = [
  67. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  68. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  69. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  70. '3' => ProcuremenStatus::WFLOW_APPROVED,
  71. ];
  72. try {
  73. foreach ($map as $num => $text) {
  74. Db::table('purchase_order')
  75. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  76. ->update(['wflow_status' => $text]);
  77. }
  78. @file_put_contents($flagFile, date('c'));
  79. } catch (\Throwable $e) {
  80. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  81. }
  82. }
  83. /**
  84. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  85. *
  86. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  87. */
  88. protected function hasProcuremenPerm(array $actions): bool
  89. {
  90. foreach ($actions as $action) {
  91. $action = strtolower(trim((string)$action));
  92. if ($action === '') {
  93. continue;
  94. }
  95. if (strpos($action, 'procuremen/') !== 0) {
  96. $action = 'procuremen/' . $action;
  97. }
  98. if ($this->auth->check($action)) {
  99. return true;
  100. }
  101. }
  102. $suffixes = [];
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. $action = preg_replace('#^procuremen/#', '', $action);
  106. if ($action !== '') {
  107. $suffixes[$action] = true;
  108. }
  109. }
  110. if ($suffixes === []) {
  111. return false;
  112. }
  113. try {
  114. foreach ($this->auth->getRuleList() as $rule) {
  115. $rule = strtolower((string)$rule);
  116. if (strpos($rule, 'procuremen/') !== 0) {
  117. continue;
  118. }
  119. foreach (array_keys($suffixes) as $suffix) {
  120. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  121. return true;
  122. }
  123. }
  124. }
  125. } catch (\Throwable $e) {
  126. }
  127. return false;
  128. }
  129. /**
  130. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  131. *
  132. * @param string[] $actions
  133. */
  134. protected function hasProcuremenPermStrict(array $actions): bool
  135. {
  136. foreach ($actions as $action) {
  137. $action = strtolower(trim((string)$action));
  138. if ($action === '') {
  139. continue;
  140. }
  141. if (strpos($action, 'procuremen/') !== 0) {
  142. $action = 'procuremen/' . $action;
  143. }
  144. if ($this->auth->check($action)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. /**
  151. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  152. *
  153. * @param string[] $titles
  154. */
  155. protected function authHasAssignedRuleTitle(array $titles): bool
  156. {
  157. $titles = array_values(array_filter(array_map('trim', $titles)));
  158. if ($titles === []) {
  159. return false;
  160. }
  161. try {
  162. $ids = $this->auth->getRuleIds();
  163. if (in_array('*', $ids, true)) {
  164. return true;
  165. }
  166. if ($ids === []) {
  167. return false;
  168. }
  169. $rows = Db::name('auth_rule')
  170. ->where('status', 'normal')
  171. ->whereIn('id', $ids)
  172. ->column('title');
  173. foreach ($rows as $title) {
  174. $t = trim((string)$title);
  175. if ($t !== '' && in_array($t, $titles, true)) {
  176. return true;
  177. }
  178. }
  179. } catch (\Throwable $e) {
  180. }
  181. return false;
  182. }
  183. protected function procuremenCanPickDelete(): bool
  184. {
  185. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  186. return true;
  187. }
  188. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  189. }
  190. protected function procuremenCanComplete(): bool
  191. {
  192. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  193. return true;
  194. }
  195. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  196. }
  197. protected function procuremenCanDispatch(): bool
  198. {
  199. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  200. }
  201. /**
  202. * 前端按钮显隐(Config.procuremenAuth)
  203. */
  204. protected function assignProcuremenAuthConfig(): void
  205. {
  206. $authMap = [
  207. 'pickreview' => $this->procuremenCanDispatch(),
  208. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  209. 'pickdelete' => $this->procuremenCanPickDelete(),
  210. 'completedirectly' => $this->procuremenCanComplete(),
  211. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  212. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  213. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  214. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  215. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  216. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  217. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  218. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  219. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  220. 'details' => $this->hasProcuremenPerm(['details']),
  221. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  222. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  223. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  224. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  225. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  228. 'add' => $this->hasProcuremenPerm(['add']),
  229. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  230. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  231. ];
  232. $this->assignconfig('procuremenAuth', $authMap);
  233. }
  234. /**
  235. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  236. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  237. *
  238. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  239. */
  240. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  241. {
  242. static $mprocCfgLoaded = false;
  243. if (!$mprocCfgLoaded) {
  244. $mprocCfgLoaded = true;
  245. if (is_file(APP_PATH . 'extra/mproc.php')) {
  246. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  247. }
  248. }
  249. $eid = (int)$purchaseOrderDetailId;
  250. $base = $this->resolveMprocMobilePublicBaseUrl();
  251. if ($base === '') {
  252. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  253. }
  254. $path = trim((string)Config::get('mproc.mobile_index_path'));
  255. if ($path === '') {
  256. $path = '/index.php/index/index/index';
  257. } else {
  258. $path = '/' . ltrim($path, '/');
  259. }
  260. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  261. if ($eid > 0) {
  262. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  263. }
  264. return $base . $path . '?main_tab=orders';
  265. }
  266. /**
  267. * 邮件/短信外链:须为带点的公网域名
  268. */
  269. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  270. {
  271. $u = trim((string)$baseUrl);
  272. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  273. return false;
  274. }
  275. $host = parse_url($u, PHP_URL_HOST);
  276. if (!is_string($host) || $host === '') {
  277. return false;
  278. }
  279. if (strcasecmp($host, 'localhost') === 0) {
  280. return false;
  281. }
  282. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  283. return false;
  284. }
  285. if (strpos($host, '.') === false) {
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * 解析用于协助邮件/短信的手机端站点根
  292. */
  293. protected function resolveMprocMobilePublicBaseUrl()
  294. {
  295. $candidates = [];
  296. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  297. $candidates[] = trim((string)Config::get('site.indexurl'));
  298. $cdn = trim((string)Config::get('site.cdnurl'));
  299. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  300. $candidates[] = rtrim($cdn, '/');
  301. }
  302. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  303. $candidates[] = $reqBase;
  304. foreach ($candidates as $c) {
  305. if ($c === '') {
  306. continue;
  307. }
  308. $c = rtrim($c, '/');
  309. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  310. return $c;
  311. }
  312. }
  313. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  314. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  315. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  316. return $reqBase;
  317. }
  318. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  319. return '';
  320. }
  321. /**
  322. * 获取 Redis 中 procuremen_redis
  323. */
  324. protected function ProcuremenRedis(): array
  325. {
  326. if ($this->procuremenRedisCache !== null) {
  327. return $this->procuremenRedisCache;
  328. }
  329. try {
  330. $redis = redis();
  331. $raw = $redis->get('procuremen_redis');
  332. if ($raw === false || $raw === '') {
  333. $this->procuremenRedisCache = [];
  334. return $this->procuremenRedisCache;
  335. }
  336. $decoded = json_decode($raw, true);
  337. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  338. $this->procuremenRedisCache = [];
  339. return $this->procuremenRedisCache;
  340. }
  341. $this->procuremenRedisCache = $decoded['data'];
  342. return $this->procuremenRedisCache;
  343. } catch (\Throwable $e) {
  344. $this->procuremenRedisCache = [];
  345. return $this->procuremenRedisCache;
  346. }
  347. }
  348. /**
  349. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  350. *
  351. * @return array<int, array<string, mixed>>
  352. */
  353. protected function procuremenFetchErpPoolFromDb(): array
  354. {
  355. try {
  356. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  357. $endTime = date('Y-m-d 23:59:59');
  358. $list = Db::table('scydgy')
  359. ->alias('a')
  360. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  361. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  362. ->where([
  363. 'a.bwjg' => 1,
  364. 'a.iEndBz' => 0,
  365. 'a.iType' => 0,
  366. 'a.iStatus' => 10,
  367. ])
  368. ->where('a.dStamp', '>=', $startTime)
  369. ->where('a.dStamp', '<=', $endTime)
  370. ->order('a.dStamp', 'desc')
  371. ->select();
  372. if (!is_array($list)) {
  373. return [];
  374. }
  375. try {
  376. $redis = redis();
  377. $payload = [
  378. 'code' => 200,
  379. 'msg' => 'success',
  380. 'data' => $list,
  381. ];
  382. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  383. $this->procuremenRedisCache = $list;
  384. } catch (\Throwable $e) {
  385. }
  386. return $list;
  387. } catch (\Throwable $e) {
  388. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  389. return [];
  390. }
  391. }
  392. /**
  393. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  394. *
  395. * @return array<int, array<string, mixed>>
  396. */
  397. protected function procuremenEnsureRedisPool(): array
  398. {
  399. $pool = $this->ProcuremenRedis();
  400. if (is_array($pool) && $pool !== []) {
  401. return $pool;
  402. }
  403. static $warmed = false;
  404. if ($warmed) {
  405. return is_array($pool) ? $pool : [];
  406. }
  407. $warmed = true;
  408. return $this->procuremenFetchErpPoolFromDb();
  409. }
  410. /**
  411. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  412. *
  413. * @param array<string, mixed> $row
  414. */
  415. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  416. {
  417. $t = $this->procuremenRowListSortTime($row, $primary);
  418. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  419. return null;
  420. }
  421. $mo = (int)$m[2];
  422. if ($mo < 1 || $mo > 12) {
  423. return null;
  424. }
  425. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  426. }
  427. /**
  428. * @param array<int, array{year:string, months:array}> $sidebar
  429. * @return array<int, array{year:string, months:array}>
  430. */
  431. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return $sidebar;
  436. }
  437. foreach ($sidebar as $block) {
  438. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  439. continue;
  440. }
  441. foreach ($block['months'] as $item) {
  442. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  443. return $sidebar;
  444. }
  445. }
  446. }
  447. $y = substr($ym, 0, 4);
  448. $mo = (int)substr($ym, 5, 2);
  449. $sidebar[] = [
  450. 'year' => $y,
  451. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  452. ];
  453. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  454. }
  455. /**
  456. * @param array<int, array{year:string, months:array}> $sidebar
  457. * @return string[]
  458. */
  459. protected function flattenProcuremenSidebarYms(array $sidebar): array
  460. {
  461. $yms = [];
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (!is_array($item)) {
  468. continue;
  469. }
  470. $ym = trim((string)($item['ym'] ?? ''));
  471. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  472. $yms[$ym] = true;
  473. }
  474. }
  475. }
  476. return array_keys($yms);
  477. }
  478. /**
  479. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  480. */
  481. protected function GetIndexYearMonths()
  482. {
  483. $ymSet = [];
  484. $pool = $this->procuremenEnsureRedisPool();
  485. foreach ($pool as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. foreach ($this->loadPickManualOrderRows() as $r) {
  495. if (!is_array($r)) {
  496. continue;
  497. }
  498. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  499. if ($ym !== null) {
  500. $ymSet[$ym] = true;
  501. }
  502. }
  503. $ymList = array_keys($ymSet);
  504. if ($ymList === []) {
  505. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  506. }
  507. return $this->buildYearMonthSidebar($ymList);
  508. }
  509. /**
  510. * @param string[] $ymList 形如 2026-06
  511. * @return array<int, array{year:string, months:array}>
  512. */
  513. protected function buildYearMonthSidebar(array $ymList): array
  514. {
  515. rsort($ymList, SORT_STRING);
  516. $byYear = [];
  517. foreach ($ymList as $ym) {
  518. $y = substr($ym, 0, 4);
  519. $mo = (int)substr($ym, 5, 2);
  520. if (!isset($byYear[$y])) {
  521. $byYear[$y] = [];
  522. }
  523. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  524. }
  525. krsort($byYear, SORT_NUMERIC);
  526. foreach ($byYear as $y => $items) {
  527. usort($byYear[$y], function ($a, $b) {
  528. return strcmp($b['ym'], $a['ym']);
  529. });
  530. }
  531. $sidebar = [];
  532. foreach ($byYear as $y => $months) {
  533. $sidebar[] = ['year' => $y, 'months' => $months];
  534. }
  535. return $sidebar;
  536. }
  537. /**
  538. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  539. */
  540. protected function GetIssuedOrderYearMonths(string $stage): array
  541. {
  542. $ymSet = [];
  543. try {
  544. $query = Db::table('purchase_order');
  545. $this->applyPurchaseOrderNotDeletedWhere($query);
  546. if ($stage === 'audit') {
  547. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  548. } elseif ($stage === 'confirm') {
  549. $this->applyPurchaseOrderConfirmStageWhere($query);
  550. } else {
  551. return $this->GetIndexYearMonths();
  552. }
  553. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  554. if (is_array($rows)) {
  555. foreach ($rows as $r) {
  556. if (!is_array($r)) {
  557. continue;
  558. }
  559. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  560. if ($ym !== null) {
  561. $ymSet[$ym] = true;
  562. }
  563. }
  564. }
  565. } catch (\Throwable $e) {
  566. $ymSet = [];
  567. }
  568. $ymList = array_keys($ymSet);
  569. if ($ymList === []) {
  570. $def = $this->resolveProcuremenDefaultYm($stage);
  571. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  577. */
  578. protected function resolveProcuremenDefaultYm(string $stage): string
  579. {
  580. if ($stage === 'pick') {
  581. return date('Y-m');
  582. }
  583. try {
  584. $query = Db::table('purchase_order');
  585. $this->applyPurchaseOrderNotDeletedWhere($query);
  586. if ($stage === 'audit') {
  587. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  588. } elseif ($stage === 'confirm') {
  589. $this->applyPurchaseOrderConfirmStageWhere($query);
  590. } else {
  591. return date('Y-m');
  592. }
  593. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  594. if ($latest === null || $latest === '') {
  595. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  596. }
  597. $t = $this->formatProcuremenDetailTime($latest);
  598. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  599. return $m[1] . '-' . $m[2];
  600. }
  601. } catch (\Throwable $e) {
  602. }
  603. return date('Y-m');
  604. }
  605. protected function applyPurchaseOrderNotDeletedWhere($query): void
  606. {
  607. $query->whereRaw(
  608. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  609. );
  610. }
  611. /**
  612. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  613. */
  614. protected function applyPurchaseOrderConfirmStageWhere($query): void
  615. {
  616. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  617. $quoted = [];
  618. foreach ($vals as $v) {
  619. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  620. }
  621. if ($quoted === []) {
  622. $query->whereRaw('1 = 0');
  623. return;
  624. }
  625. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  626. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  627. }
  628. /**
  629. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  630. *
  631. * @param array<string, mixed> $row
  632. * @return array<string, mixed>
  633. */
  634. protected function normalizePurchaseOrderListTimeRow(array $row): array
  635. {
  636. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  637. $pick = trim((string)($row['pick_time'] ?? ''));
  638. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  639. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  640. $t = trim((string)($row[$key] ?? ''));
  641. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  642. $row['pick_time'] = $t;
  643. break;
  644. }
  645. }
  646. }
  647. return $row;
  648. }
  649. /**
  650. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  651. */
  652. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  653. {
  654. if (!in_array($stage, ['audit', 'confirm'], true)) {
  655. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  656. }
  657. if ($pool === []) {
  658. $def = $this->resolveProcuremenDefaultYm($stage);
  659. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  660. }
  661. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  662. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  663. return false;
  664. }
  665. $monthStart = $ym . '-01 00:00:00';
  666. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  667. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  668. return $probe !== [];
  669. };
  670. if ($tryYm($requestedYm)) {
  671. return $requestedYm;
  672. }
  673. $fallback = $this->resolveProcuremenDefaultYm($stage);
  674. if ($tryYm($fallback)) {
  675. return $fallback;
  676. }
  677. $bestYm = '';
  678. $bestTime = '';
  679. foreach ($pool as $row) {
  680. if (!is_array($row)) {
  681. continue;
  682. }
  683. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  684. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  685. continue;
  686. }
  687. $ymRow = $m[1];
  688. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  689. $bestTime = $t;
  690. $bestYm = $ymRow;
  691. }
  692. }
  693. if ($bestYm !== '') {
  694. return $bestYm;
  695. }
  696. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  697. }
  698. protected function isPurchaseOrderDetailVoid(array $row): bool
  699. {
  700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  701. return true;
  702. }
  703. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  704. }
  705. /**
  706. * 仅当前有效下发明细(排除废弃归档)
  707. */
  708. protected function applyActivePurchaseOrderDetailWhere($query): void
  709. {
  710. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  711. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  712. }
  713. /**
  714. * @param array<string, mixed> $detailRow
  715. */
  716. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  717. {
  718. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  719. return false;
  720. }
  721. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  722. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  723. }
  724. /**
  725. * 废弃退回初选:下发明细标记归档,不物理删除
  726. *
  727. * @param array<int, int|string> $scydgyIds
  728. */
  729. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  730. {
  731. $ids = [];
  732. foreach ($scydgyIds as $sid) {
  733. $n = (int)$sid;
  734. if ($this->isValidScydgyRowId($n) || $n < 0) {
  735. $ids[$n] = true;
  736. }
  737. }
  738. if ($ids === []) {
  739. return;
  740. }
  741. $void = ProcuremenStatus::POD_VOID;
  742. Db::table('purchase_order_detail')
  743. ->where('scydgy_id', 'in', array_keys($ids))
  744. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  745. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  746. ->update([
  747. 'status' => $void,
  748. 'status_name' => $void,
  749. ]);
  750. }
  751. /**
  752. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  753. */
  754. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  755. {
  756. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  757. $norm = function (string $col) use ($p): string {
  758. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  759. };
  760. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  761. $parts = [];
  762. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  763. if ($key === 'createtime') {
  764. $parts[] = $createtime;
  765. } else {
  766. $parts[] = $norm($key);
  767. }
  768. }
  769. return 'COALESCE(' . implode(', ', $parts) . ')';
  770. }
  771. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  772. {
  773. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  774. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  775. }
  776. /**
  777. * @return array<int, array<string, mixed>>
  778. */
  779. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  780. {
  781. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  782. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  783. try {
  784. $query = Db::table('purchase_order')->field($fields);
  785. $this->applyPurchaseOrderNotDeletedWhere($query);
  786. if ($stage === 'audit') {
  787. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  788. } elseif ($stage === 'confirm') {
  789. $this->applyPurchaseOrderConfirmStageWhere($query);
  790. } else {
  791. return [];
  792. }
  793. $query->order('pick_time', 'desc')->order('id', 'desc');
  794. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  795. $monthStart = $ym . '-01 00:00:00';
  796. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  797. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  798. }
  799. $rows = $query->select();
  800. } catch (\Throwable $e) {
  801. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  802. $rows = [];
  803. }
  804. return is_array($rows) ? $rows : [];
  805. }
  806. /**
  807. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  808. */
  809. protected function resolveProcuremenListStage(): string
  810. {
  811. $tab = trim((string)$this->request->request('wff_tab', ''));
  812. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  813. return $tab;
  814. }
  815. $action = strtolower((string)$this->request->action());
  816. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  817. return $action;
  818. }
  819. return 'pick';
  820. }
  821. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  822. {
  823. $rootTrue = rtrim((string)$this->request->root(true), '/');
  824. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  825. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  826. $indexPhpRoot = $rootTrue . '/index.php';
  827. }
  828. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  829. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  830. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  831. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  832. $this->view->assign('defaultYm', $defaultYm);
  833. $this->view->assign('sidebarYearMonths', $sidebar);
  834. $this->view->assign('procuremenStage', $stage);
  835. $this->view->assign('procuremenPageTitle', $pageTitle);
  836. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  837. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  838. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  839. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  840. }
  841. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  842. public function pick()
  843. {
  844. $this->request->filter(['strip_tags', 'trim']);
  845. if (!$this->request->isAjax()) {
  846. $this->assignProcuremenListPage('pick', '协助下发');
  847. return $this->view->fetch('procuremen/index');
  848. }
  849. return $this->index();
  850. }
  851. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  852. public function audit()
  853. {
  854. $this->request->filter(['strip_tags', 'trim']);
  855. if (!$this->request->isAjax()) {
  856. $this->assignProcuremenListPage('audit', '确认供应商');
  857. return $this->view->fetch('procuremen/index');
  858. }
  859. return $this->index();
  860. }
  861. /** 采购确认(定标) */
  862. public function confirm()
  863. {
  864. $this->request->filter(['strip_tags', 'trim']);
  865. if (!$this->request->isAjax()) {
  866. $this->assignProcuremenListPage('confirm', '采购确认');
  867. return $this->view->fetch('procuremen/index');
  868. }
  869. return $this->index();
  870. }
  871. /**
  872. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  873. */
  874. public function index()
  875. {
  876. $this->request->filter(['strip_tags', 'trim']);
  877. if (!$this->request->isAjax()) {
  878. $this->assignProcuremenListPage('pick', '协助下发');
  879. return $this->view->fetch('procuremen/index');
  880. }
  881. if ($this->request->request('keyField')) {
  882. return $this->selectpage();
  883. }
  884. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  885. $limit = max(10, min(500, (int)$limit));
  886. $ym = $this->request->request('ym', '');
  887. $ym = is_string($ym) ? trim($ym) : '';
  888. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  889. $wffTab = $this->resolveProcuremenListStage();
  890. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  891. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  892. ? $this->resolveProcuremenDefaultYm($wffTab)
  893. : date('Y-m');
  894. }
  895. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  896. $ym = date('Y-m');
  897. }
  898. $monthStart = $ym . '-01 00:00:00';
  899. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  900. $search = trim((string)$this->request->get('search', ''));
  901. $hasActiveSearch = ($search !== '');
  902. if (!$hasActiveSearch) {
  903. $filterStr = $this->request->get('filter', '');
  904. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  905. $arr = json_decode($filterStr, true);
  906. if (is_array($arr) && count($arr) > 0) {
  907. foreach ($arr as $v) {
  908. if (is_array($v)) {
  909. if (array_filter($v, function ($x) {
  910. return $x !== '' && $x !== null;
  911. })) {
  912. $hasActiveSearch = true;
  913. break;
  914. }
  915. } elseif ($v !== '' && $v !== null) {
  916. $hasActiveSearch = true;
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. }
  923. $applyMonthRange = !$hasActiveSearch;
  924. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  925. $opArr = (array)json_decode($this->request->get('op', ''), true);
  926. try {
  927. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  928. if ($wffTab === 'audit') {
  929. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  930. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  931. );
  932. } elseif ($wffTab === 'confirm') {
  933. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  934. if ($dbRows === []) {
  935. try {
  936. $dbRows = Db::table('purchase_order')
  937. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  938. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  939. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  940. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  941. ->order('pick_time', 'desc')->order('id', 'desc')
  942. ->select();
  943. } catch (\Throwable $e) {
  944. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  945. $dbRows = [];
  946. }
  947. }
  948. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  949. if ($pool === []) {
  950. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  951. }
  952. } else {
  953. $pool = $this->procuremenEnsureRedisPool();
  954. if (!is_array($pool)) {
  955. $pool = [];
  956. }
  957. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  958. $hideSet = $this->loadPickHiddenScydgySet();
  959. if ($pool !== [] && $hideSet !== []) {
  960. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  961. if (!is_array($r)) {
  962. return false;
  963. }
  964. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  965. return $id <= 0 || !isset($hideSet[$id]);
  966. }));
  967. }
  968. $manualPool = $this->loadPickManualOrderRows();
  969. if ($manualPool !== []) {
  970. $pool = array_merge($pool, $manualPool);
  971. }
  972. if ($pool === []) {
  973. return json([
  974. 'total' => 0,
  975. 'rows' => [],
  976. ]);
  977. }
  978. }
  979. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  980. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  981. $monthStart = $ym . '-01 00:00:00';
  982. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  983. }
  984. $filtered = $this->filterProcuremenIndexPool(
  985. $pool,
  986. $monthStart,
  987. $monthEnd,
  988. $applyMonthRange,
  989. $search,
  990. $filterArr,
  991. $opArr,
  992. $listTimePrimary
  993. );
  994. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  995. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  996. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  997. }
  998. $sortField = 'ID';
  999. if (is_string($sort) && $sort !== '') {
  1000. $parts = explode(',', $sort);
  1001. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1002. if ($sortField === '') {
  1003. $sortField = 'ID';
  1004. }
  1005. }
  1006. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1007. $nFiltered = count($filtered);
  1008. if ($nFiltered > 1) {
  1009. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1010. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1011. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1012. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1013. if ($ta === $tb) {
  1014. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1015. }
  1016. if ($ta === '') {
  1017. return 1;
  1018. }
  1019. if ($tb === '') {
  1020. return -1;
  1021. }
  1022. return strcmp($ta, $tb) * $ord;
  1023. });
  1024. } elseif ($sortField === 'ID') {
  1025. $sortKeys = [];
  1026. foreach ($filtered as $i => $row) {
  1027. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1028. }
  1029. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1030. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1031. } elseif ($sortField === 'CCYDH') {
  1032. usort($filtered, function ($a, $b) use ($ord) {
  1033. $sa = trim((string)($a['CCYDH'] ?? ''));
  1034. $sb = trim((string)($b['CCYDH'] ?? ''));
  1035. if ($sa === $sb) {
  1036. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1037. }
  1038. if ($sa === '') {
  1039. return 1;
  1040. }
  1041. if ($sb === '') {
  1042. return -1;
  1043. }
  1044. return strcmp($sa, $sb) * $ord;
  1045. });
  1046. } else {
  1047. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1048. $va = $a[$sortField] ?? null;
  1049. $vb = $b[$sortField] ?? null;
  1050. $sa = (string)$va;
  1051. $sb = (string)$vb;
  1052. if ($sa === $sb) {
  1053. return 0;
  1054. }
  1055. return strcmp($sa, $sb) * $ord;
  1056. });
  1057. }
  1058. }
  1059. $offset = max(0, (int)$offset);
  1060. $limit = max(1, (int)$limit);
  1061. $rows = array_slice($filtered, $offset, $limit);
  1062. foreach ($rows as &$rw) {
  1063. if (!is_array($rw)) {
  1064. continue;
  1065. }
  1066. $rid = (int)($rw['ID'] ?? 0);
  1067. $rw['_iss_out'] = ($wffTab !== 'pick');
  1068. }
  1069. unset($rw);
  1070. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1071. $idList = [];
  1072. foreach ($rows as $rw) {
  1073. if (!is_array($rw)) {
  1074. continue;
  1075. }
  1076. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1077. foreach ($rw['_order_merge_rows'] as $mr) {
  1078. $mid = (int)($mr['ID'] ?? 0);
  1079. if ($this->isValidScydgyRowId($mid)) {
  1080. $idList[$mid] = true;
  1081. }
  1082. }
  1083. }
  1084. $id = (int)($rw['ID'] ?? 0);
  1085. if ($this->isValidScydgyRowId($id)) {
  1086. $idList[$id] = true;
  1087. }
  1088. }
  1089. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1090. foreach ($rows as &$rw) {
  1091. if (!is_array($rw)) {
  1092. continue;
  1093. }
  1094. $mergeIds = [];
  1095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1096. foreach ($rw['_order_merge_rows'] as $mr) {
  1097. $mid = (int)($mr['ID'] ?? 0);
  1098. if ($this->isValidScydgyRowId($mid)) {
  1099. $mergeIds[$mid] = true;
  1100. }
  1101. }
  1102. }
  1103. $rid = (int)($rw['ID'] ?? 0);
  1104. if ($this->isValidScydgyRowId($rid)) {
  1105. $mergeIds[$rid] = true;
  1106. }
  1107. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1108. $rw['po_detail_count'] = $s['cnt'];
  1109. $rw['po_amount_fill_cnt'] = $s['amt'];
  1110. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1111. }
  1112. unset($rw);
  1113. }
  1114. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1115. $idList = [];
  1116. foreach ($rows as $rw) {
  1117. if (!is_array($rw)) {
  1118. continue;
  1119. }
  1120. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1121. foreach ($rw['_order_merge_rows'] as $mr) {
  1122. $mid = (int)($mr['ID'] ?? 0);
  1123. if ($this->isValidScydgyRowId($mid)) {
  1124. $idList[$mid] = true;
  1125. }
  1126. }
  1127. }
  1128. $id = (int)($rw['ID'] ?? 0);
  1129. if ($this->isValidScydgyRowId($id)) {
  1130. $idList[$id] = true;
  1131. }
  1132. }
  1133. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1134. $bidOpenSet = [];
  1135. if ($wffTab === 'audit') {
  1136. $ccydhList = [];
  1137. foreach ($rows as $rw0) {
  1138. if (!is_array($rw0)) {
  1139. continue;
  1140. }
  1141. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1142. if ($c0 !== '') {
  1143. $ccydhList[] = $c0;
  1144. }
  1145. }
  1146. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1147. }
  1148. foreach ($rows as &$rw) {
  1149. if (!is_array($rw)) {
  1150. continue;
  1151. }
  1152. $mergeIds = [];
  1153. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1154. foreach ($rw['_order_merge_rows'] as $mr) {
  1155. $mid = (int)($mr['ID'] ?? 0);
  1156. if ($this->isValidScydgyRowId($mid)) {
  1157. $mergeIds[$mid] = true;
  1158. }
  1159. }
  1160. }
  1161. $rid = (int)($rw['ID'] ?? 0);
  1162. if ($this->isValidScydgyRowId($rid)) {
  1163. $mergeIds[$rid] = true;
  1164. }
  1165. $buckets = [];
  1166. foreach (array_keys($mergeIds) as $mid) {
  1167. if (isset($quoteBucket[$mid])) {
  1168. $buckets[] = $quoteBucket[$mid];
  1169. }
  1170. }
  1171. $supplierText = $buckets !== []
  1172. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1173. : '';
  1174. if ($wffTab === 'confirm') {
  1175. $rw['picked_supplier_name'] = $supplierText;
  1176. } else {
  1177. $rw['notify_supplier_text'] = $supplierText;
  1178. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1179. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1180. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1181. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1182. }
  1183. }
  1184. unset($rw);
  1185. }
  1186. if ($wffTab === 'all' && count($rows) > 0) {
  1187. $this->mergePurchaseOrder($rows);
  1188. }
  1189. if ($wffTab === 'pick' && count($rows) > 0) {
  1190. $this->mergePurchaseOrder($rows);
  1191. }
  1192. foreach ($rows as &$rwClean) {
  1193. if (is_array($rwClean)) {
  1194. unset($rwClean['_order_merge_rows']);
  1195. if (array_key_exists('NGZL', $rwClean)) {
  1196. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1197. }
  1198. }
  1199. }
  1200. unset($rwClean);
  1201. return json([
  1202. 'total' => count($filtered),
  1203. 'rows' => $rows,
  1204. 'activeYm' => $ym,
  1205. ]);
  1206. } catch (\Throwable $e) {
  1207. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1208. return json([
  1209. 'total' => 0,
  1210. 'rows' => [],
  1211. ]);
  1212. }
  1213. }
  1214. /**
  1215. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1216. *
  1217. * @return array<int, true>
  1218. */
  1219. protected function loadPickHiddenScydgySet(): array
  1220. {
  1221. if ($this->pickHiddenScydgySetCache !== null) {
  1222. return $this->pickHiddenScydgySetCache;
  1223. }
  1224. $hideSet = [];
  1225. try {
  1226. $poIds = Db::table('purchase_order')
  1227. ->where(function ($q) {
  1228. $q->whereIn('wflow_status', array_merge(
  1229. ProcuremenStatus::wflowPendingConfirmValues(),
  1230. ProcuremenStatus::wflowPendingApprovalValues()
  1231. ))
  1232. ->whereOr(function ($q1) {
  1233. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1234. })
  1235. ->whereOr(function ($q2) {
  1236. $q2->whereNotNull('pick_time')
  1237. ->where('pick_time', '<>', '')
  1238. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1239. })
  1240. ->whereOr(function ($q3) {
  1241. $q3->whereNotNull('mod_rq')
  1242. ->where('mod_rq', '<>', '')
  1243. ->where('mod_rq', 'not like', '0000-00-00%');
  1244. });
  1245. })
  1246. ->column('scydgy_id');
  1247. if (is_array($poIds)) {
  1248. foreach ($poIds as $pid) {
  1249. $k = (int)$pid;
  1250. if ($k !== 0) {
  1251. $hideSet[$k] = true;
  1252. }
  1253. }
  1254. }
  1255. } catch (\Throwable $e) {
  1256. }
  1257. try {
  1258. $detIdsQuery = Db::table('purchase_order_detail');
  1259. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1260. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1261. if (is_array($detIds)) {
  1262. foreach ($detIds as $pid) {
  1263. $k = (int)$pid;
  1264. if ($this->isValidScydgyRowId($k)) {
  1265. $hideSet[$k] = true;
  1266. }
  1267. }
  1268. }
  1269. } catch (\Throwable $e) {
  1270. }
  1271. $this->pickHiddenScydgySetCache = $hideSet;
  1272. return $hideSet;
  1273. }
  1274. /**
  1275. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1276. *
  1277. * @return array<int, array<string, mixed>>
  1278. */
  1279. protected function loadPickManualOrderRows(): array
  1280. {
  1281. try {
  1282. $dbRows = Db::table('purchase_order')
  1283. ->where('scydgy_id', '<', 0)
  1284. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1285. ->order('scydgy_id', 'asc')
  1286. ->select();
  1287. } catch (\Throwable $e) {
  1288. try {
  1289. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1290. } catch (\Throwable $e2) {
  1291. return [];
  1292. }
  1293. }
  1294. if (!is_array($dbRows) || $dbRows === []) {
  1295. return [];
  1296. }
  1297. $detailSidSet = [];
  1298. try {
  1299. $negIds = [];
  1300. foreach ($dbRows as $dbRow) {
  1301. if (!is_array($dbRow)) {
  1302. continue;
  1303. }
  1304. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1305. if ($sid < 0) {
  1306. $negIds[$sid] = true;
  1307. }
  1308. }
  1309. if ($negIds !== []) {
  1310. $detQuery = Db::table('purchase_order_detail')
  1311. ->where('scydgy_id', 'in', array_keys($negIds));
  1312. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1313. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1314. if (is_array($detRows)) {
  1315. foreach ($detRows as $did) {
  1316. $detailSidSet[(int)$did] = true;
  1317. }
  1318. }
  1319. }
  1320. } catch (\Throwable $e) {
  1321. }
  1322. $pool = [];
  1323. foreach ($dbRows as $dbRow) {
  1324. if (!is_array($dbRow)) {
  1325. continue;
  1326. }
  1327. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1328. if ($sid >= 0) {
  1329. continue;
  1330. }
  1331. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1332. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1333. continue;
  1334. }
  1335. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1336. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1337. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1338. continue;
  1339. }
  1340. if (isset($detailSidSet[$sid])) {
  1341. continue;
  1342. }
  1343. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1344. $r['_is_manual'] = 1;
  1345. $pool[] = $r;
  1346. }
  1347. return $pool;
  1348. }
  1349. /**
  1350. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1351. */
  1352. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1353. {
  1354. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1355. foreach ($keys as $k) {
  1356. $t = trim((string)($row[$k] ?? ''));
  1357. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1358. return $t;
  1359. }
  1360. }
  1361. return '';
  1362. }
  1363. /**
  1364. * 分配手工新增工序行 ID(负数递减)
  1365. */
  1366. protected function allocateManualScydgyId(): int
  1367. {
  1368. try {
  1369. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1370. $min = (int)$min;
  1371. return $min < 0 ? $min - 1 : -1;
  1372. } catch (\Throwable $e) {
  1373. return -1;
  1374. }
  1375. }
  1376. /**
  1377. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1378. */
  1379. protected function allocateManualOrderCcydh(): string
  1380. {
  1381. $prefix = 'YW' . date('Ymd');
  1382. $maxSeq = 0;
  1383. try {
  1384. $rows = Db::table('purchase_order')
  1385. ->where('CCYDH', 'like', $prefix . '%')
  1386. ->column('CCYDH');
  1387. if (is_array($rows)) {
  1388. foreach ($rows as $ccydh) {
  1389. $ccydh = trim((string)$ccydh);
  1390. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1391. $maxSeq = max($maxSeq, (int)$m[1]);
  1392. }
  1393. }
  1394. }
  1395. } catch (\Throwable $e) {
  1396. }
  1397. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1398. }
  1399. /**
  1400. * purchase_order.mod_rq 是否有有效软删除时间
  1401. */
  1402. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1403. {
  1404. $t = trim((string)$modRq);
  1405. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1406. }
  1407. /**
  1408. * 列表行 → purchase_order 写入字段
  1409. *
  1410. * @return array<string, mixed>
  1411. */
  1412. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1413. {
  1414. return [
  1415. 'scydgy_id' => $scydgyId,
  1416. 'CCYDH' => $row['CCYDH'] ?? null,
  1417. 'CYJMC' => $row['CYJMC'] ?? null,
  1418. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1419. 'CDXMC' => $row['CDXMC'] ?? null,
  1420. 'CGYBH' => $row['CGYBH'] ?? null,
  1421. 'CGYMC' => $row['CGYMC'] ?? null,
  1422. 'CDW' => $row['CDW'] ?? null,
  1423. 'NGZL' => $row['NGZL'] ?? null,
  1424. 'CDF' => $row['CDF'] ?? null,
  1425. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1426. 'MBZ' => $row['MBZ'] ?? null,
  1427. 'bwjg' => $row['bwjg'] ?? null,
  1428. 'iStatus' => $row['iStatus'] ?? null,
  1429. 'dStamp' => $row['dStamp'] ?? null,
  1430. 'dputrecord' => $row['dputrecord'] ?? null,
  1431. 'cywyxm' => $row['cywyxm'] ?? null,
  1432. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1433. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1434. ];
  1435. }
  1436. /**
  1437. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1438. *
  1439. * @return array{po:?array<string,mixed>, hidden:bool}
  1440. */
  1441. protected function resolvePickRowPoContext(int $sid): array
  1442. {
  1443. $po = null;
  1444. try {
  1445. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1446. if (is_array($found)) {
  1447. $po = $found;
  1448. }
  1449. } catch (\Throwable $e) {
  1450. }
  1451. $hideSet = $this->loadPickHiddenScydgySet();
  1452. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1453. }
  1454. /**
  1455. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1456. */
  1457. protected function assertPickRowCanDelete(int $sid, array $row): void
  1458. {
  1459. $ctx = $this->resolvePickRowPoContext($sid);
  1460. $po = $ctx['po'];
  1461. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1462. return;
  1463. }
  1464. if (is_array($po)) {
  1465. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1466. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1467. }
  1468. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1469. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1470. }
  1471. }
  1472. if ($ctx['hidden']) {
  1473. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1474. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1475. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1476. }
  1477. }
  1478. /**
  1479. * 初选直接完结前校验
  1480. */
  1481. protected function assertPickRowCanComplete(int $sid, array $row): void
  1482. {
  1483. $ctx = $this->resolvePickRowPoContext($sid);
  1484. $po = $ctx['po'];
  1485. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1486. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1487. }
  1488. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1489. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1490. }
  1491. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1492. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1493. }
  1494. }
  1495. /**
  1496. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1497. */
  1498. protected function softDeleteProcuremenPickRow(array $row): void
  1499. {
  1500. $sid = $this->extractScydgyRowId($row);
  1501. if (!$this->isValidScydgyRowId($sid)) {
  1502. throw new \InvalidArgumentException('无效的行主键');
  1503. }
  1504. $this->assertPickRowCanDelete($sid, $row);
  1505. $po = $this->resolvePickRowPoContext($sid)['po'];
  1506. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1507. return;
  1508. }
  1509. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1510. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1511. }
  1512. $now = date('Y-m-d H:i:s');
  1513. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1514. if (is_array($exists)) {
  1515. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1516. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1517. } else {
  1518. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1519. $data['mod_rq'] = $now;
  1520. $data['createtime'] = $now;
  1521. Db::table('purchase_order')->insert($data);
  1522. $poIdLog = (int)Db::getLastInsID();
  1523. }
  1524. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1525. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1526. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1527. if ($gymcLog !== '') {
  1528. $logTail .= ' / ' . $gymcLog;
  1529. }
  1530. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1531. }
  1532. /**
  1533. * 手工新增协助工序(写入 purchase_order)
  1534. *
  1535. * @param array<string, mixed> $params
  1536. * @return int scydgy_id
  1537. */
  1538. protected function saveManualPickOrder(array $params): int
  1539. {
  1540. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1541. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1542. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1543. if ($ccydh === '') {
  1544. $ccydh = $this->allocateManualOrderCcydh();
  1545. }
  1546. $now = date('Y-m-d H:i:s');
  1547. $sid = $this->allocateManualScydgyId();
  1548. $data = [
  1549. 'scydgy_id' => $sid,
  1550. 'CCYDH' => $ccydh,
  1551. 'CYJMC' => $cyjmc,
  1552. 'CGYMC' => $cgymc,
  1553. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1554. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1555. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1556. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1557. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1558. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1559. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1560. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1561. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1562. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1563. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1564. 'createtime' => $now,
  1565. 'dStamp' => $now,
  1566. 'dputrecord' => $now,
  1567. ];
  1568. Db::table('purchase_order')->insert($data);
  1569. $poId = (int)Db::getLastInsID();
  1570. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1571. return $sid;
  1572. }
  1573. protected function formatProcuremenRowLabel(array $row): string
  1574. {
  1575. $dh = trim((string)($row['CCYDH'] ?? ''));
  1576. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1577. if ($dh !== '' && $gymc !== '') {
  1578. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1579. }
  1580. if ($dh !== '') {
  1581. return '订单「' . $dh . '」';
  1582. }
  1583. if ($gymc !== '') {
  1584. return '工序「' . $gymc . '」';
  1585. }
  1586. $id = $this->extractScydgyRowId($row);
  1587. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1588. }
  1589. /**
  1590. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1591. */
  1592. protected function extractScydgyRowId(array $row): int
  1593. {
  1594. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1595. }
  1596. protected function isValidScydgyRowId(int $id): bool
  1597. {
  1598. return ProcuremenGuard::isValidScydgyId($id);
  1599. }
  1600. protected function isManualScydgyRowId(int $id): bool
  1601. {
  1602. return $id < 0;
  1603. }
  1604. /**
  1605. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1606. *
  1607. * @param int[] $scydgyIds
  1608. * @return array<int, string[]>
  1609. */
  1610. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1611. {
  1612. $out = [];
  1613. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1614. if ($scydgyIds === []) {
  1615. return $out;
  1616. }
  1617. try {
  1618. $rows = Db::table('purchase_order_detail')
  1619. ->where('scydgy_id', 'in', $scydgyIds)
  1620. ->field('scydgy_id,company_name')
  1621. ->order('company_name', 'asc')
  1622. ->select();
  1623. } catch (\Throwable $e) {
  1624. $rows = [];
  1625. }
  1626. if (!is_array($rows)) {
  1627. return $out;
  1628. }
  1629. foreach ($rows as $r) {
  1630. if (!is_array($r)) {
  1631. continue;
  1632. }
  1633. $sid = (int)($r['scydgy_id'] ?? 0);
  1634. $cn = trim((string)($r['company_name'] ?? ''));
  1635. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1636. continue;
  1637. }
  1638. if (!isset($out[$sid])) {
  1639. $out[$sid] = [];
  1640. }
  1641. if (!in_array($cn, $out[$sid], true)) {
  1642. $out[$sid][] = $cn;
  1643. }
  1644. }
  1645. return $out;
  1646. }
  1647. /**
  1648. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1649. *
  1650. * @param string[] $names
  1651. */
  1652. protected function formatNotifySupplierDisplay(array $names): string
  1653. {
  1654. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1655. return trim((string)$n);
  1656. }, $names))));
  1657. if ($names === []) {
  1658. return '';
  1659. }
  1660. sort($names, SORT_STRING);
  1661. return implode("\n", $names);
  1662. }
  1663. /**
  1664. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1665. *
  1666. * @param int[] $scydgyIds
  1667. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1668. */
  1669. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1670. {
  1671. $out = [];
  1672. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1673. if ($scydgyIds === []) {
  1674. return $out;
  1675. }
  1676. try {
  1677. $rows = Db::table('purchase_order_detail')
  1678. ->where('scydgy_id', 'in', $scydgyIds)
  1679. ->field('scydgy_id,company_name,amount')
  1680. ->select();
  1681. } catch (\Throwable $e) {
  1682. $rows = [];
  1683. }
  1684. if (!is_array($rows)) {
  1685. return $out;
  1686. }
  1687. foreach ($rows as $r) {
  1688. if (!is_array($r)) {
  1689. continue;
  1690. }
  1691. $sid = (int)($r['scydgy_id'] ?? 0);
  1692. $cn = trim((string)($r['company_name'] ?? ''));
  1693. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1694. continue;
  1695. }
  1696. if (!isset($out[$sid])) {
  1697. $out[$sid] = ['all' => [], 'quoted' => []];
  1698. }
  1699. $out[$sid]['all'][$cn] = true;
  1700. $am = trim((string)($r['amount'] ?? ''));
  1701. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1702. $out[$sid]['quoted'][$cn] = true;
  1703. }
  1704. }
  1705. return $out;
  1706. }
  1707. /**
  1708. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1709. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1710. */
  1711. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1712. {
  1713. $merged = ['all' => [], 'quoted' => []];
  1714. foreach ($buckets as $b) {
  1715. if (!is_array($b)) {
  1716. continue;
  1717. }
  1718. foreach ($b['all'] ?? [] as $cn => $_) {
  1719. $merged['all'][$cn] = true;
  1720. }
  1721. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1722. $merged['quoted'][$cn] = true;
  1723. }
  1724. }
  1725. return $merged;
  1726. }
  1727. /**
  1728. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1729. */
  1730. protected function formatQuotedSupplierLines(array $bucket): string
  1731. {
  1732. $all = array_keys($bucket['all'] ?? []);
  1733. if ($all === []) {
  1734. return '';
  1735. }
  1736. sort($all, SORT_STRING);
  1737. $lines = [];
  1738. foreach ($all as $cn) {
  1739. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1740. $lines[] = $cn . '(' . $status . ')';
  1741. }
  1742. return implode("\n", $lines);
  1743. }
  1744. /**
  1745. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1746. */
  1747. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1748. {
  1749. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1750. $this->view->engine->layout(false);
  1751. try {
  1752. $bodyHtml = $this->view->fetch($view);
  1753. $this->view->assign('dialogBody', $bodyHtml);
  1754. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1755. return $this->view->fetch('procuremen/dialog_lite_shell');
  1756. } finally {
  1757. if ($restoreLayout) {
  1758. $this->view->engine->layout($restoreLayout);
  1759. }
  1760. }
  1761. }
  1762. /**
  1763. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1764. */
  1765. protected function resolveBundleSysRq(array $bundle): string
  1766. {
  1767. foreach ($bundle['pos'] ?? [] as $po) {
  1768. if (!is_array($po)) {
  1769. continue;
  1770. }
  1771. $sr = trim((string)($po['sys_rq'] ?? ''));
  1772. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1773. return $sr;
  1774. }
  1775. }
  1776. return '';
  1777. }
  1778. /**
  1779. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1780. */
  1781. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1782. {
  1783. $raw = trim((string)$sysRq);
  1784. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1785. return true;
  1786. }
  1787. $ts = strtotime(str_replace('T', ' ', $raw));
  1788. if ($ts === false || $ts <= 0) {
  1789. return true;
  1790. }
  1791. return time() >= $ts;
  1792. }
  1793. /**
  1794. * 开标前校验:必须已过报价截止时间
  1795. *
  1796. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1797. */
  1798. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1799. {
  1800. $sysRq = $this->resolveBundleSysRq($bundle);
  1801. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1802. $this->error('未到截止时间');
  1803. }
  1804. }
  1805. /**
  1806. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1807. *
  1808. * @param array<string, mixed> $d
  1809. * @param string $deliveryYmd
  1810. */
  1811. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1812. {
  1813. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1814. return max(0, (int)$d['lead_days']);
  1815. }
  1816. if ($deliveryYmd === '') {
  1817. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1818. }
  1819. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1820. return null;
  1821. }
  1822. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1823. $t2 = strtotime($m[1] . ' 00:00:00');
  1824. if ($t1 === false || $t2 === false) {
  1825. return null;
  1826. }
  1827. return max(0, (int)round(($t2 - $t1) / 86400));
  1828. }
  1829. /**
  1830. * @param int|null $days
  1831. */
  1832. protected function formatProcuremenLeadDaysText($days): string
  1833. {
  1834. if ($days === null || $days === '') {
  1835. return '未填写';
  1836. }
  1837. if (!is_numeric($days)) {
  1838. return '未填写';
  1839. }
  1840. return ((int)$days) . '天';
  1841. }
  1842. /**
  1843. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  1844. *
  1845. * @param array<string, mixed> $line
  1846. */
  1847. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1848. {
  1849. $amountFilled = !empty($line['amount_filled']);
  1850. $deliveryFilled = !empty($line['delivery_filled']);
  1851. $leadFilled = !empty($line['lead_days_filled']);
  1852. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  1853. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1854. $line['amount_show'] = '';
  1855. if (array_key_exists('amount_text', $line)) {
  1856. $line['amount_text'] = $line['unit_price_text'];
  1857. }
  1858. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1859. $line['delivery_show'] = $deliveryText;
  1860. if (array_key_exists('delivery_text', $line)) {
  1861. $line['delivery_text'] = $deliveryText;
  1862. }
  1863. $line['delivery_ymd'] = '';
  1864. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  1865. $line['lead_days_show'] = $leadText;
  1866. $line['lead_days_text'] = $leadText;
  1867. $line['lead_days'] = '';
  1868. // 小计、操作时间与单价等同属报价信息,开标前不可见
  1869. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  1870. $line['subtotal_num'] = null;
  1871. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  1872. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1873. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1874. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  1875. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  1876. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  1877. $line['amount_filled'] = false;
  1878. $line['delivery_filled'] = false;
  1879. $line['lead_days_filled'] = false;
  1880. $line['is_quoted'] = false;
  1881. if (array_key_exists('quote_label', $line)) {
  1882. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  1883. }
  1884. }
  1885. protected function ensurePurchaseOrderBidOpenTable(): void
  1886. {
  1887. try {
  1888. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1889. } catch (\Throwable $e) {
  1890. Db::execute(
  1891. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1892. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1893. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1894. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1895. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1896. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1897. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1898. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1899. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1900. `createtime` datetime DEFAULT NULL,
  1901. PRIMARY KEY (`id`),
  1902. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1903. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1904. );
  1905. }
  1906. }
  1907. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1908. {
  1909. $ccydh = trim($ccydh);
  1910. if ($ccydh === '') {
  1911. return false;
  1912. }
  1913. $this->ensurePurchaseOrderBidOpenTable();
  1914. try {
  1915. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1916. return is_array($row);
  1917. } catch (\Throwable $e) {
  1918. return false;
  1919. }
  1920. }
  1921. /**
  1922. * 批量查询订单是否已开标验证
  1923. *
  1924. * @param array<int, string> $ccydhs
  1925. * @return array<string, bool> ccydh => true
  1926. */
  1927. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  1928. {
  1929. $set = [];
  1930. $list = [];
  1931. foreach ($ccydhs as $c) {
  1932. $c = trim((string)$c);
  1933. if ($c !== '') {
  1934. $list[$c] = true;
  1935. }
  1936. }
  1937. if ($list === []) {
  1938. return $set;
  1939. }
  1940. $this->ensurePurchaseOrderBidOpenTable();
  1941. try {
  1942. $rows = Db::table('purchase_order_bid_open')
  1943. ->where('ccydh', 'in', array_keys($list))
  1944. ->field('ccydh')
  1945. ->select();
  1946. foreach ($rows as $row) {
  1947. if (!is_array($row)) {
  1948. continue;
  1949. }
  1950. $c = trim((string)($row['ccydh'] ?? ''));
  1951. if ($c !== '') {
  1952. $set[$c] = true;
  1953. }
  1954. }
  1955. } catch (\Throwable $e) {
  1956. return [];
  1957. }
  1958. return $set;
  1959. }
  1960. /**
  1961. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  1962. *
  1963. * @param array<string, mixed> $group
  1964. */
  1965. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  1966. {
  1967. if ($quoteVisible) {
  1968. $group['remark_quote_pending'] = 0;
  1969. return;
  1970. }
  1971. $group['remark'] = '';
  1972. $group['remark_quote_pending'] = 0;
  1973. }
  1974. /**
  1975. * @param array{ccydh?:string} $bundle
  1976. */
  1977. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1978. {
  1979. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1980. }
  1981. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1982. {
  1983. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1984. }
  1985. protected function loadBidOpenAdminUser(int $adminId): ?array
  1986. {
  1987. if ($adminId <= 0) {
  1988. return null;
  1989. }
  1990. try {
  1991. $row = Db::name('admin')->where('id', $adminId)->find();
  1992. } catch (\Throwable $e) {
  1993. return null;
  1994. }
  1995. if (!is_array($row)) {
  1996. return null;
  1997. }
  1998. $status = strtolower(trim((string)($row['status'] ?? '')));
  1999. if ($status !== '' && $status !== 'normal') {
  2000. return null;
  2001. }
  2002. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2003. return null;
  2004. }
  2005. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2006. if (!preg_match('/^1\d{10}$/', $phone)) {
  2007. return null;
  2008. }
  2009. $name = trim((string)($row['nickname'] ?? ''));
  2010. if ($name === '') {
  2011. $name = trim((string)($row['username'] ?? ''));
  2012. }
  2013. return [
  2014. 'id' => (int)$row['id'],
  2015. 'username' => trim((string)($row['username'] ?? '')),
  2016. 'nickname' => $name,
  2017. 'mobile' => $phone,
  2018. ];
  2019. }
  2020. /**
  2021. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2022. */
  2023. protected function bidOpenVerifierAuthGroupRootId(): int
  2024. {
  2025. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2026. return $id > 0 ? $id : 10;
  2027. }
  2028. /**
  2029. * @return int[]
  2030. */
  2031. protected function loadBidOpenVerifierAuthGroupIds(): array
  2032. {
  2033. static $memo = [];
  2034. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2035. if (isset($memo[$rootId])) {
  2036. return $memo[$rootId];
  2037. }
  2038. try {
  2039. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2040. } catch (\Throwable $e) {
  2041. $memo[$rootId] = [$rootId];
  2042. return $memo[$rootId];
  2043. }
  2044. if (!is_array($groups) || $groups === []) {
  2045. $memo[$rootId] = [$rootId];
  2046. return $memo[$rootId];
  2047. }
  2048. $groupList = [];
  2049. foreach ($groups as $g) {
  2050. if (is_array($g)) {
  2051. $groupList[] = $g;
  2052. }
  2053. }
  2054. if ($groupList === []) {
  2055. $memo[$rootId] = [$rootId];
  2056. return $memo[$rootId];
  2057. }
  2058. $tree = \fast\Tree::instance();
  2059. $tree->init($groupList);
  2060. $ids = $tree->getChildrenIds($rootId, true);
  2061. if (!is_array($ids) || $ids === []) {
  2062. $memo[$rootId] = [$rootId];
  2063. return $memo[$rootId];
  2064. }
  2065. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2066. return $memo[$rootId];
  2067. }
  2068. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2069. {
  2070. if ($adminId <= 0) {
  2071. return false;
  2072. }
  2073. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2074. if ($groupIds === []) {
  2075. return false;
  2076. }
  2077. try {
  2078. return (bool)Db::name('auth_group_access')
  2079. ->where('uid', $adminId)
  2080. ->where('group_id', 'in', $groupIds)
  2081. ->count();
  2082. } catch (\Throwable $e) {
  2083. return false;
  2084. }
  2085. }
  2086. /**
  2087. * @return array<int, array<string, mixed>>
  2088. */
  2089. protected function listBidOpenVerifierCandidates(): array
  2090. {
  2091. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2092. if ($groupIds === []) {
  2093. return [];
  2094. }
  2095. try {
  2096. $adminIds = Db::name('auth_group_access')
  2097. ->where('group_id', 'in', $groupIds)
  2098. ->column('uid');
  2099. } catch (\Throwable $e) {
  2100. $adminIds = [];
  2101. }
  2102. $adminIds = is_array($adminIds)
  2103. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2104. : [];
  2105. if ($adminIds === []) {
  2106. return [];
  2107. }
  2108. try {
  2109. $rows = Db::name('admin')
  2110. ->where('status', 'normal')
  2111. ->where('id', 'in', $adminIds)
  2112. ->where('mobile', '<>', '')
  2113. ->order('id', 'asc')
  2114. ->select();
  2115. } catch (\Throwable $e) {
  2116. return [];
  2117. }
  2118. if (!is_array($rows)) {
  2119. return [];
  2120. }
  2121. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2122. $out = [];
  2123. foreach ($rows as $row) {
  2124. if (!is_array($row)) {
  2125. continue;
  2126. }
  2127. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2128. if ($one === null) {
  2129. continue;
  2130. }
  2131. $out[] = [
  2132. 'id' => $one['id'],
  2133. 'username' => $one['username'],
  2134. 'nickname' => $one['nickname'],
  2135. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2136. 'mobile' => mask_phone($one['mobile']),
  2137. ];
  2138. }
  2139. return $out;
  2140. }
  2141. /**
  2142. * @param int[] $adminIds
  2143. * @return array<int, string>
  2144. */
  2145. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2146. {
  2147. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2148. if ($adminIds === []) {
  2149. return [];
  2150. }
  2151. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2152. try {
  2153. $rows = Db::name('auth_group_access')
  2154. ->alias('aga')
  2155. ->join('auth_group ag', 'aga.group_id = ag.id')
  2156. ->where('aga.uid', 'in', $adminIds)
  2157. ->where('aga.group_id', 'in', $groupIds)
  2158. ->field('aga.uid,ag.name')
  2159. ->order('aga.uid', 'asc')
  2160. ->order('aga.group_id', 'asc')
  2161. ->select();
  2162. } catch (\Throwable $e) {
  2163. return [];
  2164. }
  2165. if (!is_array($rows)) {
  2166. return [];
  2167. }
  2168. $out = [];
  2169. foreach ($rows as $row) {
  2170. if (!is_array($row)) {
  2171. continue;
  2172. }
  2173. $uid = (int)($row['uid'] ?? 0);
  2174. $name = trim((string)($row['name'] ?? ''));
  2175. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2176. continue;
  2177. }
  2178. $out[$uid] = $name;
  2179. }
  2180. return $out;
  2181. }
  2182. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2183. {
  2184. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2185. }
  2186. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2187. {
  2188. return 'procuremen_bidopen_wait_' . $adminId;
  2189. }
  2190. protected function renderBidOpenVerifySms(string $code): string
  2191. {
  2192. $tpl = '';
  2193. try {
  2194. $row = $this->loadNotifyTemplateRow('bid_open');
  2195. if (is_array($row)) {
  2196. $tpl = trim((string)($row['content'] ?? ''));
  2197. }
  2198. } catch (\Throwable $e) {
  2199. $tpl = '';
  2200. }
  2201. if ($tpl === '') {
  2202. $tpl = '【可集达】您的短信验证码是{code}';
  2203. }
  2204. return str_replace('{code}', $code, $tpl);
  2205. }
  2206. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2207. {
  2208. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2209. }
  2210. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2211. {
  2212. $code = trim($code);
  2213. if (!preg_match('/^\d{6}$/', $code)) {
  2214. return false;
  2215. }
  2216. $mock = Config::get('mproc.mock_sms_code');
  2217. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2218. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2219. return true;
  2220. }
  2221. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2222. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2223. return false;
  2224. }
  2225. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2226. return true;
  2227. }
  2228. /**
  2229. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2230. */
  2231. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2232. {
  2233. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2234. if ($ccydh === '') {
  2235. throw new \InvalidArgumentException('订单号无效');
  2236. }
  2237. $this->ensurePurchaseOrderBidOpenTable();
  2238. list($operatorId, $operatorName) = $this->GetUseName();
  2239. $now = date('Y-m-d H:i:s');
  2240. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2241. $payload = [
  2242. 'ccydh' => $ccydh,
  2243. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2244. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2245. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2246. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2247. 'operator_id' => (int)$operatorId,
  2248. 'operator_name' => trim((string)$operatorName),
  2249. 'createtime' => $now,
  2250. ];
  2251. if (is_array($exists)) {
  2252. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2253. } else {
  2254. Db::table('purchase_order_bid_open')->insert($payload);
  2255. }
  2256. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2257. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2258. $orderPart = '(订单' . $ccydh . ')';
  2259. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2260. $seenSid = [];
  2261. foreach ($bundle['pos'] ?? [] as $poRow) {
  2262. if (!is_array($poRow)) {
  2263. continue;
  2264. }
  2265. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2266. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2267. continue;
  2268. }
  2269. $seenSid[$sid] = true;
  2270. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2271. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2272. }
  2273. if ($seenSid === []) {
  2274. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2275. if ($this->isValidScydgyRowId($anchor)) {
  2276. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2277. }
  2278. }
  2279. }
  2280. /**
  2281. * 报价行展示字段默认值(模板安全访问)
  2282. *
  2283. * @param array<string, mixed> $line
  2284. * @return array<string, mixed>
  2285. */
  2286. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2287. {
  2288. if (!array_key_exists('amount_quote_pending', $line)) {
  2289. $line['amount_quote_pending'] = 0;
  2290. }
  2291. if (!array_key_exists('delivery_quote_pending', $line)) {
  2292. $line['delivery_quote_pending'] = 0;
  2293. }
  2294. if (!array_key_exists('quote_before_deadline', $line)) {
  2295. $line['quote_before_deadline'] = 0;
  2296. }
  2297. if (!array_key_exists('amount_filled', $line)) {
  2298. $line['amount_filled'] = 0;
  2299. }
  2300. if (!array_key_exists('delivery_filled', $line)) {
  2301. $line['delivery_filled'] = 0;
  2302. }
  2303. if (!array_key_exists('lead_days_filled', $line)) {
  2304. $line['lead_days_filled'] = 0;
  2305. }
  2306. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2307. $line['lead_days_quote_pending'] = 0;
  2308. }
  2309. if (!array_key_exists('lead_days_show', $line)) {
  2310. $line['lead_days_show'] = '未填写';
  2311. }
  2312. if (!array_key_exists('lead_days_text', $line)) {
  2313. $line['lead_days_text'] = $line['lead_days_show'];
  2314. }
  2315. return $line;
  2316. }
  2317. /**
  2318. * 审核弹窗:按供应商汇总报价明细
  2319. *
  2320. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2321. * @return array<int, array<string, mixed>>
  2322. */
  2323. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2324. {
  2325. $sids = [];
  2326. foreach ($bundle['pos'] ?? [] as $po) {
  2327. if (!is_array($po)) {
  2328. continue;
  2329. }
  2330. $sid = (int)($po['scydgy_id'] ?? 0);
  2331. if ($this->isValidScydgyRowId($sid)) {
  2332. $sids[$sid] = true;
  2333. }
  2334. }
  2335. if ($sids === []) {
  2336. return [];
  2337. }
  2338. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2339. $gymcMap = [];
  2340. $qtyBySid = [];
  2341. $orderedSids = [];
  2342. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2343. if (!is_array($mr)) {
  2344. continue;
  2345. }
  2346. $gid = $this->extractScydgyRowId($mr);
  2347. if ($this->isValidScydgyRowId($gid)) {
  2348. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2349. $orderedSids[] = $gid;
  2350. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2351. if ($qty === '') {
  2352. $qty = trim((string)($mr['NGZL'] ?? ''));
  2353. }
  2354. $qtyBySid[$gid] = $qty;
  2355. }
  2356. }
  2357. foreach ($bundle['pos'] ?? [] as $po) {
  2358. if (!is_array($po)) {
  2359. continue;
  2360. }
  2361. $gid = (int)($po['scydgy_id'] ?? 0);
  2362. if ($this->isValidScydgyRowId($gid)) {
  2363. $nm = trim((string)($po['CGYMC'] ?? ''));
  2364. if ($nm !== '') {
  2365. $gymcMap[$gid] = $nm;
  2366. }
  2367. if (!in_array($gid, $orderedSids, true)) {
  2368. $orderedSids[] = $gid;
  2369. }
  2370. }
  2371. }
  2372. try {
  2373. $detailsQuery = Db::table('purchase_order_detail')
  2374. ->where('scydgy_id', 'in', array_keys($sids));
  2375. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2376. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2377. } catch (\Throwable $e) {
  2378. try {
  2379. $detailsQuery = Db::table('purchase_order_detail')
  2380. ->where('scydgy_id', 'in', array_keys($sids));
  2381. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2382. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2383. } catch (\Throwable $e2) {
  2384. $details = [];
  2385. }
  2386. }
  2387. if (!is_array($details)) {
  2388. $details = [];
  2389. }
  2390. $byCompany = [];
  2391. foreach ($details as $d) {
  2392. if (!is_array($d)) {
  2393. continue;
  2394. }
  2395. $cn = trim((string)($d['company_name'] ?? ''));
  2396. if ($cn === '') {
  2397. continue;
  2398. }
  2399. if (!isset($byCompany[$cn])) {
  2400. $ph = trim((string)($d['phone'] ?? ''));
  2401. $username = trim((string)($d['username'] ?? ''));
  2402. if ($username === '') {
  2403. $username = $this->resolveCustomerContactName($ph, $cn);
  2404. }
  2405. $byCompany[$cn] = [
  2406. 'name' => $cn,
  2407. 'email' => trim((string)($d['email'] ?? '')),
  2408. 'phone' => $ph,
  2409. 'username' => $username,
  2410. 'remark' => '',
  2411. 'has_quote' => false,
  2412. 'lines_map' => [],
  2413. ];
  2414. }
  2415. if ($byCompany[$cn]['remark'] === '') {
  2416. $rm = '';
  2417. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2418. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2419. $rm = trim((string)$d[$rk]);
  2420. break;
  2421. }
  2422. }
  2423. if ($rm !== '') {
  2424. $byCompany[$cn]['remark'] = $rm;
  2425. }
  2426. }
  2427. $sid = (int)($d['scydgy_id'] ?? 0);
  2428. $am = trim((string)($d['amount'] ?? ''));
  2429. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2430. if ($gymc === '') {
  2431. $gymc = '工序';
  2432. }
  2433. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2434. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2435. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2436. $deliveryShow = $deliveryRaw;
  2437. }
  2438. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2439. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2440. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2441. $subtotal = null;
  2442. if ($amountNum !== null) {
  2443. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2444. }
  2445. $unitPriceText = $amountFilled
  2446. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2447. : '未填写';
  2448. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2449. $leadFilled = ($leadDays !== null);
  2450. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2451. $lineRow = [
  2452. 'cgymc' => $gymc,
  2453. 'amount' => $am,
  2454. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2455. 'amount_filled' => $amountFilled,
  2456. 'unit_price_text' => $unitPriceText,
  2457. 'delivery' => $deliveryRaw,
  2458. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2459. 'delivery_filled' => $deliveryFilled,
  2460. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2461. 'lead_days' => $leadFilled ? $leadDays : '',
  2462. 'lead_days_filled'=> $leadFilled,
  2463. 'lead_days_show' => $leadText,
  2464. 'lead_days_text' => $leadText,
  2465. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2466. 'subtotal_num' => $subtotal,
  2467. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2468. 'is_quoted' => $amountFilled,
  2469. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2470. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2471. ];
  2472. if (!$quoteVisible) {
  2473. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2474. }
  2475. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2476. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2477. }
  2478. foreach ($byCompany as $cn => $g) {
  2479. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2480. $lines = [];
  2481. $usedSids = [];
  2482. foreach ($orderedSids as $sid) {
  2483. if (!isset($linesMap[$sid])) {
  2484. continue;
  2485. }
  2486. $lines[] = $linesMap[$sid];
  2487. $usedSids[$sid] = true;
  2488. }
  2489. foreach ($linesMap as $sid => $ln) {
  2490. if (isset($usedSids[$sid])) {
  2491. continue;
  2492. }
  2493. $lines[] = $ln;
  2494. }
  2495. $total = count($lines);
  2496. $quoted = 0;
  2497. $groupTotal = 0.0;
  2498. $groupHasTotal = false;
  2499. if ($quoteVisible) {
  2500. foreach ($lines as $ln) {
  2501. $am = trim((string)($ln['amount'] ?? ''));
  2502. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2503. $quoted++;
  2504. }
  2505. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2506. $groupTotal += (float)$ln['subtotal_num'];
  2507. $groupHasTotal = true;
  2508. }
  2509. }
  2510. }
  2511. unset($byCompany[$cn]['lines_map']);
  2512. $byCompany[$cn]['lines'] = $lines;
  2513. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2514. $byCompany[$cn]['line_count'] = $total;
  2515. $byCompany[$cn]['has_total'] = $total > 0;
  2516. $byCompany[$cn]['has_remark'] = $total > 0;
  2517. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2518. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2519. // 工序行 + 备注行 + 总计行
  2520. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2521. }
  2522. return array_values($byCompany);
  2523. }
  2524. /**
  2525. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2526. *
  2527. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2528. * @return array<int, array<string, mixed>>
  2529. */
  2530. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2531. {
  2532. $sids = [];
  2533. $poIdMap = [];
  2534. foreach ($bundle['pos'] ?? [] as $po) {
  2535. if (!is_array($po)) {
  2536. continue;
  2537. }
  2538. $sid = (int)($po['scydgy_id'] ?? 0);
  2539. if ($this->isValidScydgyRowId($sid)) {
  2540. $sids[$sid] = true;
  2541. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2542. }
  2543. }
  2544. if ($sids === []) {
  2545. return [];
  2546. }
  2547. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2548. $gymcMap = [];
  2549. $qtyBySid = [];
  2550. $orderedSids = [];
  2551. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2552. if (!is_array($mr)) {
  2553. continue;
  2554. }
  2555. $gid = $this->extractScydgyRowId($mr);
  2556. if ($this->isValidScydgyRowId($gid)) {
  2557. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2558. $orderedSids[] = $gid;
  2559. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2560. if ($qty === '') {
  2561. $qty = trim((string)($mr['NGZL'] ?? ''));
  2562. }
  2563. $qtyBySid[$gid] = $qty;
  2564. }
  2565. }
  2566. foreach ($bundle['pos'] ?? [] as $po) {
  2567. if (!is_array($po)) {
  2568. continue;
  2569. }
  2570. $gid = (int)($po['scydgy_id'] ?? 0);
  2571. if ($this->isValidScydgyRowId($gid)) {
  2572. $nm = trim((string)($po['CGYMC'] ?? ''));
  2573. if ($nm !== '') {
  2574. $gymcMap[$gid] = $nm;
  2575. }
  2576. }
  2577. }
  2578. try {
  2579. $details = Db::table('purchase_order_detail')
  2580. ->where('scydgy_id', 'in', array_keys($sids))
  2581. ->order('company_name', 'asc')
  2582. ->order('id', 'asc')
  2583. ->select();
  2584. } catch (\Throwable $e) {
  2585. try {
  2586. $details = Db::table('purchase_order_detail')
  2587. ->where('scydgy_id', 'in', array_keys($sids))
  2588. ->order('company_name', 'asc')
  2589. ->order('ID', 'asc')
  2590. ->select();
  2591. } catch (\Throwable $e2) {
  2592. $details = [];
  2593. }
  2594. }
  2595. if (!is_array($details)) {
  2596. $details = [];
  2597. }
  2598. $byCompany = [];
  2599. foreach ($details as $d) {
  2600. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2601. continue;
  2602. }
  2603. $cn = trim((string)($d['company_name'] ?? ''));
  2604. if ($cn === '') {
  2605. continue;
  2606. }
  2607. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2608. $sid = (int)($d['scydgy_id'] ?? 0);
  2609. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2610. continue;
  2611. }
  2612. if (!isset($byCompany[$cn])) {
  2613. $ph = trim((string)($d['phone'] ?? ''));
  2614. $username = trim((string)($d['username'] ?? ''));
  2615. if ($username === '') {
  2616. $username = $this->resolveCustomerContactName($ph, $cn);
  2617. }
  2618. $byCompany[$cn] = [
  2619. 'name' => $cn,
  2620. 'email' => trim((string)($d['email'] ?? '')),
  2621. 'phone' => $ph,
  2622. 'username' => $username,
  2623. 'remark' => '',
  2624. 'pick_lines' => [],
  2625. 'detail_picks' => [],
  2626. ];
  2627. }
  2628. if ($byCompany[$cn]['remark'] === '') {
  2629. $rm = '';
  2630. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2631. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2632. $rm = trim((string)$d[$rk]);
  2633. break;
  2634. }
  2635. }
  2636. if ($rm !== '') {
  2637. $byCompany[$cn]['remark'] = $rm;
  2638. }
  2639. }
  2640. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2641. if ($gymc === '') {
  2642. $gymc = '工序';
  2643. }
  2644. $am = trim((string)($d['amount'] ?? ''));
  2645. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2646. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2647. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2648. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2649. $deliveryShow = $deliveryRaw;
  2650. }
  2651. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2652. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2653. $subtotal = null;
  2654. if ($amountNum !== null) {
  2655. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2656. }
  2657. $unitPriceText = $amountFilled
  2658. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2659. : '未填写';
  2660. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2661. $leadFilled = ($leadDays !== null);
  2662. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2663. $pickLine = [
  2664. 'cgymc' => $gymc,
  2665. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2666. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2667. 'amount_filled' => $amountFilled,
  2668. 'delivery_filled' => $deliveryFilled,
  2669. 'unit_price_text' => $unitPriceText,
  2670. 'lead_days' => $leadFilled ? $leadDays : '',
  2671. 'lead_days_filled'=> $leadFilled,
  2672. 'lead_days_show' => $leadText,
  2673. 'lead_days_text' => $leadText,
  2674. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2675. 'subtotal_num' => $subtotal,
  2676. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2677. 'is_quoted' => $amountFilled,
  2678. ];
  2679. if (!$quoteVisible) {
  2680. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2681. }
  2682. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2683. $byCompany[$cn]['detail_picks'][$sid] = [
  2684. 'scydgy_id' => $sid,
  2685. 'detail_id' => $detailId,
  2686. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2687. 'cgymc' => $gymc,
  2688. ];
  2689. }
  2690. $out = [];
  2691. foreach ($byCompany as $g) {
  2692. $pickLinesMap = $g['pick_lines'] ?? [];
  2693. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2694. continue;
  2695. }
  2696. $pickLines = [];
  2697. $usedLineSids = [];
  2698. foreach ($orderedSids as $sid) {
  2699. if (!isset($pickLinesMap[$sid])) {
  2700. continue;
  2701. }
  2702. $pickLines[] = $pickLinesMap[$sid];
  2703. $usedLineSids[$sid] = true;
  2704. }
  2705. foreach ($pickLinesMap as $sid => $ln) {
  2706. if (isset($usedLineSids[$sid])) {
  2707. continue;
  2708. }
  2709. $pickLines[] = $ln;
  2710. }
  2711. $groupTotal = 0.0;
  2712. $groupHasTotal = false;
  2713. if ($quoteVisible) {
  2714. foreach ($pickLines as $ln) {
  2715. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2716. $groupTotal += (float)$ln['subtotal_num'];
  2717. $groupHasTotal = true;
  2718. }
  2719. }
  2720. }
  2721. $lineCount = count($pickLines);
  2722. $g['pick_lines'] = $pickLines;
  2723. $g['line_count'] = $lineCount;
  2724. $g['has_total'] = $lineCount > 0;
  2725. $g['has_remark'] = $lineCount > 0;
  2726. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2727. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2728. // 工序行 + 备注行 + 总计行
  2729. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2730. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2731. $detailPicks = [];
  2732. $usedPickSids = [];
  2733. foreach ($orderedSids as $sid) {
  2734. if (!isset($detailPicksMap[$sid])) {
  2735. continue;
  2736. }
  2737. $detailPicks[] = $detailPicksMap[$sid];
  2738. $usedPickSids[$sid] = true;
  2739. }
  2740. foreach ($detailPicksMap as $sid => $dp) {
  2741. if (isset($usedPickSids[$sid])) {
  2742. continue;
  2743. }
  2744. $detailPicks[] = $dp;
  2745. }
  2746. $g['detail_picks'] = $detailPicks;
  2747. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2748. unset($g['detail_picks']);
  2749. $out[] = $g;
  2750. }
  2751. return $out;
  2752. }
  2753. /**
  2754. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2755. * @return array<int, int[]> scydgy_id => detail_id[]
  2756. */
  2757. protected function mapDetailIdsByScydgyId(array $details): array
  2758. {
  2759. $out = [];
  2760. foreach ($details as $d) {
  2761. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2762. continue;
  2763. }
  2764. $sid = (int)($d['scydgy_id'] ?? 0);
  2765. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2766. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2767. continue;
  2768. }
  2769. if (!isset($out[$sid])) {
  2770. $out[$sid] = [];
  2771. }
  2772. $out[$sid][] = $pk;
  2773. }
  2774. foreach ($out as $sid => $ids) {
  2775. $out[$sid] = array_values(array_unique($ids));
  2776. }
  2777. return $out;
  2778. }
  2779. /**
  2780. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2781. *
  2782. * @param array<string, mixed> $dbRow
  2783. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2784. */
  2785. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2786. {
  2787. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2788. $r = [
  2789. 'ID' => $sid,
  2790. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2791. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2792. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2793. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2794. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2795. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2796. 'CDW' => $dbRow['CDW'] ?? '',
  2797. 'NGZL' => $dbRow['NGZL'] ?? '',
  2798. 'CDF' => $dbRow['CDF'] ?? '',
  2799. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2800. 'MBZ' => $dbRow['MBZ'] ?? '',
  2801. 'bwjg' => $dbRow['bwjg'] ?? '',
  2802. 'iStatus' => $dbRow['iStatus'] ?? '',
  2803. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2804. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2805. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2806. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2807. 'dStamp' => $dbRow['dStamp'] ?? '',
  2808. 'pick_time' => $dbRow['pick_time'] ?? '',
  2809. ];
  2810. if ($sid > 0 && isset($dStampMap[$sid])) {
  2811. $t = trim((string)$dStampMap[$sid]);
  2812. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2813. $r['dStamp'] = $dStampMap[$sid];
  2814. }
  2815. }
  2816. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2817. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2818. $ct = $dbRow['createtime'];
  2819. if (is_numeric($ct) && (int)$ct > 946684800) {
  2820. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2821. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2822. $r['dStamp'] = trim($ct);
  2823. }
  2824. }
  2825. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2826. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2827. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2828. $fallback = trim((string)($r['dStamp'] ?? ''));
  2829. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2830. $r['dputrecord'] = $fallback;
  2831. }
  2832. }
  2833. if (array_key_exists('id', $dbRow)) {
  2834. $r['purchase_order_id'] = (int)$dbRow['id'];
  2835. }
  2836. if ($sid < 0) {
  2837. $r['_is_manual'] = 1;
  2838. }
  2839. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2840. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2841. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2842. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2843. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2844. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2845. $r['pick_time'] = $pickFallback;
  2846. break;
  2847. }
  2848. }
  2849. }
  2850. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2851. if ($pickNm !== '') {
  2852. $r['pick_company_name'] = $pickNm;
  2853. $r['picked_supplier_name'] = $pickNm;
  2854. }
  2855. return $r;
  2856. }
  2857. /**
  2858. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2859. *
  2860. * @return array<int, array<string, mixed>>
  2861. */
  2862. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2863. {
  2864. $pool = [];
  2865. if (!is_array($dbRows) || $dbRows === []) {
  2866. return $pool;
  2867. }
  2868. $dStampMap = [];
  2869. $sidList = [];
  2870. foreach ($dbRows as $tmpRow) {
  2871. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2872. $sid = (int)$tmpRow['scydgy_id'];
  2873. if ($sid > 0) {
  2874. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2875. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2876. $sidList[$sid] = true;
  2877. }
  2878. }
  2879. }
  2880. }
  2881. if ($sidList !== []) {
  2882. try {
  2883. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2884. } catch (\Throwable $e) {
  2885. $dStampMap = [];
  2886. }
  2887. }
  2888. foreach ($dbRows as $dbRow) {
  2889. if (!is_array($dbRow)) {
  2890. continue;
  2891. }
  2892. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2893. }
  2894. return $pool;
  2895. }
  2896. /**
  2897. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2898. *
  2899. * @param int[] $scydgyIds
  2900. * @return array<int, array<string, mixed>>
  2901. */
  2902. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2903. {
  2904. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2905. if ($scydgyIds === []) {
  2906. return [];
  2907. }
  2908. try {
  2909. $list = Db::table('purchase_order_detail')
  2910. ->where('scydgy_id', 'in', $scydgyIds)
  2911. ->field('scydgy_id,company_name,amount,delivery')
  2912. ->select();
  2913. } catch (\Throwable $e) {
  2914. $list = [];
  2915. }
  2916. return is_array($list) ? $list : [];
  2917. }
  2918. /**
  2919. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2920. *
  2921. * @param int[] $scydgyIds
  2922. * @param array<int, array<string, mixed>> $allRows
  2923. * @return array{cnt:int, amt:int, deliv:int}
  2924. */
  2925. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2926. {
  2927. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2928. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2929. if ($scydgyIds === [] || $allRows === []) {
  2930. return $out;
  2931. }
  2932. $idSet = array_flip($scydgyIds);
  2933. $all = [];
  2934. $withAmt = [];
  2935. $withDeliv = [];
  2936. foreach ($allRows as $r) {
  2937. if (!is_array($r)) {
  2938. continue;
  2939. }
  2940. $sid = (int)($r['scydgy_id'] ?? 0);
  2941. if (!isset($idSet[$sid])) {
  2942. continue;
  2943. }
  2944. $cn = trim((string)($r['company_name'] ?? ''));
  2945. if ($cn === '') {
  2946. continue;
  2947. }
  2948. $all[$cn] = true;
  2949. $am = $r['amount'] ?? null;
  2950. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2951. $withAmt[$cn] = true;
  2952. }
  2953. $dv = $r['delivery'] ?? null;
  2954. if ($dv !== null && trim((string)$dv) !== '') {
  2955. $withDeliv[$cn] = true;
  2956. }
  2957. }
  2958. return [
  2959. 'cnt' => count($all),
  2960. 'amt' => count($withAmt),
  2961. 'deliv' => count($withDeliv),
  2962. ];
  2963. }
  2964. /**
  2965. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2966. *
  2967. * @param int[] $scydgyIds
  2968. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2969. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2970. */
  2971. protected function OrderDetailSummary(array $scydgyIds)
  2972. {
  2973. $out = [];
  2974. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2975. if ($scydgyIds === []) {
  2976. return $out;
  2977. }
  2978. $list = [];
  2979. try {
  2980. $list = Db::table('purchase_order_detail')
  2981. ->where('scydgy_id', 'in', $scydgyIds)
  2982. ->field('id,scydgy_id,amount,delivery')
  2983. ->select();
  2984. } catch (\Throwable $e) {
  2985. $list = [];
  2986. }
  2987. if (!is_array($list)) {
  2988. return $out;
  2989. }
  2990. foreach ($list as $r) {
  2991. if (!is_array($r)) {
  2992. continue;
  2993. }
  2994. $ids = (int)($r['scydgy_id'] ?? 0);
  2995. if (!$this->isValidScydgyRowId($ids)) {
  2996. continue;
  2997. }
  2998. if (!isset($out[$ids])) {
  2999. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3000. }
  3001. $out[$ids]['cnt']++;
  3002. $am = $r['amount'] ?? null;
  3003. if ($am !== null && $am !== '') {
  3004. if (!(is_string($am) && trim($am) === '')) {
  3005. $out[$ids]['amt']++;
  3006. }
  3007. }
  3008. $dv = $r['delivery'] ?? null;
  3009. if ($dv !== null && trim((string)$dv) !== '') {
  3010. $out[$ids]['deliv']++;
  3011. }
  3012. }
  3013. return $out;
  3014. }
  3015. /**
  3016. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3017. *
  3018. * @return array
  3019. */
  3020. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3021. {
  3022. $strContains = function ($haystack, $needle) {
  3023. if ($needle === '') {
  3024. return false;
  3025. }
  3026. $haystack = (string)$haystack;
  3027. if (function_exists('mb_stripos')) {
  3028. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3029. }
  3030. return stripos($haystack, $needle) !== false;
  3031. };
  3032. $stripAlias = function ($f) {
  3033. return preg_replace('/^[ab]\./i', '', (string)$f);
  3034. };
  3035. $searchColNames = [];
  3036. foreach (explode(',', $this->searchFields) as $colRaw) {
  3037. $c = $stripAlias(trim($colRaw));
  3038. if ($c !== '') {
  3039. $searchColNames[] = $c;
  3040. }
  3041. }
  3042. $filtered = [];
  3043. foreach ($pool as $r) {
  3044. if (!is_array($r)) {
  3045. continue;
  3046. }
  3047. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3048. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3049. if (!$isManual) {
  3050. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3051. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3052. continue;
  3053. }
  3054. if ($applyMonthRange) {
  3055. $mo = (int)$m[2];
  3056. if ($mo < 1 || $mo > 12) {
  3057. continue;
  3058. }
  3059. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3060. $rowMonthStart = $ymRow . '-01 00:00:00';
  3061. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3062. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3063. continue;
  3064. }
  3065. }
  3066. } elseif ($applyMonthRange) {
  3067. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3068. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3069. $ds = $listTime;
  3070. }
  3071. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3072. continue;
  3073. }
  3074. $mo = (int)$m[2];
  3075. if ($mo < 1 || $mo > 12) {
  3076. continue;
  3077. }
  3078. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3079. $rowMonthStart = $ymRow . '-01 00:00:00';
  3080. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3081. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3082. continue;
  3083. }
  3084. }
  3085. if ($search !== '') {
  3086. $hitSearch = false;
  3087. foreach ($searchColNames as $c) {
  3088. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3089. if ($cell !== '' && $strContains($cell, $search)) {
  3090. $hitSearch = true;
  3091. break;
  3092. }
  3093. }
  3094. if (!$hitSearch) {
  3095. continue;
  3096. }
  3097. }
  3098. foreach ($filterArr as $fk => $fv) {
  3099. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3100. continue;
  3101. }
  3102. if (is_array($fv)) {
  3103. continue;
  3104. }
  3105. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3106. continue;
  3107. }
  3108. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3109. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3110. $field = $stripAlias($fk);
  3111. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3112. $cellStr = trim((string)$cell);
  3113. switch ($sym) {
  3114. case '=':
  3115. if ((string)$cell !== (string)$fv) {
  3116. continue 3;
  3117. }
  3118. break;
  3119. case '<>':
  3120. if ((string)$cell === (string)$fv) {
  3121. continue 3;
  3122. }
  3123. break;
  3124. case 'LIKE':
  3125. case 'NOT LIKE':
  3126. $needle = trim((string)$fv);
  3127. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3128. if ($sym === 'LIKE' && !$hit) {
  3129. continue 3;
  3130. }
  3131. if ($sym === 'NOT LIKE' && $hit) {
  3132. continue 3;
  3133. }
  3134. break;
  3135. case '>':
  3136. case '>=':
  3137. case '<':
  3138. case '<=':
  3139. if (!is_numeric($cell) && $cellStr === '') {
  3140. continue 3;
  3141. }
  3142. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  3143. $vv = (float)$fv;
  3144. if ($sym === '>' && !($cv > $vv)) {
  3145. continue 3;
  3146. }
  3147. if ($sym === '>=' && !($cv >= $vv)) {
  3148. continue 3;
  3149. }
  3150. if ($sym === '<' && !($cv < $vv)) {
  3151. continue 3;
  3152. }
  3153. if ($sym === '<=' && !($cv <= $vv)) {
  3154. continue 3;
  3155. }
  3156. break;
  3157. case 'RANGE':
  3158. case 'NOT RANGE':
  3159. case 'BETWEEN':
  3160. case 'NOT BETWEEN':
  3161. case 'BETWEEN TIME':
  3162. case 'NOT BETWEEN TIME':
  3163. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  3164. $rawR = str_replace(' - ', ',', $rawR);
  3165. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  3166. if (count($arr) < 2) {
  3167. break;
  3168. }
  3169. $lo = $arr[0];
  3170. $hi = $arr[1];
  3171. if ($lo === '' && $hi === '') {
  3172. break;
  3173. }
  3174. $isNot = (strpos($sym, 'NOT') !== false);
  3175. if ($lo === '') {
  3176. $in = ($cellStr !== '' && $cellStr <= $hi);
  3177. if ($isNot ? $in : !$in) {
  3178. continue 3;
  3179. }
  3180. break;
  3181. }
  3182. if ($hi === '') {
  3183. $in = ($cellStr !== '' && $cellStr >= $lo);
  3184. if ($isNot ? $in : !$in) {
  3185. continue 3;
  3186. }
  3187. break;
  3188. }
  3189. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3190. if ($isNot ? $in : !$in) {
  3191. continue 3;
  3192. }
  3193. break;
  3194. case 'NULL':
  3195. case 'IS NULL':
  3196. if ($cell !== null && $cell !== '') {
  3197. continue 3;
  3198. }
  3199. break;
  3200. case 'NOT NULL':
  3201. case 'IS NOT NULL':
  3202. if ($cell === null || $cell === '') {
  3203. continue 3;
  3204. }
  3205. break;
  3206. default:
  3207. break;
  3208. }
  3209. }
  3210. $filtered[] = $r;
  3211. }
  3212. return $filtered;
  3213. }
  3214. /**
  3215. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3216. */
  3217. public function snapshotToProcure()
  3218. {
  3219. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3220. $this->error(__('Invalid parameters'));
  3221. }
  3222. $row = json_decode($this->request->post('row_json', ''), true);
  3223. if (!is_array($row)) {
  3224. $this->error(__('Invalid parameters'));
  3225. }
  3226. try {
  3227. $ids = $this->extractScydgyRowId($row);
  3228. if (!$this->isValidScydgyRowId($ids)) {
  3229. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3230. }
  3231. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3232. $data = [
  3233. 'scydgy_id' => $ids,
  3234. 'CCYDH' => $row['CCYDH'] ?? null,
  3235. 'CYJMC' => $row['CYJMC'] ?? null,
  3236. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3237. 'CDXMC' => $row['CDXMC'] ?? null,
  3238. 'CGYBH' => $row['CGYBH'] ?? null,
  3239. 'CGYMC' => $row['CGYMC'] ?? null,
  3240. 'CDW' => $row['CDW'] ?? null,
  3241. 'NGZL' => $row['NGZL'] ?? null,
  3242. 'CDF' => $row['CDF'] ?? null,
  3243. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3244. 'MBZ' => $row['MBZ'] ?? null,
  3245. 'bwjg' => $row['bwjg'] ?? null,
  3246. 'iStatus' => $row['iStatus'] ?? null,
  3247. 'dStamp' => $row['dStamp'] ?? null,
  3248. 'dputrecord' => $row['dputrecord'] ?? null,
  3249. 'cywyxm' => $row['cywyxm'] ?? null,
  3250. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3251. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3252. ];
  3253. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3254. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3255. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3256. $this->success('操作成功');
  3257. return;
  3258. }
  3259. if ($exists) {
  3260. $upd = $data;
  3261. unset($upd['scydgy_id'], $upd['status']);
  3262. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3263. } else {
  3264. // 新增:不写 status(空/走库默认);仅写创建时间
  3265. $data['createtime'] = date('Y-m-d H:i:s');
  3266. Db::table('purchase_order')->insert($data);
  3267. }
  3268. } catch (\Throwable $e) {
  3269. $this->error($e->getMessage());
  3270. }
  3271. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3272. $this->success('操作成功');
  3273. }
  3274. /**
  3275. * 未发列表
  3276. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3277. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3278. */
  3279. public function completeDirectly()
  3280. {
  3281. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3282. $this->error(__('参数错误'));
  3283. }
  3284. if (!$this->procuremenCanComplete()) {
  3285. $this->error(__('You have no permission'));
  3286. }
  3287. $row = json_decode($this->request->post('row_json', ''), true);
  3288. if (!is_array($row)) {
  3289. $this->error(__('Invalid parameters'));
  3290. }
  3291. $finishRaw = $this->request->post('finish', '1');
  3292. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3293. $poIdLog = null;
  3294. try {
  3295. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3296. $ids = $this->extractScydgyRowId($row);
  3297. if (!$this->isValidScydgyRowId($ids)) {
  3298. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3299. }
  3300. if ($asComplete) {
  3301. $this->assertPickRowCanComplete($ids, $row);
  3302. }
  3303. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3304. $data = [
  3305. 'scydgy_id' => $ids,
  3306. 'CCYDH' => $row['CCYDH'] ?? null,
  3307. 'CYJMC' => $row['CYJMC'] ?? null,
  3308. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3309. 'CDXMC' => $row['CDXMC'] ?? null,
  3310. 'CGYBH' => $row['CGYBH'] ?? null,
  3311. 'CGYMC' => $row['CGYMC'] ?? null,
  3312. 'CDW' => $row['CDW'] ?? null,
  3313. 'NGZL' => $row['NGZL'] ?? null,
  3314. 'CDF' => $row['CDF'] ?? null,
  3315. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3316. 'MBZ' => $row['MBZ'] ?? null,
  3317. 'bwjg' => $row['bwjg'] ?? null,
  3318. 'iStatus' => $row['iStatus'] ?? null,
  3319. 'dStamp' => $row['dStamp'] ?? null,
  3320. 'dputrecord' => $row['dputrecord'] ?? null,
  3321. 'cywyxm' => $row['cywyxm'] ?? null,
  3322. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3323. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3324. ];
  3325. if ($asComplete) {
  3326. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3327. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3328. }
  3329. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3330. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3331. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3332. $this->success('操作成功');
  3333. return;
  3334. }
  3335. if ($exists) {
  3336. $upd = $data;
  3337. unset($upd['scydgy_id']);
  3338. if (!$asComplete) {
  3339. unset($upd['status']);
  3340. }
  3341. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3342. } else {
  3343. // 新增:不写 status;完结时 $data 已含 status=1
  3344. $data['createtime'] = date('Y-m-d H:i:s');
  3345. Db::table('purchase_order')->insert($data);
  3346. }
  3347. } catch (\Throwable $e) {
  3348. $this->error($e->getMessage());
  3349. }
  3350. try {
  3351. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3352. if (is_array($rpo)) {
  3353. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3354. $poIdLog = $tid > 0 ? $tid : null;
  3355. }
  3356. } catch (\Throwable $e) {
  3357. $poIdLog = null;
  3358. }
  3359. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3360. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3361. if ($asComplete) {
  3362. $this->addOrderLog(
  3363. $ids,
  3364. 'mark_complete',
  3365. '点击「完结」,已标记为已完结',
  3366. $poIdLog
  3367. );
  3368. try {
  3369. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3370. if ($pdfPublicPath === '') {
  3371. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3372. }
  3373. } catch (\Throwable $e) {
  3374. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3375. }
  3376. } else {
  3377. $this->addOrderLog(
  3378. $ids,
  3379. 'save_qty_price',
  3380. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3381. $poIdLog
  3382. );
  3383. }
  3384. $this->pickHiddenScydgySetCache = null;
  3385. $this->success("操作成功");
  3386. }
  3387. /**
  3388. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3389. *
  3390. * @param array<int, array> $rows 引用传递当前页行
  3391. */
  3392. protected function mergePurchaseOrder(array &$rows)
  3393. {
  3394. if ($rows === []) {
  3395. return;
  3396. }
  3397. $ids = [];
  3398. foreach ($rows as $rw) {
  3399. if (!is_array($rw)) {
  3400. continue;
  3401. }
  3402. $id = (int)($rw['ID'] ?? 0);
  3403. if ($id > 0) {
  3404. $ids[$id] = true;
  3405. }
  3406. }
  3407. $idList = array_keys($ids);
  3408. if ($idList === []) {
  3409. return;
  3410. }
  3411. try {
  3412. $list = Db::table('purchase_order')
  3413. ->where('scydgy_id', 'in', $idList)
  3414. ->field('scydgy_id,This_quantity,ceilingPrice')
  3415. ->select();
  3416. } catch (\Throwable $e) {
  3417. return;
  3418. }
  3419. if (!is_array($list)) {
  3420. return;
  3421. }
  3422. $byId = [];
  3423. foreach ($list as $dbRow) {
  3424. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3425. continue;
  3426. }
  3427. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3428. }
  3429. foreach ($rows as &$rw) {
  3430. if (!is_array($rw)) {
  3431. continue;
  3432. }
  3433. $sid = (int)($rw['ID'] ?? 0);
  3434. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3435. continue;
  3436. }
  3437. $db = $byId[$sid];
  3438. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3439. if (array_key_exists('This_quantity', $db)) {
  3440. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3441. }
  3442. if (array_key_exists('ceilingPrice', $db)) {
  3443. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3444. } elseif (array_key_exists('ceiling_price', $db)) {
  3445. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3446. }
  3447. }
  3448. unset($rw);
  3449. }
  3450. /**
  3451. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3452. */
  3453. public function purchaseConfirmPick()
  3454. {
  3455. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3456. $this->error(__('Invalid parameters'));
  3457. }
  3458. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3459. $this->error(__('You have no permission'));
  3460. }
  3461. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3462. if ($batchRaw !== '') {
  3463. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3464. return;
  3465. }
  3466. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3467. $sid = (int)$scydgyId;
  3468. if (!$this->isValidScydgyRowId($sid)) {
  3469. $this->error('参数无效');
  3470. }
  3471. $parseIdList = function ($raw) {
  3472. if (is_array($raw)) {
  3473. $arr = $raw;
  3474. } else {
  3475. $decoded = json_decode((string)$raw, true);
  3476. $arr = is_array($decoded) ? $decoded : [];
  3477. }
  3478. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3479. };
  3480. $selectedRaw = $this->request->post('selected_ids', null);
  3481. if ($selectedRaw === null || $selectedRaw === '') {
  3482. $legacy = (int)$this->request->post('selected_id', 0);
  3483. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3484. } else {
  3485. $selectedIds = $parseIdList($selectedRaw);
  3486. }
  3487. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3488. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3489. try {
  3490. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3491. } catch (\InvalidArgumentException $e) {
  3492. $this->error($e->getMessage());
  3493. } catch (\Throwable $e) {
  3494. $this->error($e->getMessage());
  3495. }
  3496. $this->pickHiddenScydgySetCache = null;
  3497. $this->success('操作成功', '', $result);
  3498. }
  3499. /**
  3500. * 整单采购确认(多道工序一次提交)
  3501. */
  3502. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3503. {
  3504. $decoded = json_decode($batchRaw, true);
  3505. if (!is_array($decoded) || $decoded === []) {
  3506. $this->error('提交数据无效');
  3507. }
  3508. $picks = [];
  3509. foreach ($decoded as $item) {
  3510. if (!is_array($item)) {
  3511. continue;
  3512. }
  3513. $sid = (int)($item['scydgy_id'] ?? 0);
  3514. if (!$this->isValidScydgyRowId($sid)) {
  3515. continue;
  3516. }
  3517. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3518. if (!is_array($sel)) {
  3519. $sel = [(int)$sel];
  3520. }
  3521. $unsel = $item['unselected_ids'] ?? [];
  3522. if (!is_array($unsel)) {
  3523. $unsel = json_decode((string)$unsel, true);
  3524. $unsel = is_array($unsel) ? $unsel : [];
  3525. }
  3526. $picks[] = [
  3527. 'scydgy_id' => $sid,
  3528. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3529. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3530. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3531. ];
  3532. }
  3533. if ($picks === []) {
  3534. $this->error('提交数据无效');
  3535. }
  3536. Db::startTrans();
  3537. $results = [];
  3538. try {
  3539. foreach ($picks as $pick) {
  3540. $results[] = $this->runPurchaseConfirmPick(
  3541. (int)$pick['scydgy_id'],
  3542. $pick['selected_ids'],
  3543. $pick['unselected_ids'],
  3544. (int)$pick['purchase_order_id'],
  3545. false,
  3546. false
  3547. );
  3548. }
  3549. Db::commit();
  3550. } catch (\Throwable $e) {
  3551. Db::rollback();
  3552. $msg = $e->getMessage();
  3553. $this->error($msg !== '' ? $msg : '提交失败');
  3554. }
  3555. try {
  3556. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3557. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3558. } catch (\Throwable $e) {
  3559. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3560. }
  3561. $this->pickHiddenScydgySetCache = null;
  3562. $this->success('操作成功', '', ['batch' => $results]);
  3563. }
  3564. /**
  3565. * @return array<string, mixed>
  3566. */
  3567. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3568. {
  3569. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3570. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3571. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3572. $scydgyId = (string)$sid;
  3573. if ($selectedIds === []) {
  3574. throw new \InvalidArgumentException('请至少勾选一条明细');
  3575. }
  3576. $inter = array_intersect($selectedIds, $unselectedIds);
  3577. if ($inter !== []) {
  3578. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3579. }
  3580. $allIds = $this->purchaseOrderDetail($sid);
  3581. if ($allIds === []) {
  3582. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3583. }
  3584. foreach ($selectedIds as $id) {
  3585. if (!in_array($id, $allIds, true)) {
  3586. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3587. }
  3588. }
  3589. foreach ($unselectedIds as $id) {
  3590. if (!in_array($id, $allIds, true)) {
  3591. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3592. }
  3593. }
  3594. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3595. sort($union, SORT_NUMERIC);
  3596. $expect = $allIds;
  3597. sort($expect, SORT_NUMERIC);
  3598. if ($union !== $expect) {
  3599. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3600. }
  3601. if ($manageTransaction) {
  3602. Db::startTrans();
  3603. }
  3604. try {
  3605. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3606. $aff = 0;
  3607. try {
  3608. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3609. } catch (\Throwable $e) {
  3610. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3611. }
  3612. if ($aff < 1) {
  3613. throw new \Exception('更新选中状态失败');
  3614. }
  3615. $poPayload = [
  3616. 'status' => ProcuremenStatus::PO_COMPLETED,
  3617. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3618. ];
  3619. if ($purchaseOrderId > 0) {
  3620. $poAff = (int)Db::table('purchase_order')
  3621. ->where('id', $purchaseOrderId)
  3622. ->where('scydgy_id', $sid)
  3623. ->update($poPayload);
  3624. if ($poAff < 1) {
  3625. throw new \Exception('主表订单不存在或与工序行不匹配');
  3626. }
  3627. } else {
  3628. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3629. if ($poAff < 1) {
  3630. throw new \Exception('未找到');
  3631. }
  3632. }
  3633. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3634. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3635. if ($manageTransaction) {
  3636. Db::commit();
  3637. }
  3638. } catch (\Throwable $e) {
  3639. if ($manageTransaction) {
  3640. Db::rollback();
  3641. }
  3642. throw $e;
  3643. }
  3644. $poIdFinal = $purchaseOrderId;
  3645. if ($poIdFinal <= 0) {
  3646. try {
  3647. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3648. if (is_array($rpo)) {
  3649. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3650. }
  3651. } catch (\Throwable $e) {
  3652. $poIdFinal = 0;
  3653. }
  3654. }
  3655. $pickNames = [];
  3656. foreach ($selectedIds as $pid) {
  3657. $dr = $this->purchaseOrderDetai($sid, $pid);
  3658. $nm = trim((string)($dr['company_name'] ?? ''));
  3659. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3660. }
  3661. $this->addOrderLog(
  3662. $sid,
  3663. 'purchase_confirm',
  3664. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3665. $poIdFinal > 0 ? $poIdFinal : null
  3666. );
  3667. if ($sendNotifications) {
  3668. try {
  3669. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3670. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3671. 'scydgy_id' => $sid,
  3672. 'selected_ids' => $selectedIds,
  3673. 'unselected_ids' => $unselectedIds,
  3674. 'purchase_order_id' => $purchaseOrderId,
  3675. ]]);
  3676. } catch (\Throwable $e) {
  3677. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3678. }
  3679. }
  3680. Log::write(sprintf(
  3681. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3682. $scydgyId,
  3683. $purchaseOrderId,
  3684. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3685. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3686. ), 'notice');
  3687. $pdfPublicPath = '';
  3688. try {
  3689. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3690. } catch (\Throwable $e) {
  3691. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3692. }
  3693. return [
  3694. 'scydgy_id' => $scydgyId,
  3695. 'purchase_order_id' => $purchaseOrderId,
  3696. 'selected_ids' => $selectedIds,
  3697. 'unselected_ids' => $unselectedIds,
  3698. 'purchase_confirm_pdf' => $pdfPublicPath,
  3699. ];
  3700. }
  3701. /**
  3702. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3703. *
  3704. * @param int[]|string[] $scydgyIds
  3705. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3706. */
  3707. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3708. {
  3709. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3710. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3711. if ($scydgyIds === []) {
  3712. return $empty;
  3713. }
  3714. $pos = [];
  3715. try {
  3716. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3717. } catch (\Throwable $e) {
  3718. $rows = [];
  3719. }
  3720. if (is_array($rows)) {
  3721. foreach ($rows as $po) {
  3722. if (is_array($po)) {
  3723. $pos[] = $po;
  3724. }
  3725. }
  3726. }
  3727. if ($pos === []) {
  3728. return $empty;
  3729. }
  3730. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3731. return [
  3732. 'ccydh' => $ccydh,
  3733. 'pos' => $pos,
  3734. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3735. ];
  3736. }
  3737. /**
  3738. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3739. *
  3740. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3741. * @param array<int, array<string, mixed>> $picks
  3742. */
  3743. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3744. {
  3745. if ($picks === []) {
  3746. return;
  3747. }
  3748. $fallbackDetailId = 0;
  3749. $winners = [];
  3750. $losers = [];
  3751. foreach ($picks as $pick) {
  3752. if (!is_array($pick)) {
  3753. continue;
  3754. }
  3755. $sid = (int)($pick['scydgy_id'] ?? 0);
  3756. if (!$this->isValidScydgyRowId($sid)) {
  3757. continue;
  3758. }
  3759. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3760. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3761. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3762. $fallbackDetailId = (int)$selectedIds[0];
  3763. }
  3764. foreach ($selectedIds as $pid) {
  3765. $dr = $this->purchaseOrderDetai($sid, $pid);
  3766. if (!is_array($dr)) {
  3767. continue;
  3768. }
  3769. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3770. }
  3771. foreach ($unselectedIds as $pid) {
  3772. $dr = $this->purchaseOrderDetai($sid, $pid);
  3773. if (!is_array($dr)) {
  3774. continue;
  3775. }
  3776. $key = $this->notifySupplierDedupeKey($dr);
  3777. if (!isset($winners[$key])) {
  3778. $losers[$key] = $dr;
  3779. }
  3780. }
  3781. }
  3782. if ($winners === [] && $losers === []) {
  3783. return;
  3784. }
  3785. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3786. $sendSmsSafe = function ($phone, $content) {
  3787. $phone = trim((string)$phone);
  3788. if ($phone === '') {
  3789. return;
  3790. }
  3791. try {
  3792. $this->smsbao($phone, $content);
  3793. } catch (\Throwable $e) {
  3794. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3795. }
  3796. };
  3797. foreach ($winners as $dr) {
  3798. $cname = trim((string)($dr['company_name'] ?? ''));
  3799. $ph = trim((string)($dr['phone'] ?? ''));
  3800. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3801. 'company_name' => $cname,
  3802. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3803. 'phone' => $ph,
  3804. ]));
  3805. $sendSmsSafe($ph, $sms);
  3806. }
  3807. foreach ($losers as $dr) {
  3808. $cname = trim((string)($dr['company_name'] ?? ''));
  3809. $ph = trim((string)($dr['phone'] ?? ''));
  3810. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3811. 'company_name' => $cname,
  3812. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3813. 'phone' => $ph,
  3814. ]));
  3815. $sendSmsSafe($ph, $sms);
  3816. }
  3817. }
  3818. /**
  3819. * 短信去重键:优先手机号,否则公司名
  3820. */
  3821. protected function notifySupplierDedupeKey(array $detailRow): string
  3822. {
  3823. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3824. if ($ph !== '') {
  3825. return 'p:' . $ph;
  3826. }
  3827. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3828. return 'c:' . $cn;
  3829. }
  3830. /**
  3831. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3832. *
  3833. * @param int[] $detailIds
  3834. */
  3835. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3836. {
  3837. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3838. if ($detailIds === []) {
  3839. return;
  3840. }
  3841. $payload = ['status_name' => $statusName];
  3842. try {
  3843. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3844. } catch (\Throwable $e) {
  3845. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3846. }
  3847. }
  3848. /**
  3849. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3850. */
  3851. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3852. {
  3853. try {
  3854. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3855. } catch (\Throwable $e) {
  3856. return;
  3857. }
  3858. if (!is_array($rows)) {
  3859. return;
  3860. }
  3861. foreach ($rows as $dr) {
  3862. if (!is_array($dr)) {
  3863. continue;
  3864. }
  3865. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3866. if ($id <= 0) {
  3867. continue;
  3868. }
  3869. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3870. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3871. try {
  3872. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3873. } catch (\Throwable $e) {
  3874. }
  3875. }
  3876. }
  3877. /**
  3878. * @param array<string, mixed> $detailRow
  3879. */
  3880. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3881. {
  3882. $am = $detailRow['amount'] ?? null;
  3883. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3884. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3885. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3886. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3887. }
  3888. /**
  3889. * @return int[]
  3890. */
  3891. protected function purchaseOrderDetail(int $scydgyId): array
  3892. {
  3893. if (!$this->isValidScydgyRowId($scydgyId)) {
  3894. return [];
  3895. }
  3896. try {
  3897. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3898. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3899. $list = $listQuery->select();
  3900. } catch (\Throwable $e) {
  3901. return [];
  3902. }
  3903. if (!is_array($list)) {
  3904. return [];
  3905. }
  3906. $ids = [];
  3907. foreach ($list as $r) {
  3908. if (!is_array($r)) {
  3909. continue;
  3910. }
  3911. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3912. if ($pk > 0) {
  3913. $ids[] = $pk;
  3914. }
  3915. }
  3916. return array_values(array_unique($ids));
  3917. }
  3918. /**
  3919. * 获取当前登录用户信息 [id, 展示名]
  3920. */
  3921. protected function GetUseName(): array
  3922. {
  3923. $id = 0;
  3924. $name = '';
  3925. try {
  3926. if ($this->auth && $this->auth->isLogin()) {
  3927. $u = $this->auth->getUserInfo();
  3928. if (is_array($u)) {
  3929. $id = (int)($u['id'] ?? 0);
  3930. $name = trim((string)($u['nickname'] ?? ''));
  3931. if ($name === '') {
  3932. $name = trim((string)($u['username'] ?? ''));
  3933. }
  3934. }
  3935. }
  3936. } catch (\Throwable $e) {
  3937. }
  3938. if ($name === '') {
  3939. $name = '未知用户';
  3940. }
  3941. return [$id, $name];
  3942. }
  3943. /**
  3944. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3945. */
  3946. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3947. {
  3948. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3949. }
  3950. /**
  3951. * 按主键取一条
  3952. */
  3953. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3954. {
  3955. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3956. return [];
  3957. }
  3958. try {
  3959. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3960. if (is_array($one)) {
  3961. return $one;
  3962. }
  3963. } catch (\Throwable $e) {
  3964. }
  3965. try {
  3966. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3967. if (is_array($one)) {
  3968. return $one;
  3969. }
  3970. } catch (\Throwable $e) {
  3971. }
  3972. return [];
  3973. }
  3974. /**
  3975. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3976. */
  3977. protected function formatProcuremenDetailTime($v): string
  3978. {
  3979. if ($v === null || $v === '') {
  3980. return '';
  3981. }
  3982. if (is_numeric($v) && (int)$v > 946684800) {
  3983. return date('Y-m-d H:i:s', (int)$v);
  3984. }
  3985. return ProcuremenTime::formatDisplayDateTime($v);
  3986. }
  3987. /**
  3988. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3989. */
  3990. protected function formatDeliveryYmd($v): string
  3991. {
  3992. if ($v === null || $v === '') {
  3993. return '';
  3994. }
  3995. $s = trim((string)$v);
  3996. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3997. return '';
  3998. }
  3999. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4000. return $m[1];
  4001. }
  4002. $ts = strtotime($s);
  4003. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4004. }
  4005. /**
  4006. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4007. */
  4008. protected function detailRowSupplierOperated(array $r): bool
  4009. {
  4010. $am = $r['amount'] ?? null;
  4011. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4012. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4013. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4014. return $okAmt || $okDel;
  4015. }
  4016. /**
  4017. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4018. */
  4019. protected function resolveDetailSupplierOperTime(array $r): string
  4020. {
  4021. if (!$this->detailRowSupplierOperated($r)) {
  4022. return '';
  4023. }
  4024. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4025. if ($t !== '') {
  4026. return $t;
  4027. }
  4028. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4029. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4030. continue;
  4031. }
  4032. $t = $this->formatProcuremenDetailTime($r[$col]);
  4033. if ($t !== '') {
  4034. return $t;
  4035. }
  4036. }
  4037. return '';
  4038. }
  4039. /**
  4040. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4041. */
  4042. protected function detailRowSupplierAccepted(array $r): bool
  4043. {
  4044. $am = $r['amount'] ?? null;
  4045. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4046. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4047. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4048. return $okAmt && $okDel;
  4049. }
  4050. /**
  4051. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4052. */
  4053. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4054. {
  4055. if ($detailCount > 0) {
  4056. return true;
  4057. }
  4058. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4059. return true;
  4060. }
  4061. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4062. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4063. return true;
  4064. }
  4065. return false;
  4066. }
  4067. /**
  4068. * 下发时间:优先 pick_time,其次首条下发明细时间
  4069. */
  4070. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4071. {
  4072. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4073. if ($issueTime !== '') {
  4074. return $issueTime;
  4075. }
  4076. foreach ($details as $dr) {
  4077. if (!is_array($dr)) {
  4078. continue;
  4079. }
  4080. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4081. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4082. $issueTime = $t;
  4083. }
  4084. }
  4085. if ($issueTime !== '') {
  4086. return $issueTime;
  4087. }
  4088. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4089. }
  4090. /**
  4091. * 直接点「完结」时间:优先操作记录 mark_complete
  4092. */
  4093. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4094. {
  4095. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4096. }
  4097. /**
  4098. * 操作记录时间(取指定 action 最近一条)
  4099. *
  4100. * @param string|array<int, string> $actions
  4101. */
  4102. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4103. {
  4104. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4105. }
  4106. /**
  4107. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4108. *
  4109. * @param array $main purchase_order 一行
  4110. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4111. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4112. */
  4113. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4114. {
  4115. $issueCnt = count($details);
  4116. $acceptCnt = 0;
  4117. $pickedName = '';
  4118. $pickedTime = '';
  4119. foreach ($details as $dr) {
  4120. if (!is_array($dr)) {
  4121. continue;
  4122. }
  4123. if ($this->detailRowSupplierAccepted($dr)) {
  4124. $acceptCnt++;
  4125. }
  4126. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4127. if ($pickedName === '') {
  4128. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4129. }
  4130. if ($pickedTime === '') {
  4131. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4132. if ($pickedTime === '') {
  4133. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4134. }
  4135. }
  4136. }
  4137. }
  4138. $hasMain = $main !== [];
  4139. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4140. if ($poTime === '') {
  4141. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4142. }
  4143. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4144. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4145. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4146. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4147. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4148. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4149. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4150. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4151. $supplierTime = '';
  4152. if ($acceptCnt > 0) {
  4153. foreach ($details as $dr) {
  4154. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4155. continue;
  4156. }
  4157. $t = $this->resolveDetailSupplierOperTime($dr);
  4158. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4159. $supplierTime = $t;
  4160. }
  4161. }
  4162. }
  4163. $directComplete = ($mainCompleted && !$issued);
  4164. $doneTime = '';
  4165. if ($mainCompleted) {
  4166. if ($directComplete) {
  4167. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4168. }
  4169. if ($doneTime === '') {
  4170. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4171. }
  4172. if ($doneTime === '') {
  4173. foreach ($details as $dr) {
  4174. if (!is_array($dr)) {
  4175. continue;
  4176. }
  4177. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4178. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4179. $doneTime = $t;
  4180. }
  4181. }
  4182. }
  4183. if ($doneTime === '') {
  4184. $doneTime = $poTime;
  4185. }
  4186. if ($confirmApproveTime !== '') {
  4187. $doneTime = $confirmApproveTime;
  4188. }
  4189. }
  4190. if ($directComplete) {
  4191. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4192. $step1Done = $hasMain;
  4193. $step2Done = false;
  4194. $step3Done = false;
  4195. $step4Done = false;
  4196. $step5Done = false;
  4197. $step6Done = true;
  4198. } else {
  4199. $step1Done = $issued;
  4200. $step2Done = $issued;
  4201. $step3Done = $acceptCnt > 0;
  4202. $step4Done = $wflowPendingApproval;
  4203. if (!$step4Done) {
  4204. foreach ($details as $dr) {
  4205. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4206. $step4Done = true;
  4207. break;
  4208. }
  4209. }
  4210. }
  4211. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4212. $step6Done = $mainCompleted;
  4213. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4214. if ($mainCompleted && $issued) {
  4215. $step3Done = true;
  4216. $step4Done = true;
  4217. $step5Done = true;
  4218. if ($supplierTime === '') {
  4219. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4220. if ($fillT !== '') {
  4221. $supplierTime = $fillT;
  4222. }
  4223. }
  4224. if ($pickedTime === '') {
  4225. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4226. if ($fillT !== '') {
  4227. $pickedTime = $fillT;
  4228. }
  4229. }
  4230. if ($auditSelectTime === '') {
  4231. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4232. if ($fillT !== '') {
  4233. $auditSelectTime = $fillT;
  4234. }
  4235. }
  4236. if ($confirmApproveTime === '') {
  4237. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4238. if ($fillT !== '') {
  4239. $confirmApproveTime = $fillT;
  4240. }
  4241. }
  4242. }
  4243. }
  4244. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4245. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4246. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4247. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4248. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4249. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4250. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4251. $deadlineLines = [];
  4252. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4253. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4254. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4255. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4256. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  4257. }
  4258. }
  4259. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  4260. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  4261. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  4262. if ($deliveryDisp === '') {
  4263. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  4264. }
  4265. if ($deliveryDisp !== '') {
  4266. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  4267. }
  4268. }
  4269. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  4270. if ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') {
  4271. $deadlineLines[] = '操作时间:' . $issueOperTimeRaw;
  4272. }
  4273. $deadlineText = implode("\n", $deadlineLines);
  4274. $prefixOperTime = static function (string $t): string {
  4275. $t = trim($t);
  4276. if ($t === '' || $t === '—') {
  4277. return $t;
  4278. }
  4279. if (strpos($t, '操作时间') === 0) {
  4280. return $t;
  4281. }
  4282. return '操作时间:' . $t;
  4283. };
  4284. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  4285. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '';
  4286. $step6Time = $step6Done ? $doneTime : '';
  4287. $steps = [
  4288. [
  4289. 'title' => '未发',
  4290. 'subtitle' => '',
  4291. 'time' => $issued ? '—' : ($hasMain ? $prefixOperTime($poTime) : ''),
  4292. 'done' => $step1Done,
  4293. ],
  4294. [
  4295. 'title' => '下发',
  4296. 'subtitle' => $deadlineText,
  4297. 'time' => '',
  4298. 'done' => $step2Done,
  4299. ],
  4300. [
  4301. 'title' => '供应商接单',
  4302. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4303. 'time' => '',
  4304. 'done' => $step3Done,
  4305. ],
  4306. [
  4307. 'title' => '待确认',
  4308. 'subtitle' => $step4Done
  4309. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4310. : ($issued ? '待选供应商' : ''),
  4311. 'time' => $prefixOperTime($step4Time),
  4312. 'done' => $step4Done,
  4313. ],
  4314. [
  4315. 'title' => '待审批',
  4316. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4317. 'time' => $prefixOperTime($step5Time),
  4318. 'done' => $step5Done,
  4319. ],
  4320. [
  4321. 'title' => '已完结',
  4322. 'subtitle' => '',
  4323. 'time' => $prefixOperTime($step6Time),
  4324. 'done' => $step6Done,
  4325. ],
  4326. ];
  4327. $currentIdx = count($steps) - 1;
  4328. if (!$directComplete) {
  4329. foreach ($steps as $i => $s) {
  4330. if (!$s['done']) {
  4331. $currentIdx = $i;
  4332. break;
  4333. }
  4334. }
  4335. }
  4336. $nSteps = count($steps);
  4337. foreach ($steps as $idx => &$s) {
  4338. $s['current'] = ($idx === $currentIdx);
  4339. if ($idx === 0) {
  4340. $s['pdf_left_bg'] = '';
  4341. } else {
  4342. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4343. }
  4344. if ($idx >= $nSteps - 1) {
  4345. $s['pdf_right_bg'] = '';
  4346. } else {
  4347. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4348. }
  4349. }
  4350. unset($s);
  4351. $labelMap = [
  4352. 'CCYDH' => '订单号',
  4353. 'CYJMC' => '印件名称',
  4354. 'CCLBMMC' => '承揽部门',
  4355. 'CGYMC' => '工序名称',
  4356. 'CDW' => '单位',
  4357. 'NGZL' => '工作量',
  4358. 'CDF' => '单价',
  4359. 'cGzzxMc' => '工作中心',
  4360. 'MBZ' => '备注',
  4361. 'This_quantity' => '本次数量',
  4362. 'ceilingPrice' => '最高限价',
  4363. ];
  4364. $orderSummary = [];
  4365. foreach ($labelMap as $key => $lab) {
  4366. if (!array_key_exists($key, $main)) {
  4367. continue;
  4368. }
  4369. $val = $main[$key];
  4370. if ($val === null) {
  4371. $val = '';
  4372. } elseif (!is_scalar($val)) {
  4373. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4374. } else {
  4375. $val = (string)$val;
  4376. }
  4377. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4378. }
  4379. $orderSummaryGrid = [];
  4380. $n = count($orderSummary);
  4381. for ($i = 0; $i < $n; $i += 2) {
  4382. $left = $orderSummary[$i];
  4383. $hasRight = ($i + 1) < $n;
  4384. $orderSummaryGrid[] = [
  4385. 'l1' => $left['label'],
  4386. 'v1' => $left['value'],
  4387. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4388. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4389. ];
  4390. }
  4391. return [
  4392. 'steps' => $steps,
  4393. 'orderSummary' => $orderSummary,
  4394. 'orderSummaryGrid' => $orderSummaryGrid,
  4395. 'detailRows' => $details,
  4396. ];
  4397. }
  4398. /**
  4399. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4400. *
  4401. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4402. */
  4403. protected function prepareProcuremenDetailsView(string $ids): array
  4404. {
  4405. $main = [];
  4406. try {
  4407. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4408. $main = is_array($one) ? $one : [];
  4409. } catch (\Throwable $e) {
  4410. $main = [];
  4411. }
  4412. $details = [];
  4413. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4414. if ($mergeRows === []) {
  4415. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4416. if ($mergeRows === [] && $main !== []) {
  4417. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4418. }
  4419. }
  4420. $detailSidList = [];
  4421. $anchorSid = (int)$ids;
  4422. if ($anchorSid !== 0) {
  4423. $detailSidList[$anchorSid] = true;
  4424. }
  4425. foreach ($mergeRows as $mr) {
  4426. if (!is_array($mr)) {
  4427. continue;
  4428. }
  4429. $sid = $this->extractScydgyRowId($mr);
  4430. if ($sid !== 0) {
  4431. $detailSidList[$sid] = true;
  4432. }
  4433. }
  4434. try {
  4435. if ($detailSidList !== []) {
  4436. $details = Db::table('purchase_order_detail')
  4437. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4438. ->order('id', 'asc')
  4439. ->select();
  4440. }
  4441. } catch (\Throwable $e) {
  4442. $details = [];
  4443. }
  4444. if (!is_array($details)) {
  4445. $details = [];
  4446. }
  4447. foreach ($details as &$r) {
  4448. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4449. $r['id'] = $r['ID'];
  4450. }
  4451. if (isset($r['createtime'])) {
  4452. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4453. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4454. } else {
  4455. $r['createtime_text'] = (string)$r['createtime'];
  4456. }
  4457. } else {
  4458. $r['createtime_text'] = '';
  4459. }
  4460. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4461. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4462. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4463. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4464. if (is_array($r)) {
  4465. $r = $this->maskSupplierContactFields($r);
  4466. }
  4467. }
  4468. unset($r);
  4469. $activeDetails = [];
  4470. foreach ($details as $r) {
  4471. if (is_array($r) && empty($r['is_void'])) {
  4472. $activeDetails[] = $r;
  4473. }
  4474. }
  4475. $operLogs = [];
  4476. try {
  4477. $operSidList = array_keys($detailSidList);
  4478. if ($operSidList === [] && (int)$ids !== 0) {
  4479. $operSidList = [(int)$ids];
  4480. }
  4481. if ($operSidList !== []) {
  4482. $operLogs = Db::table('purchase_order_oper_log')
  4483. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  4484. ->order('id', 'asc')
  4485. ->select();
  4486. }
  4487. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  4488. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  4489. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  4490. if ($poId > 0) {
  4491. $operLogs = Db::table('purchase_order_oper_log')
  4492. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  4493. ->order('id', 'asc')
  4494. ->select();
  4495. }
  4496. }
  4497. } catch (\Throwable $e) {
  4498. $operLogs = [];
  4499. }
  4500. if (!is_array($operLogs)) {
  4501. $operLogs = [];
  4502. }
  4503. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4504. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4505. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4506. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4507. if ($ccydh === '') {
  4508. foreach ($details as $r) {
  4509. if (!is_array($r)) {
  4510. continue;
  4511. }
  4512. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4513. if ($ccydh !== '') {
  4514. break;
  4515. }
  4516. }
  4517. }
  4518. $this->view->assign('ccydh', $ccydh);
  4519. $this->view->assign('steps', $bundle['steps']);
  4520. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4521. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4522. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4523. $this->view->assign('processCount', count($mergeRows));
  4524. $this->view->assign('detailRows', $details);
  4525. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4526. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4527. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4528. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4529. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4530. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4531. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4532. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4533. $this->view->assign('operLogs', $operLogs);
  4534. return [
  4535. 'ok' => $main !== [] || $details !== [],
  4536. 'ccydh' => $ccydh,
  4537. ];
  4538. }
  4539. /**
  4540. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4541. */
  4542. public function details()
  4543. {
  4544. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4545. if (is_array($ids)) {
  4546. $ids = isset($ids[0]) ? $ids[0] : '';
  4547. }
  4548. $ids = trim((string)$ids);
  4549. if ($ids === '') {
  4550. $this->error(__('Invalid parameters'));
  4551. }
  4552. $this->assertManualOrderDetailsViewable((int)$ids);
  4553. $this->prepareProcuremenDetailsView($ids);
  4554. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4555. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4556. $this->view->engine->layout(false);
  4557. try {
  4558. return $this->view->fetch('procuremen/details_dialog_shell');
  4559. } finally {
  4560. if ($restoreLayout) {
  4561. $this->view->engine->layout($restoreLayout);
  4562. }
  4563. }
  4564. }
  4565. /**
  4566. * 解析合并审核工序行(订单号须一致,且均未协助)
  4567. *
  4568. * @return array<int, array<string, mixed>>
  4569. */
  4570. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4571. {
  4572. $primary = json_decode($rowJson, true);
  4573. if (!is_array($primary)) {
  4574. $this->error(__('Invalid parameters'));
  4575. }
  4576. $merge = json_decode($mergeRowsJson, true);
  4577. if (!is_array($merge) || $merge === []) {
  4578. $merge = [$primary];
  4579. }
  4580. $seen = [];
  4581. $out = [];
  4582. foreach ($merge as $r) {
  4583. if (!is_array($r)) {
  4584. continue;
  4585. }
  4586. $id = $this->extractScydgyRowId($r);
  4587. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4588. continue;
  4589. }
  4590. $seen[$id] = true;
  4591. $out[] = $r;
  4592. }
  4593. if ($out === []) {
  4594. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4595. }
  4596. $ccydh = null;
  4597. foreach ($out as $r) {
  4598. $dh = trim((string)($r['CCYDH'] ?? ''));
  4599. if ($ccydh === null) {
  4600. $ccydh = $dh;
  4601. } elseif ($dh !== $ccydh) {
  4602. $this->error('合并审核要求所选行的订单号一致');
  4603. }
  4604. }
  4605. $ids = [];
  4606. foreach ($out as $r) {
  4607. $id = $this->extractScydgyRowId($r);
  4608. if ($this->isValidScydgyRowId($id)) {
  4609. $ids[$id] = true;
  4610. }
  4611. }
  4612. $poBySid = [];
  4613. $detCntBySid = [];
  4614. if ($ids !== []) {
  4615. $idList = array_keys($ids);
  4616. try {
  4617. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4618. if (is_array($poList)) {
  4619. foreach ($poList as $po) {
  4620. if (!is_array($po)) {
  4621. continue;
  4622. }
  4623. $sid = (int)($po['scydgy_id'] ?? 0);
  4624. if ($this->isValidScydgyRowId($sid)) {
  4625. $poBySid[$sid] = $po;
  4626. }
  4627. }
  4628. }
  4629. } catch (\Throwable $e) {
  4630. }
  4631. try {
  4632. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4633. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4634. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4635. if (is_array($detRows)) {
  4636. foreach ($detRows as $dr) {
  4637. if (!is_array($dr)) {
  4638. continue;
  4639. }
  4640. $sid = (int)($dr['scydgy_id'] ?? 0);
  4641. if ($this->isValidScydgyRowId($sid)) {
  4642. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4643. }
  4644. }
  4645. }
  4646. } catch (\Throwable $e) {
  4647. }
  4648. }
  4649. foreach ($out as $r) {
  4650. $id = $this->extractScydgyRowId($r);
  4651. if (!$this->isValidScydgyRowId($id)) {
  4652. continue;
  4653. }
  4654. $po = $poBySid[$id] ?? null;
  4655. if (!is_array($po)) {
  4656. continue;
  4657. }
  4658. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4659. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4660. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4661. }
  4662. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4663. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4664. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4665. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4666. }
  4667. }
  4668. return $out;
  4669. }
  4670. /**
  4671. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4672. */
  4673. protected function maskSupplierContactFields(array $item): array
  4674. {
  4675. if (array_key_exists('email', $item)) {
  4676. $item['email'] = mask_email((string)$item['email']);
  4677. }
  4678. if (array_key_exists('phone', $item)) {
  4679. $item['phone'] = mask_phone((string)$item['phone']);
  4680. }
  4681. return $item;
  4682. }
  4683. /**
  4684. * @param array<int, array<string, mixed>> $list
  4685. * @return array<int, array<string, mixed>>
  4686. */
  4687. protected function maskSupplierContactList(array $list): array
  4688. {
  4689. $out = [];
  4690. foreach ($list as $item) {
  4691. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4692. }
  4693. return $out;
  4694. }
  4695. /**
  4696. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4697. *
  4698. * @return array<string, string>|null
  4699. */
  4700. protected function buildCustomerContactPayloadFromRow($row): ?array
  4701. {
  4702. if (!is_array($row)) {
  4703. return null;
  4704. }
  4705. $norm = [];
  4706. foreach ($row as $k => $v) {
  4707. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4708. }
  4709. $row = $norm;
  4710. $st = $row['status'] ?? '';
  4711. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4712. return null;
  4713. }
  4714. $companyName = '';
  4715. foreach (['company_name', 'name'] as $nk) {
  4716. if (!empty($row[$nk])) {
  4717. $companyName = trim((string)$row[$nk]);
  4718. break;
  4719. }
  4720. }
  4721. if ($companyName === '') {
  4722. return null;
  4723. }
  4724. $username = '';
  4725. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4726. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4727. $username = trim((string)$row[$uk]);
  4728. break;
  4729. }
  4730. }
  4731. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4732. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4733. if ($phone === '' && isset($row['account'])) {
  4734. $phone = trim((string)$row['account']);
  4735. }
  4736. if ($phone === '' && isset($row['mobile'])) {
  4737. $phone = trim((string)$row['mobile']);
  4738. }
  4739. if ($email === '' && $phone === '') {
  4740. return null;
  4741. }
  4742. $category = '';
  4743. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4744. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4745. $category = trim((string)$row[$ck]);
  4746. break;
  4747. }
  4748. }
  4749. return [
  4750. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4751. 'name' => $companyName,
  4752. 'company_name' => $companyName,
  4753. 'username' => $username,
  4754. 'email' => $email,
  4755. 'phone' => $phone,
  4756. 'category' => $category,
  4757. 'company_type' => $category,
  4758. ];
  4759. }
  4760. /**
  4761. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4762. */
  4763. protected function resolveCustomerContactById(string $id): ?array
  4764. {
  4765. $id = trim($id);
  4766. if ($id === '' || !ctype_digit($id)) {
  4767. return null;
  4768. }
  4769. try {
  4770. $row = Db::table('customer')->where('id', (int)$id)->find();
  4771. } catch (\Throwable $e) {
  4772. return null;
  4773. }
  4774. return $this->buildCustomerContactPayloadFromRow($row);
  4775. }
  4776. /**
  4777. * 按供应商名称解析联系信息(兼容旧提交数据)
  4778. */
  4779. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4780. {
  4781. $name = trim($name);
  4782. if ($name === '') {
  4783. return null;
  4784. }
  4785. try {
  4786. $row = Db::table('customer')
  4787. ->where(function ($q) use ($name) {
  4788. $q->where('company_name', $name)->whereOr('name', $name);
  4789. })
  4790. ->order('id', 'desc')
  4791. ->find();
  4792. } catch (\Throwable $e) {
  4793. return null;
  4794. }
  4795. return $this->buildCustomerContactPayloadFromRow($row);
  4796. }
  4797. /**
  4798. * 规范化下发/确认时勾选的供应商
  4799. *
  4800. * @param array<int, mixed> $companies
  4801. * @return array<int, array<string, string>>
  4802. */
  4803. protected function normalizePickCompanies(array $companies): array
  4804. {
  4805. $out = [];
  4806. foreach ($companies as $c) {
  4807. if (!is_array($c)) {
  4808. continue;
  4809. }
  4810. $resolved = null;
  4811. $cid = trim((string)($c['id'] ?? ''));
  4812. if ($cid !== '') {
  4813. $resolved = $this->resolveCustomerContactById($cid);
  4814. }
  4815. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4816. if ($resolved === null && $name !== '') {
  4817. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4818. }
  4819. if ($resolved === null) {
  4820. continue;
  4821. }
  4822. $out[] = $resolved;
  4823. }
  4824. return $out;
  4825. }
  4826. /**
  4827. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4828. *
  4829. * @param array<int, array<string, mixed>> $pool
  4830. * @return array<int, array<string, mixed>>
  4831. */
  4832. protected function collapseProcuremenPoolByOrder(array $pool): array
  4833. {
  4834. if ($pool === []) {
  4835. return [];
  4836. }
  4837. $groups = [];
  4838. foreach ($pool as $row) {
  4839. if (!is_array($row)) {
  4840. continue;
  4841. }
  4842. $dh = trim((string)($row['CCYDH'] ?? ''));
  4843. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4844. if (!isset($groups[$key])) {
  4845. $groups[$key] = [];
  4846. }
  4847. $groups[$key][] = $row;
  4848. }
  4849. $out = [];
  4850. foreach ($groups as $ccydh => $rows) {
  4851. if ($rows === []) {
  4852. continue;
  4853. }
  4854. usort($rows, function ($a, $b) {
  4855. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4856. });
  4857. $head = $rows[0];
  4858. $gymcList = [];
  4859. foreach ($rows as $r) {
  4860. $g = trim((string)($r['CGYMC'] ?? ''));
  4861. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4862. $gymcList[] = $g;
  4863. }
  4864. }
  4865. $merged = $head;
  4866. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4867. $merged['process_count'] = count($rows);
  4868. $merged['_order_merge_rows'] = $rows;
  4869. if (count($rows) > 1) {
  4870. $merged['CGYMC'] = implode('、', $gymcList);
  4871. }
  4872. $mergedPickTime = '';
  4873. foreach ($rows as $r) {
  4874. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4875. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4876. $mergedPickTime = $t;
  4877. }
  4878. }
  4879. if ($mergedPickTime !== '') {
  4880. $merged['pick_time'] = $mergedPickTime;
  4881. }
  4882. $out[] = $merged;
  4883. }
  4884. usort($out, function ($a, $b) {
  4885. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4886. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4887. if ($ta === $tb) {
  4888. $ida = (int)($a['purchase_order_id'] ?? 0);
  4889. $idb = (int)($b['purchase_order_id'] ?? 0);
  4890. if ($ida !== $idb) {
  4891. return $idb <=> $ida;
  4892. }
  4893. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4894. }
  4895. if ($ta === '') {
  4896. return 1;
  4897. }
  4898. if ($tb === '') {
  4899. return -1;
  4900. }
  4901. return strcmp($tb, $ta);
  4902. });
  4903. return $out;
  4904. }
  4905. /**
  4906. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4907. *
  4908. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4909. */
  4910. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4911. {
  4912. $scydgyId = trim($scydgyId);
  4913. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4914. if ($scydgyId === '') {
  4915. return $empty;
  4916. }
  4917. try {
  4918. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4919. } catch (\Throwable $e) {
  4920. $anchor = null;
  4921. }
  4922. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4923. return $empty;
  4924. }
  4925. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4926. if ($ccydh === '') {
  4927. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4928. }
  4929. try {
  4930. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4931. } catch (\Throwable $e) {
  4932. $pos = [$anchor];
  4933. }
  4934. if (!is_array($pos) || $pos === []) {
  4935. $pos = [$anchor];
  4936. }
  4937. return [
  4938. 'ccydh' => $ccydh,
  4939. 'pos' => $pos,
  4940. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4941. ];
  4942. }
  4943. /**
  4944. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4945. */
  4946. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4947. {
  4948. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4949. return false;
  4950. }
  4951. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4952. return false;
  4953. }
  4954. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4955. return true;
  4956. }
  4957. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4958. $sid = (int)($po['scydgy_id'] ?? 0);
  4959. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4960. }
  4961. return false;
  4962. }
  4963. /**
  4964. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4965. *
  4966. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4967. */
  4968. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4969. {
  4970. $scydgyId = trim($scydgyId);
  4971. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4972. if ($scydgyId === '') {
  4973. return $empty;
  4974. }
  4975. try {
  4976. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4977. } catch (\Throwable $e) {
  4978. $anchor = null;
  4979. }
  4980. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4981. return $empty;
  4982. }
  4983. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4984. if ($ccydh === '') {
  4985. return [
  4986. 'ccydh' => '',
  4987. 'pos' => [$anchor],
  4988. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4989. ];
  4990. }
  4991. try {
  4992. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4993. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4994. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4995. } catch (\Throwable $e) {
  4996. $pos = [$anchor];
  4997. }
  4998. if (!is_array($pos) || $pos === []) {
  4999. $pos = [$anchor];
  5000. }
  5001. $pos = array_values(array_filter($pos, function ($po) {
  5002. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  5003. }));
  5004. if ($pos === []) {
  5005. $pos = [$anchor];
  5006. }
  5007. return [
  5008. 'ccydh' => $ccydh,
  5009. 'pos' => $pos,
  5010. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5011. ];
  5012. }
  5013. /**
  5014. * @param array<int, array<string, mixed>> $purchaseOrders
  5015. * @return array<int, array<string, mixed>>
  5016. */
  5017. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  5018. {
  5019. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  5020. $byId = [];
  5021. foreach ($pool as $r) {
  5022. if (!is_array($r)) {
  5023. continue;
  5024. }
  5025. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  5026. if ($this->isValidScydgyRowId($sid)) {
  5027. $byId[$sid] = $r;
  5028. }
  5029. }
  5030. $out = [];
  5031. foreach ($purchaseOrders as $po) {
  5032. if (!is_array($po)) {
  5033. continue;
  5034. }
  5035. $sid = (int)($po['scydgy_id'] ?? 0);
  5036. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  5037. $out[] = $byId[$sid];
  5038. }
  5039. }
  5040. return $out;
  5041. }
  5042. /**
  5043. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  5044. *
  5045. * @return array<int, array<string, mixed>>
  5046. */
  5047. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5048. {
  5049. $scydgyId = trim($scydgyId);
  5050. if ($scydgyId === '') {
  5051. return [];
  5052. }
  5053. try {
  5054. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5055. } catch (\Throwable $e) {
  5056. $anchor = null;
  5057. }
  5058. if (!is_array($anchor)) {
  5059. return [];
  5060. }
  5061. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5062. return [];
  5063. }
  5064. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5065. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5066. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5067. try {
  5068. $q = Db::table('purchase_order');
  5069. if ($ccydh !== '') {
  5070. $q->where('CCYDH', $ccydh);
  5071. } else {
  5072. $q->where('scydgy_id', $scydgyId);
  5073. }
  5074. if ($isValidPick) {
  5075. $q->where('pick_time', $pickTime);
  5076. }
  5077. $pos = $q->order('scydgy_id', 'asc')->select();
  5078. } catch (\Throwable $e) {
  5079. $pos = [$anchor];
  5080. }
  5081. if (!is_array($pos) || $pos === []) {
  5082. $pos = [$anchor];
  5083. }
  5084. $pos = array_values(array_filter($pos, function ($po) {
  5085. if (!is_array($po)) {
  5086. return false;
  5087. }
  5088. $mr = $po['mod_rq'] ?? null;
  5089. if ($mr === null || $mr === '') {
  5090. return true;
  5091. }
  5092. $mrs = trim((string)$mr);
  5093. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5094. }));
  5095. if ($pos === []) {
  5096. $pos = [$anchor];
  5097. }
  5098. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5099. if ($rows === []) {
  5100. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5101. }
  5102. return $rows;
  5103. }
  5104. /**
  5105. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5106. *
  5107. * @param array<int, array<string, mixed>> $mergeRows
  5108. * @return array<int, array<string, mixed>>
  5109. */
  5110. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5111. {
  5112. $list = array_values($mergeRows);
  5113. $n = count($list);
  5114. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5115. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5116. $mergeSame = $n > 1 && $orderKey0 !== '';
  5117. if ($mergeSame) {
  5118. foreach ($list as $rr) {
  5119. if (!is_array($rr)) {
  5120. $mergeSame = false;
  5121. break;
  5122. }
  5123. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5124. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5125. $mergeSame = false;
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. $out = [];
  5131. foreach ($list as $idx => $r) {
  5132. if (!is_array($r)) {
  5133. continue;
  5134. }
  5135. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5136. if (is_scalar($qty)) {
  5137. $qty = trim((string)$qty);
  5138. } else {
  5139. $qty = '';
  5140. }
  5141. if ($qty === '') {
  5142. $gzl = $r['NGZL'] ?? '';
  5143. if (is_scalar($gzl)) {
  5144. $qty = trim((string)$gzl);
  5145. }
  5146. }
  5147. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5148. $sid = $this->extractScydgyRowId($r);
  5149. $out[] = [
  5150. 'seq' => $idx + 1,
  5151. 'scydgy_id' => $sid,
  5152. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5153. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5154. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5155. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5156. 'NGZL' => $r['NGZL'] ?? '',
  5157. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5158. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5159. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5160. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5161. 'show_order_cells' => !$mergeSame || $idx === 0,
  5162. 'order_rowspan' => $mergeSame ? $n : 1,
  5163. ];
  5164. }
  5165. return $out;
  5166. }
  5167. /**
  5168. * 解析金额/数量(去千分位等非数字字符)
  5169. */
  5170. protected function parseProcuremenMoneyNumber($value): ?float
  5171. {
  5172. if ($value === null || $value === '') {
  5173. return null;
  5174. }
  5175. if (is_numeric($value)) {
  5176. return (float)$value;
  5177. }
  5178. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5179. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5180. }
  5181. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5182. {
  5183. if ($amount === null) {
  5184. return '';
  5185. }
  5186. return (string)(int)round($amount);
  5187. }
  5188. /**
  5189. * 列表/详情展示:工作量为 0 时显示空
  5190. */
  5191. protected function formatProcuremenWorkloadDisplay($value): string
  5192. {
  5193. if ($value === null || $value === '') {
  5194. return '';
  5195. }
  5196. $s = trim((string)$value);
  5197. if ($s === '') {
  5198. return '';
  5199. }
  5200. if (is_numeric($s) && (float)$s == 0) {
  5201. return '';
  5202. }
  5203. return $s;
  5204. }
  5205. /**
  5206. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5207. */
  5208. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5209. {
  5210. foreach ($details as $d) {
  5211. if (!is_array($d)) {
  5212. continue;
  5213. }
  5214. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5215. $cn = trim((string)($d['company_name'] ?? ''));
  5216. if ($cn !== '') {
  5217. return $cn;
  5218. }
  5219. }
  5220. }
  5221. return trim((string)($main['pick_company_name'] ?? ''));
  5222. }
  5223. /**
  5224. * 详情报价小计:单价 × 本工序本次数量
  5225. */
  5226. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5227. {
  5228. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5229. if ($unit === null) {
  5230. return null;
  5231. }
  5232. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5233. if ($qty === null || $qty <= 0) {
  5234. return null;
  5235. }
  5236. return $unit * $qty;
  5237. }
  5238. /**
  5239. * 详情页:工序小计 + 供应商分组报价与总计
  5240. *
  5241. * @param array<int, array<string, mixed>> $mergeRows
  5242. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5243. * @return array{
  5244. * process_rows: array,
  5245. * supplier_groups: array,
  5246. * order_total_text: string,
  5247. * order_total_has: bool,
  5248. * selected_company: string
  5249. * }
  5250. */
  5251. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5252. {
  5253. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5254. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5255. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5256. $qtyBySid = [];
  5257. $gymcBySid = [];
  5258. $orderedSids = [];
  5259. foreach ($mergeRows as $mr) {
  5260. if (!is_array($mr)) {
  5261. continue;
  5262. }
  5263. $sid = $this->extractScydgyRowId($mr);
  5264. if ($this->isValidScydgyRowId($sid)) {
  5265. $orderedSids[] = $sid;
  5266. }
  5267. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5268. if ($qty === '') {
  5269. $qty = trim((string)($mr['NGZL'] ?? ''));
  5270. }
  5271. $qtyBySid[$sid] = $qty;
  5272. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5273. }
  5274. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5275. $detailByCompanySid = [];
  5276. foreach ($details as $d) {
  5277. if (!is_array($d)) {
  5278. continue;
  5279. }
  5280. $cn = trim((string)($d['company_name'] ?? ''));
  5281. $sid = (int)($d['scydgy_id'] ?? 0);
  5282. if ($cn === '' || $sid === 0) {
  5283. continue;
  5284. }
  5285. if (!isset($detailByCompanySid[$cn])) {
  5286. $detailByCompanySid[$cn] = [];
  5287. }
  5288. $detailByCompanySid[$cn][$sid] = $d;
  5289. }
  5290. $supplierGroups = [];
  5291. foreach ($detailByCompanySid as $cn => $bySid) {
  5292. $lines = [];
  5293. $groupTotal = 0.0;
  5294. $groupHas = false;
  5295. $groupVoid = true;
  5296. $usedSids = [];
  5297. $appendLine = function (int $sid, array $d) use (
  5298. &$lines,
  5299. &$groupTotal,
  5300. &$groupHas,
  5301. &$groupVoid,
  5302. $qtyBySid,
  5303. $gymcBySid,
  5304. $quoteVisible
  5305. ) {
  5306. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5307. if (!$isVoid) {
  5308. $groupVoid = false;
  5309. }
  5310. $qtyStr = $qtyBySid[$sid] ?? '';
  5311. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5312. $am = trim((string)($d['amount'] ?? ''));
  5313. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5314. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5315. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5316. $sub = null;
  5317. if (!$isVoid && $amountNum !== null) {
  5318. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5319. }
  5320. $ct = $this->resolveDetailSupplierOperTime($d);
  5321. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5322. $leadFilled = ($leadDays !== null);
  5323. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5324. $line = [
  5325. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5326. 'unit_price_text' => $amountFilled
  5327. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5328. : '未填写',
  5329. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5330. 'delivery_ymd' => $deliveryYmd,
  5331. 'amount_filled' => $amountFilled,
  5332. 'delivery_filled' => $deliveryFilled,
  5333. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5334. 'lead_days' => $leadFilled ? $leadDays : '',
  5335. 'lead_days_filled'=> $leadFilled,
  5336. 'lead_days_show' => $leadText,
  5337. 'lead_days_text' => $leadText,
  5338. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5339. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5340. 'is_void' => $isVoid,
  5341. 'oper_time_text' => $ct,
  5342. ];
  5343. if (!$quoteVisible && !$isVoid) {
  5344. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5345. } elseif ($sub !== null) {
  5346. $groupTotal += $sub;
  5347. $groupHas = true;
  5348. }
  5349. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5350. };
  5351. foreach ($orderedSids as $sid) {
  5352. if (!isset($bySid[$sid])) {
  5353. continue;
  5354. }
  5355. $usedSids[$sid] = true;
  5356. $appendLine($sid, $bySid[$sid]);
  5357. }
  5358. foreach ($bySid as $sid => $d) {
  5359. if (isset($usedSids[$sid])) {
  5360. continue;
  5361. }
  5362. $appendLine((int)$sid, $d);
  5363. }
  5364. $firstDetail = null;
  5365. foreach ($bySid as $d) {
  5366. if (is_array($d)) {
  5367. $firstDetail = $d;
  5368. break;
  5369. }
  5370. }
  5371. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5372. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5373. if ($username === '' && $ph !== '') {
  5374. $username = $this->resolveCustomerContactName($ph, $cn);
  5375. }
  5376. $remark = '';
  5377. foreach ($bySid as $d) {
  5378. if (!is_array($d)) {
  5379. continue;
  5380. }
  5381. $rm = '';
  5382. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5383. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5384. $rm = trim((string)$d[$rk]);
  5385. break;
  5386. }
  5387. }
  5388. if ($rm !== '') {
  5389. $remark = $rm;
  5390. break;
  5391. }
  5392. }
  5393. $lineCount = count($lines);
  5394. $hasRemark = $lineCount > 0;
  5395. $supplierGroup = [
  5396. 'company_name' => $cn,
  5397. 'username' => $username,
  5398. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5399. 'phone' => $ph,
  5400. 'remark' => $remark,
  5401. 'has_remark' => $hasRemark,
  5402. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5403. 'is_void' => $groupVoid,
  5404. 'lines' => $lines,
  5405. 'line_count' => $lineCount,
  5406. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5407. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5408. 'has_total' => $lineCount > 0,
  5409. ];
  5410. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5411. $supplierGroups[] = $supplierGroup;
  5412. }
  5413. usort($supplierGroups, function ($a, $b) {
  5414. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5415. return ($a['is_void'] ?? false) ? 1 : -1;
  5416. }
  5417. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5418. return ($a['is_selected'] ?? false) ? -1 : 1;
  5419. }
  5420. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5421. });
  5422. return [
  5423. 'process_rows' => $processRows,
  5424. 'supplier_groups' => $supplierGroups,
  5425. 'order_total_text' => '',
  5426. 'order_total_has' => false,
  5427. 'selected_company' => $selectedCompany,
  5428. ];
  5429. }
  5430. /**
  5431. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5432. */
  5433. protected function buildProcessLinesPlain(array $mergeRows): string
  5434. {
  5435. $lines = [];
  5436. $i = 1;
  5437. foreach ($mergeRows as $r) {
  5438. if (!is_array($r)) {
  5439. continue;
  5440. }
  5441. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5442. $dw = trim((string)($r['CDW'] ?? ''));
  5443. $gzl = trim((string)($r['NGZL'] ?? ''));
  5444. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5445. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5446. if ($dw !== '') {
  5447. $parts[] = '单位:' . $dw;
  5448. }
  5449. if ($gzl !== '') {
  5450. $parts[] = '工作量:' . $gzl;
  5451. }
  5452. if ($qty !== '') {
  5453. $parts[] = '本次数量:' . $qty;
  5454. }
  5455. $lines[] = implode(' ', $parts);
  5456. $i++;
  5457. }
  5458. return implode("\n", $lines);
  5459. }
  5460. /**
  5461. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5462. *
  5463. * @return array<string, string>
  5464. */
  5465. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5466. {
  5467. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5468. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5469. }
  5470. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5471. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5472. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5473. $cyjmc = '';
  5474. foreach ($mergeRows as $mr) {
  5475. if (!is_array($mr)) {
  5476. continue;
  5477. }
  5478. if ($ccydh === '') {
  5479. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5480. }
  5481. if ($cyjmc === '') {
  5482. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5483. }
  5484. }
  5485. if ($pos !== []) {
  5486. $firstPo = $pos[0];
  5487. if (is_array($firstPo)) {
  5488. if ($ccydh === '') {
  5489. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5490. }
  5491. if ($cyjmc === '') {
  5492. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5493. }
  5494. }
  5495. }
  5496. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5497. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5498. if (is_array($any)) {
  5499. if ($ccydh === '') {
  5500. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5501. }
  5502. if ($cyjmc === '') {
  5503. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5504. }
  5505. }
  5506. }
  5507. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5508. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5509. $cgymc = '';
  5510. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5511. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5512. }
  5513. return [
  5514. 'ccydh' => $ccydh,
  5515. 'cyjmc' => $cyjmc,
  5516. 'cgymc' => $cgymc,
  5517. 'process_lines' => $processLines,
  5518. 'process_lines_html' => '',
  5519. ];
  5520. }
  5521. /**
  5522. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5523. */
  5524. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5525. {
  5526. $lines = [];
  5527. if ($ccydh !== '') {
  5528. $lines[] = '订单号:' . $ccydh;
  5529. }
  5530. if ($cyjmc !== '') {
  5531. $lines[] = '印件名称:' . $cyjmc;
  5532. }
  5533. if ($processPlain !== '') {
  5534. $lines[] = $processPlain;
  5535. }
  5536. return implode("\n", $lines);
  5537. }
  5538. /**
  5539. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5540. *
  5541. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5542. */
  5543. protected function buildPlatformLinksPlain(array $detailLinks): string
  5544. {
  5545. $lines = [];
  5546. $i = 1;
  5547. foreach ($detailLinks as $lk) {
  5548. if (!is_array($lk)) {
  5549. continue;
  5550. }
  5551. $url = trim((string)($lk['url'] ?? ''));
  5552. if ($url === '') {
  5553. continue;
  5554. }
  5555. $label = trim((string)($lk['cgymc'] ?? ''));
  5556. if ($label === '') {
  5557. $label = '工序' . $i;
  5558. }
  5559. $lines[] = $label . ':' . $url;
  5560. $i++;
  5561. }
  5562. return implode("\n", $lines);
  5563. }
  5564. /**
  5565. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5566. *
  5567. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5568. */
  5569. protected function buildPlatformLinksHtml(array $detailLinks): string
  5570. {
  5571. $parts = [];
  5572. $i = 1;
  5573. foreach ($detailLinks as $lk) {
  5574. if (!is_array($lk)) {
  5575. continue;
  5576. }
  5577. $url = trim((string)($lk['url'] ?? ''));
  5578. if ($url === '') {
  5579. continue;
  5580. }
  5581. $label = trim((string)($lk['cgymc'] ?? ''));
  5582. if ($label === '') {
  5583. $label = '工序' . $i;
  5584. }
  5585. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5586. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5587. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5588. $i++;
  5589. }
  5590. return implode("<br>\n", $parts);
  5591. }
  5592. /**
  5593. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5594. *
  5595. * @return array<string, mixed>
  5596. */
  5597. protected function loadMailerConfig(): array
  5598. {
  5599. try {
  5600. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5601. } catch (\Throwable $e) {
  5602. $cfg = [];
  5603. }
  5604. return is_array($cfg) ? $cfg : [];
  5605. }
  5606. protected function loadNotifyTemplateRow(string $scene): ?array
  5607. {
  5608. try {
  5609. $row = Db::table('purchase_sms_template')
  5610. ->where('scene', $scene)
  5611. ->where(function ($q) {
  5612. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5613. })
  5614. ->order('id', 'asc')
  5615. ->find();
  5616. } catch (\Throwable $e) {
  5617. return null;
  5618. }
  5619. if (!is_array($row) || $row === []) {
  5620. return null;
  5621. }
  5622. return [
  5623. 'title' => trim((string)($row['title'] ?? '')),
  5624. 'content' => trim((string)($row['content'] ?? '')),
  5625. ];
  5626. }
  5627. /**
  5628. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5629. */
  5630. protected function buildProcessLinesHtml(array $mergeRows): string
  5631. {
  5632. if (count($mergeRows) <= 1) {
  5633. $r = $mergeRows[0] ?? [];
  5634. if (!is_array($r)) {
  5635. return '';
  5636. }
  5637. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5638. $dw = trim((string)($r['CDW'] ?? ''));
  5639. $gzl = trim((string)($r['NGZL'] ?? ''));
  5640. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5641. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5642. if ($dw !== '') {
  5643. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5644. }
  5645. if ($gzl !== '') {
  5646. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5647. }
  5648. if ($qty !== '') {
  5649. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5650. }
  5651. return $html;
  5652. }
  5653. $rows = '';
  5654. $i = 1;
  5655. foreach ($mergeRows as $r) {
  5656. if (!is_array($r)) {
  5657. continue;
  5658. }
  5659. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5660. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5661. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5662. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5663. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5664. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5665. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5666. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5667. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5668. $i++;
  5669. }
  5670. if ($rows === '') {
  5671. return '';
  5672. }
  5673. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5674. . '<thead><tr style="background:#f5f5f5;">'
  5675. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5676. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5677. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5678. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5679. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5680. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5681. }
  5682. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5683. {
  5684. $sysRq = trim($sysRq);
  5685. if ($sysRq === '') {
  5686. if ($required) {
  5687. $this->error('请选择招标截止日期');
  5688. }
  5689. return '';
  5690. }
  5691. $ts = strtotime($sysRq);
  5692. if ($ts === false || $ts <= 0) {
  5693. $this->error('招标截止日期格式无效');
  5694. }
  5695. $ymd = date('Y-m-d', $ts);
  5696. if ($ymd < date('Y-m-d')) {
  5697. $this->error('招标截止日期不能早于今天');
  5698. }
  5699. if ($ts <= time()) {
  5700. $this->error('招标截止时间不能早于当前时间');
  5701. }
  5702. return date('Y-m-d H:i:s', $ts);
  5703. }
  5704. /**
  5705. * 确保 purchase_order.delivery_deadline 存在
  5706. */
  5707. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  5708. {
  5709. static $done = false;
  5710. if ($done) {
  5711. return;
  5712. }
  5713. $done = true;
  5714. try {
  5715. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  5716. if (empty($cols)) {
  5717. Db::execute(
  5718. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  5719. );
  5720. }
  5721. } catch (\Throwable $e) {
  5722. // ignore
  5723. }
  5724. }
  5725. /**
  5726. * 解析交货截止日期(仅年月日)
  5727. */
  5728. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  5729. {
  5730. $raw = trim($raw);
  5731. if ($raw === '') {
  5732. if ($required) {
  5733. $this->error('请选择交货截止日期');
  5734. }
  5735. return '';
  5736. }
  5737. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  5738. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  5739. } else {
  5740. $ts = strtotime(str_replace('/', '-', $raw));
  5741. if ($ts === false || $ts <= 0) {
  5742. $this->error('交货截止日期格式无效');
  5743. }
  5744. $ymd = date('Y-m-d', $ts);
  5745. }
  5746. if ($ymd < date('Y-m-d')) {
  5747. $this->error('交货截止日期不能早于今天');
  5748. }
  5749. return $ymd;
  5750. }
  5751. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  5752. {
  5753. $s = trim((string)$value);
  5754. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  5755. return '';
  5756. }
  5757. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5758. return $m[1];
  5759. }
  5760. $ts = strtotime(str_replace('/', '-', $s));
  5761. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  5762. }
  5763. /**
  5764. * @param array{pos?:array} $bundle
  5765. */
  5766. protected function resolveBundleDeliveryDeadline(array $bundle): string
  5767. {
  5768. foreach ($bundle['pos'] ?? [] as $po) {
  5769. if (!is_array($po)) {
  5770. continue;
  5771. }
  5772. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  5773. if ($d !== '') {
  5774. return $d;
  5775. }
  5776. }
  5777. return '';
  5778. }
  5779. protected function formatProcuremenSysRqForInput($sysRq): string
  5780. {
  5781. $sr = trim((string)$sysRq);
  5782. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5783. return '';
  5784. }
  5785. $ts = strtotime($sr);
  5786. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5787. }
  5788. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5789. {
  5790. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5791. if ($sr === '') {
  5792. return '—';
  5793. }
  5794. $ts = strtotime($sr);
  5795. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5796. }
  5797. /**
  5798. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5799. *
  5800. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5801. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5802. */
  5803. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5804. {
  5805. return $bundle;
  5806. }
  5807. /**
  5808. * 写入/更新 purchase_order(单道工序行)
  5809. */
  5810. protected function upsertPurchaseOrderFromRow(
  5811. array $row,
  5812. string $sysRqDb,
  5813. $wflowStatus = null,
  5814. ?string $pickTime = null,
  5815. ?array $exists = null,
  5816. ?string $deliveryDeadline = null
  5817. ): void {
  5818. $ids = $this->extractScydgyRowId($row);
  5819. if (!$this->isValidScydgyRowId($ids)) {
  5820. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5821. }
  5822. if ($exists === null) {
  5823. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5824. }
  5825. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  5826. $data = [
  5827. 'scydgy_id' => $ids,
  5828. 'CCYDH' => $row['CCYDH'] ?? null,
  5829. 'CYJMC' => $row['CYJMC'] ?? null,
  5830. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5831. 'CDXMC' => $row['CDXMC'] ?? null,
  5832. 'CGYBH' => $row['CGYBH'] ?? null,
  5833. 'CGYMC' => $row['CGYMC'] ?? null,
  5834. 'CDW' => $row['CDW'] ?? null,
  5835. 'NGZL' => $row['NGZL'] ?? null,
  5836. 'CDF' => $row['CDF'] ?? null,
  5837. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5838. 'MBZ' => $row['MBZ'] ?? null,
  5839. 'bwjg' => $row['bwjg'] ?? null,
  5840. 'iStatus' => $row['iStatus'] ?? null,
  5841. 'dStamp' => $row['dStamp'] ?? null,
  5842. 'dputrecord' => $row['dputrecord'] ?? null,
  5843. 'cywyxm' => $row['cywyxm'] ?? null,
  5844. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5845. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5846. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5847. 'sys_rq' => $sysRqDb,
  5848. ];
  5849. if ($deliveryDeadline !== null) {
  5850. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  5851. }
  5852. if ($wflowStatus !== null && $wflowStatus !== '') {
  5853. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5854. }
  5855. if ($pickTime !== null && $pickTime !== '') {
  5856. $data['pick_time'] = $pickTime;
  5857. $data['pick_company_name'] = '';
  5858. }
  5859. if ($exists) {
  5860. $upd = $data;
  5861. unset($upd['scydgy_id']);
  5862. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5863. } else {
  5864. $data['createtime'] = date('Y-m-d H:i:s');
  5865. Db::table('purchase_order')->insert($data);
  5866. }
  5867. }
  5868. /**
  5869. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5870. *
  5871. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5872. */
  5873. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5874. {
  5875. $toDb = function ($value) {
  5876. if ($value === null) {
  5877. return null;
  5878. }
  5879. if (is_scalar($value)) {
  5880. return $value;
  5881. }
  5882. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5883. };
  5884. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5885. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5886. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5887. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5888. if ($username === '') {
  5889. $username = $this->resolveCustomerContactName($phone, $companyName);
  5890. }
  5891. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5892. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5893. }
  5894. if ($phone === '') {
  5895. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5896. }
  5897. $detailLinks = [];
  5898. foreach ($mergeRows as $row) {
  5899. if (!is_array($row)) {
  5900. continue;
  5901. }
  5902. $sid = $this->extractScydgyRowId($row);
  5903. $detailId = 0;
  5904. if ($skipExisting) {
  5905. try {
  5906. $existsQuery = Db::table('purchase_order_detail')
  5907. ->where('scydgy_id', $sid)
  5908. ->where('company_name', $companyName);
  5909. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5910. $exists = $existsQuery->find();
  5911. } catch (\Throwable $e) {
  5912. $exists = null;
  5913. }
  5914. if (is_array($exists)) {
  5915. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5916. }
  5917. }
  5918. if ($detailId <= 0) {
  5919. $one = [
  5920. 'scydgy_id' => $toDb($sid),
  5921. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5922. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5923. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5924. 'username' => $username !== '' ? $username : null,
  5925. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5926. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5927. 'createtime' => date('Y-m-d H:i:s'),
  5928. 'status' => ProcuremenStatus::POD_UNPICKED,
  5929. 'status_name' => '未提交',
  5930. ];
  5931. Db::table('purchase_order_detail')->insert($one);
  5932. $detailId = (int)Db::getLastInsID();
  5933. }
  5934. $mprocUrl = '';
  5935. if ($buildMobileLinks && $detailId > 0) {
  5936. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5937. }
  5938. $detailLinks[] = [
  5939. 'detail_id' => $detailId,
  5940. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5941. 'url' => $mprocUrl,
  5942. ];
  5943. }
  5944. return $detailLinks;
  5945. }
  5946. /**
  5947. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5948. * @return array<string, mixed>
  5949. */
  5950. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5951. {
  5952. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5953. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5954. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5955. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5956. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5957. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5958. $isMerge = !empty($ctx['is_merge']);
  5959. $contactName = trim((string)($c['username'] ?? ''));
  5960. if ($contactName === '') {
  5961. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5962. }
  5963. $notifyVars = [
  5964. 'company_name' => $companyName,
  5965. 'contact_name' => $contactName,
  5966. 'phone' => $phone,
  5967. 'email' => $toEmail,
  5968. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5969. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5970. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5971. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5972. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5973. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5974. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5975. 'platform_url' => $platformUrl,
  5976. 'platform_links' => $platformLinksPlain,
  5977. 'platform_links_html' => $platformLinksHtml,
  5978. ];
  5979. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5980. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5981. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5982. return [
  5983. 'company_name' => $companyName,
  5984. 'phone' => $phone,
  5985. 'email' => $toEmail,
  5986. 'sms_content' => $smsContent,
  5987. 'mail_plain' => $mailPlain,
  5988. 'mail_body' => $mailBody,
  5989. 'notify_vars' => $notifyVars,
  5990. 'detail_links' => $detailLinks,
  5991. ];
  5992. }
  5993. /**
  5994. * @param array<string, mixed> $chosen
  5995. * @param array<int, array<string, mixed>> $mergeRows
  5996. * @param array{ccydh:string, pos:array} $bundle
  5997. */
  5998. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5999. {
  6000. if (!$sendSms && !$sendEmail) {
  6001. return;
  6002. }
  6003. $companyName = trim((string)($chosen['name'] ?? ''));
  6004. $phone = trim((string)($chosen['phone'] ?? ''));
  6005. $toEmail = trim((string)($chosen['email'] ?? ''));
  6006. if ($companyName === '') {
  6007. throw new \Exception('供应商名称无效');
  6008. }
  6009. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  6010. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  6011. }
  6012. if ($sendSms && $phone === '') {
  6013. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  6014. }
  6015. $sids = [];
  6016. foreach ($mergeRows as $mr) {
  6017. if (!is_array($mr)) {
  6018. continue;
  6019. }
  6020. $sid = $this->extractScydgyRowId($mr);
  6021. if ($this->isValidScydgyRowId($sid)) {
  6022. $sids[$sid] = true;
  6023. }
  6024. }
  6025. if ($sids === []) {
  6026. throw new \Exception('未找到工序行,无法发送通知');
  6027. }
  6028. $sysRqNotify = '';
  6029. $pos = $bundle['pos'] ?? [];
  6030. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6031. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  6032. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  6033. $ts = strtotime($sr);
  6034. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  6035. }
  6036. }
  6037. try {
  6038. $detailsQuery = Db::table('purchase_order_detail')
  6039. ->where('scydgy_id', 'in', array_keys($sids))
  6040. ->where('company_name', $companyName);
  6041. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6042. $details = $detailsQuery->order('id', 'asc')->select();
  6043. } catch (\Throwable $e) {
  6044. $details = [];
  6045. }
  6046. if (!is_array($details) || $details === []) {
  6047. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6048. try {
  6049. $detailsQuery = Db::table('purchase_order_detail')
  6050. ->where('scydgy_id', 'in', array_keys($sids))
  6051. ->where('company_name', $companyName);
  6052. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6053. $details = $detailsQuery->order('id', 'asc')->select();
  6054. } catch (\Throwable $e) {
  6055. $details = [];
  6056. }
  6057. }
  6058. if (!is_array($details) || $details === []) {
  6059. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6060. }
  6061. $detailLinks = [];
  6062. foreach ($details as $d) {
  6063. if (!is_array($d)) {
  6064. continue;
  6065. }
  6066. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6067. if ($detailId <= 0) {
  6068. continue;
  6069. }
  6070. $sid = (int)($d['scydgy_id'] ?? 0);
  6071. $gymc = '';
  6072. foreach ($mergeRows as $mr) {
  6073. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6074. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6075. break;
  6076. }
  6077. }
  6078. $detailLinks[] = [
  6079. 'detail_id' => $detailId,
  6080. 'cgymc' => $gymc,
  6081. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6082. ];
  6083. }
  6084. if ($detailLinks === []) {
  6085. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6086. }
  6087. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6088. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6089. $notifyBundle['email_log_scene'] = $emailLogScene;
  6090. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6091. $poIdLog = 0;
  6092. $pos = $bundle['pos'] ?? [];
  6093. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6094. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6095. }
  6096. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6097. if ($sendEmail) {
  6098. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6099. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6100. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6101. }
  6102. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6103. $mailConfig = $this->loadMailerConfig();
  6104. if (!$this->isProcuremenNotifyDryRun()) {
  6105. if (empty($mailConfig['host'])) {
  6106. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6107. }
  6108. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6109. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6110. }
  6111. }
  6112. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6113. }
  6114. if ($sendSms) {
  6115. $this->issueSendSupplierSms($notifyBundle);
  6116. }
  6117. }
  6118. /**
  6119. * @param array<int, array<string, mixed>> $quoteGroups
  6120. * @return array<int, array<string, mixed>>
  6121. */
  6122. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6123. {
  6124. $names = [];
  6125. if (is_string($companiesJson) && $companiesJson !== '') {
  6126. $decoded = json_decode($companiesJson, true);
  6127. if (is_array($decoded)) {
  6128. foreach ($decoded as $nm) {
  6129. $nm = trim((string)$nm);
  6130. if ($nm !== '') {
  6131. $names[] = $nm;
  6132. }
  6133. }
  6134. }
  6135. }
  6136. $names = array_values(array_unique($names));
  6137. if ($names === [] && $selectedCompany !== '') {
  6138. $names = [$selectedCompany];
  6139. }
  6140. if ($names === []) {
  6141. return $quoteGroups;
  6142. }
  6143. $targets = [];
  6144. foreach ($quoteGroups as $g) {
  6145. if (!is_array($g)) {
  6146. continue;
  6147. }
  6148. $cn = trim((string)($g['name'] ?? ''));
  6149. if ($cn !== '' && in_array($cn, $names, true)) {
  6150. $targets[] = $g;
  6151. }
  6152. }
  6153. return $targets;
  6154. }
  6155. /**
  6156. * @return array{pos:array, merge_rows:array, bundle:array}
  6157. */
  6158. protected function loadAuditResendBundle(string $scydgyId): array
  6159. {
  6160. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6161. $pos = $bundle['pos'];
  6162. $mergeRows = $bundle['merge_rows'];
  6163. if ($pos === [] || $mergeRows === []) {
  6164. $this->error('该订单不在待确认供应商状态');
  6165. }
  6166. $sysRqDb = '';
  6167. if (isset($pos[0]) && is_array($pos[0])) {
  6168. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6169. }
  6170. foreach ($pos as $i => $poRow) {
  6171. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6172. $pos[$i]['sys_rq'] = $sysRqDb;
  6173. }
  6174. }
  6175. $bundle['pos'] = $pos;
  6176. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6177. }
  6178. /**
  6179. * @param array<int, array<string, mixed>> $targets
  6180. */
  6181. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6182. {
  6183. if ($targets === []) {
  6184. $this->error('未找到可通知的供应商');
  6185. }
  6186. $notifyErrors = [];
  6187. try {
  6188. $this->notifyDryRunPreview = [];
  6189. foreach ($targets as $g) {
  6190. if (!is_array($g)) {
  6191. continue;
  6192. }
  6193. $cname = trim((string)($g['name'] ?? ''));
  6194. if ($cname === '') {
  6195. continue;
  6196. }
  6197. $chosen = [
  6198. 'name' => $cname,
  6199. 'company_name' => $cname,
  6200. 'email' => trim((string)($g['email'] ?? '')),
  6201. 'phone' => trim((string)($g['phone'] ?? '')),
  6202. 'username' => trim((string)($g['username'] ?? '')),
  6203. ];
  6204. try {
  6205. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6206. } catch (\Throwable $e) {
  6207. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6208. }
  6209. }
  6210. } catch (\Throwable $e) {
  6211. $this->error('通知发送失败:' . $e->getMessage());
  6212. }
  6213. if ($notifyErrors !== []) {
  6214. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6215. }
  6216. if ($this->isProcuremenNotifyDryRun()) {
  6217. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6218. 'notify_dry_run' => true,
  6219. 'notify_preview' => $this->notifyDryRunPreview,
  6220. ]);
  6221. }
  6222. $nameLabels = [];
  6223. foreach ($targets as $g) {
  6224. if (!is_array($g)) {
  6225. continue;
  6226. }
  6227. $n = trim((string)($g['name'] ?? ''));
  6228. if ($n !== '') {
  6229. $nameLabels[] = $n;
  6230. }
  6231. }
  6232. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6233. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6234. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6235. $seenLogSid = [];
  6236. foreach ($bundle['pos'] ?? [] as $poRow) {
  6237. if (!is_array($poRow)) {
  6238. continue;
  6239. }
  6240. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6241. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6242. continue;
  6243. }
  6244. $seenLogSid[$sid] = true;
  6245. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6246. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6247. }
  6248. if ($seenLogSid === []) {
  6249. foreach ($mergeRows as $mr) {
  6250. if (!is_array($mr)) {
  6251. continue;
  6252. }
  6253. $sid = $this->extractScydgyRowId($mr);
  6254. if ($this->isValidScydgyRowId($sid)) {
  6255. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6256. break;
  6257. }
  6258. }
  6259. }
  6260. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6261. }
  6262. /**
  6263. * 协助下发 — 发送短信(一家供应商)
  6264. *
  6265. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6266. */
  6267. protected function issueSendSupplierSms(array $bundle): void
  6268. {
  6269. $companyName = (string)($bundle['company_name'] ?? '');
  6270. $phone = (string)($bundle['phone'] ?? '');
  6271. $smsContent = (string)($bundle['sms_content'] ?? '');
  6272. $this->logIssueNotifyDebug('短信', [
  6273. 'company' => $companyName,
  6274. 'phone' => $phone,
  6275. 'sms_content' => $smsContent,
  6276. ]);
  6277. if ($this->isProcuremenNotifyDryRun()) {
  6278. $this->recordNotifyDryRunPreview([
  6279. 'scene' => 'issue_sms',
  6280. 'company_name' => $companyName,
  6281. 'phone' => $phone,
  6282. 'sms_content' => $smsContent,
  6283. ]);
  6284. return;
  6285. }
  6286. $this->smsbao($phone, $smsContent);
  6287. }
  6288. /**
  6289. * 协助下发 — 发送邮件(一家供应商)
  6290. *
  6291. * @param array<string, mixed> $bundle
  6292. * @param array<string, mixed> $mailConfig
  6293. */
  6294. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6295. {
  6296. $companyName = (string)($bundle['company_name'] ?? '');
  6297. $toEmail = (string)($bundle['email'] ?? '');
  6298. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6299. $mailBody = (string)($bundle['mail_body'] ?? '');
  6300. $this->logIssueNotifyDebug('邮件', [
  6301. 'company' => $companyName,
  6302. 'email' => $toEmail,
  6303. 'mail_subject' => $mailSubject,
  6304. 'mail_body' => $mailPlain,
  6305. ]);
  6306. if ($this->isProcuremenNotifyDryRun()) {
  6307. $this->recordNotifyDryRunPreview([
  6308. 'scene' => 'issue_email',
  6309. 'company_name' => $companyName,
  6310. 'email' => $toEmail,
  6311. 'mail_subject' => $mailSubject,
  6312. 'mail_body' => $mailPlain,
  6313. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6314. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6315. 'detail_links' => $bundle['detail_links'] ?? [],
  6316. ]);
  6317. return;
  6318. }
  6319. $mail = new PHPMailer(true);
  6320. $mail->isSMTP();
  6321. $mail->Host = $mailConfig['host'];
  6322. $mail->SMTPAuth = true;
  6323. $mail->Username = $mailConfig['addr'];
  6324. $mail->Password = $mailConfig['pass'];
  6325. $mail->SMTPSecure = $mailConfig['security'];
  6326. $mail->Port = $mailConfig['port'];
  6327. $mail->CharSet = $mailConfig['charset'];
  6328. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6329. $mail->addAddress($toEmail, $companyName);
  6330. $mail->isHTML(true);
  6331. $mail->Subject = $mailSubject;
  6332. $mail->Body = $mailBody;
  6333. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6334. $sendOk = true;
  6335. $failReason = '';
  6336. try {
  6337. $mail->send();
  6338. } catch (\Throwable $e) {
  6339. $sendOk = false;
  6340. $failReason = $e->getMessage();
  6341. $this->persistEmailSendLog([
  6342. 'from_email' => $fromEmail,
  6343. 'to_email' => $toEmail,
  6344. 'send_time' => date('Y-m-d H:i:s'),
  6345. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6346. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6347. 'company_name' => $companyName,
  6348. 'mail_subject' => $mailSubject,
  6349. 'status' => 0,
  6350. 'fail_reason' => $failReason,
  6351. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6352. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6353. ]);
  6354. throw $e;
  6355. }
  6356. $this->persistEmailSendLog([
  6357. 'from_email' => $fromEmail,
  6358. 'to_email' => $toEmail,
  6359. 'send_time' => date('Y-m-d H:i:s'),
  6360. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6361. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6362. 'company_name' => $companyName,
  6363. 'mail_subject' => $mailSubject,
  6364. 'status' => 1,
  6365. 'fail_reason' => '',
  6366. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6367. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6368. ]);
  6369. }
  6370. /**
  6371. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6372. *
  6373. * @param array<int, array<string, mixed>> $mergeRows
  6374. * @return array<string, mixed>
  6375. */
  6376. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6377. {
  6378. $head = $mergeRows[0] ?? [];
  6379. $isMerge = count($mergeRows) > 1;
  6380. return [
  6381. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6382. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6383. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6384. 'is_merge' => $isMerge,
  6385. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6386. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6387. 'deadline' => $sysRqNotify,
  6388. ];
  6389. }
  6390. /**
  6391. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6392. *
  6393. * @param array<string, mixed> $data
  6394. */
  6395. protected function logIssueNotifyDebug(string $type, array $data): void
  6396. {
  6397. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6398. return;
  6399. }
  6400. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6401. }
  6402. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6403. {
  6404. try {
  6405. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6406. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6407. return;
  6408. } catch (\Throwable $e) {
  6409. }
  6410. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6411. if (is_file($sqlFile)) {
  6412. $sql = file_get_contents($sqlFile);
  6413. if (is_string($sql) && $sql !== '') {
  6414. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6415. $stmt = trim($stmt);
  6416. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6417. continue;
  6418. }
  6419. try {
  6420. Db::execute($stmt);
  6421. } catch (\Throwable $ignore) {
  6422. }
  6423. }
  6424. }
  6425. }
  6426. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6427. }
  6428. /**
  6429. * @param array<string, mixed> $row
  6430. */
  6431. protected function persistEmailSendLog(array $row): void
  6432. {
  6433. try {
  6434. $this->ensurePurchaseEmailSendLogTableOnce();
  6435. } catch (\Throwable $e) {
  6436. return;
  6437. }
  6438. list($adminId, $adminName) = $this->GetUseName();
  6439. $cut = function ($s, $max) {
  6440. $s = (string)$s;
  6441. if (function_exists('mb_substr')) {
  6442. return mb_substr($s, 0, $max, 'UTF-8');
  6443. }
  6444. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6445. };
  6446. $data = [
  6447. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6448. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6449. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6450. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6451. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6452. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6453. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6454. 'status' => !empty($row['status']) ? 1 : 0,
  6455. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6456. 'admin_id' => (int)$adminId,
  6457. 'admin_name' => $cut($adminName, 64),
  6458. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6459. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6460. 'createtime' => date('Y-m-d H:i:s'),
  6461. ];
  6462. try {
  6463. Db::table('purchase_email_send_log')->insert($data);
  6464. } catch (\Throwable $e) {
  6465. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6466. }
  6467. }
  6468. protected function formatEmailLogSceneText(string $scene): string
  6469. {
  6470. $map = [
  6471. 'pick_issue' => '初选下发',
  6472. 'audit_resend' => '确认页重发',
  6473. ];
  6474. return $map[$scene] ?? $scene;
  6475. }
  6476. /**
  6477. * 邮件发送日志列表
  6478. */
  6479. public function emailLog()
  6480. {
  6481. $this->relationSearch = false;
  6482. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6483. $this->request->filter(['strip_tags', 'trim']);
  6484. $bakModel = $this->model;
  6485. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6486. if ($this->request->isAjax()) {
  6487. $this->ensurePurchaseEmailSendLogTableOnce();
  6488. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6489. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6490. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6491. $list = $this->model
  6492. ->where($where)
  6493. ->order($sortField, $orderDir)
  6494. ->paginate($limit);
  6495. $rows = [];
  6496. foreach ($list->items() as $item) {
  6497. $row = is_array($item) ? $item : $item->toArray();
  6498. $scene = trim((string)($row['scene'] ?? ''));
  6499. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6500. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6501. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6502. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6503. $rows[] = $row;
  6504. }
  6505. $this->model = $bakModel;
  6506. return json(['total' => $list->total(), 'rows' => $rows]);
  6507. }
  6508. $this->model = $bakModel;
  6509. return $this->view->fetch('procuremen/emaillog');
  6510. }
  6511. /**
  6512. * 协助下发弹窗(选多家供应商并通知)
  6513. */
  6514. public function pickReview()
  6515. {
  6516. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6517. $this->error(__('You have no permission'));
  6518. }
  6519. if ($this->request->isPost()) {
  6520. $this->error('请使用弹窗内「确认下发」提交');
  6521. }
  6522. $this->view->assign('pickMode', 1);
  6523. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6524. }
  6525. /**
  6526. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6527. */
  6528. public function add()
  6529. {
  6530. if ($this->request->isPost()) {
  6531. $params = $this->request->post('row/a');
  6532. if (!is_array($params)) {
  6533. $this->error(__('Parameter %s can not be empty', ''));
  6534. }
  6535. [, $adminName] = $this->GetUseName();
  6536. $params['cywyxm'] = $adminName;
  6537. try {
  6538. $sid = $this->saveManualPickOrder($params);
  6539. } catch (\InvalidArgumentException $e) {
  6540. $this->error($e->getMessage());
  6541. } catch (\Throwable $e) {
  6542. $this->error($e->getMessage());
  6543. }
  6544. $this->success('新增成功', '', [
  6545. 'scydgy_id' => $sid,
  6546. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6547. ]);
  6548. }
  6549. [, $adminName] = $this->GetUseName();
  6550. $this->view->assign('adminNickname', $adminName);
  6551. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6552. $this->view->assign('defaultCclbmmc', '营销中心');
  6553. return $this->view->fetch();
  6554. }
  6555. /**
  6556. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6557. */
  6558. public function rfqlist()
  6559. {
  6560. $this->relationSearch = false;
  6561. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6562. $this->request->filter(['strip_tags', 'trim']);
  6563. if ($this->request->isAjax()) {
  6564. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6565. $limit = max(10, min(500, (int)$limit));
  6566. $applyFilters = function ($query) use ($where) {
  6567. $query->where('scydgy_id', '<', 0);
  6568. $query->whereRaw(
  6569. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6570. );
  6571. if (!$this->auth->isSuperAdmin()) {
  6572. [, $adminName] = $this->GetUseName();
  6573. $query->where('cywyxm', $adminName);
  6574. }
  6575. if (!empty($where)) {
  6576. $query->where($where);
  6577. }
  6578. };
  6579. $countQuery = Db::table('purchase_order');
  6580. $applyFilters($countQuery);
  6581. $total = (int)$countQuery->count();
  6582. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6583. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6584. $listQuery = Db::table('purchase_order');
  6585. $applyFilters($listQuery);
  6586. $rows = $listQuery
  6587. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6588. ->order($sortField, $orderDir)
  6589. ->limit($offset, $limit)
  6590. ->select();
  6591. if (!is_array($rows)) {
  6592. $rows = [];
  6593. }
  6594. $out = [];
  6595. foreach ($rows as $r) {
  6596. if (!is_array($r)) {
  6597. continue;
  6598. }
  6599. $sid = (int)($r['scydgy_id'] ?? 0);
  6600. if ($sid >= 0) {
  6601. continue;
  6602. }
  6603. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6604. if ($createdText === '') {
  6605. $createdText = trim((string)($r['dStamp'] ?? ''));
  6606. }
  6607. $out[] = [
  6608. 'id' => (int)($r['id'] ?? 0),
  6609. 'scydgy_id' => $sid,
  6610. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6611. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6612. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6613. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6614. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6615. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6616. 'createtime' => $r['createtime'] ?? null,
  6617. 'createtime_text' => $createdText,
  6618. ];
  6619. }
  6620. return json(['total' => $total, 'rows' => $out]);
  6621. }
  6622. [, $adminName] = $this->GetUseName();
  6623. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6624. $this->view->assign('adminNickname', $adminName);
  6625. return $this->view->fetch('procuremen/rfqlist');
  6626. }
  6627. /**
  6628. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6629. */
  6630. public function rfqlistDetails()
  6631. {
  6632. return $this->details();
  6633. }
  6634. /**
  6635. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6636. */
  6637. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6638. {
  6639. if ($scydgyId >= 0) {
  6640. return;
  6641. }
  6642. try {
  6643. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6644. } catch (\Throwable $e) {
  6645. $po = null;
  6646. }
  6647. if (!is_array($po)) {
  6648. $this->error('订单不存在');
  6649. }
  6650. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6651. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6652. $this->error('订单不存在');
  6653. }
  6654. if ($this->auth->isSuperAdmin()) {
  6655. return;
  6656. }
  6657. [, $adminName] = $this->GetUseName();
  6658. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6659. if ($cywy !== '' && $cywy === $adminName) {
  6660. return;
  6661. }
  6662. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6663. try {
  6664. if ($this->auth->check($rule)) {
  6665. return;
  6666. }
  6667. } catch (\Throwable $e) {
  6668. }
  6669. }
  6670. $this->error('无权查看该订单');
  6671. }
  6672. /**
  6673. * 手工新增协助工序进度文案
  6674. */
  6675. protected function formatProcuremenRfqProgressText(array $row): string
  6676. {
  6677. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6678. return ProcuremenStatus::PO_COMPLETED;
  6679. }
  6680. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6681. return '待采购确认';
  6682. }
  6683. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6684. return '待确认供应商';
  6685. }
  6686. $sid = (int)($row['scydgy_id'] ?? 0);
  6687. if ($sid < 0) {
  6688. try {
  6689. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6690. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6691. $detCnt = (int)$detCntQuery->count();
  6692. if ($detCnt > 0) {
  6693. return '已下发待确认';
  6694. }
  6695. } catch (\Throwable $e) {
  6696. }
  6697. }
  6698. return '待协助下发';
  6699. }
  6700. /**
  6701. * 协助初选列表 — 批量软删除
  6702. */
  6703. public function pickDelete()
  6704. {
  6705. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6706. $this->error(__('Invalid parameters'));
  6707. }
  6708. if (!$this->procuremenCanPickDelete()) {
  6709. $this->error(__('You have no permission'));
  6710. }
  6711. $rowsRaw = $this->request->post('rows_json', '[]');
  6712. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6713. if (!is_array($rows) || $rows === []) {
  6714. $this->error('请至少勾选一条工序');
  6715. }
  6716. $done = 0;
  6717. Db::startTrans();
  6718. try {
  6719. foreach ($rows as $row) {
  6720. if (!is_array($row)) {
  6721. continue;
  6722. }
  6723. $this->softDeleteProcuremenPickRow($row);
  6724. $done++;
  6725. }
  6726. if ($done < 1) {
  6727. throw new \Exception('没有可删除的工序');
  6728. }
  6729. Db::commit();
  6730. } catch (\InvalidArgumentException $e) {
  6731. Db::rollback();
  6732. $this->error($e->getMessage());
  6733. } catch (\Throwable $e) {
  6734. Db::rollback();
  6735. $this->error($e->getMessage());
  6736. }
  6737. $this->pickHiddenScydgySetCache = null;
  6738. $this->success('已删除 ' . $done . ' 条工序');
  6739. }
  6740. /**
  6741. * 下发 — 手工新增工序(弹窗)
  6742. */
  6743. public function pickAdd()
  6744. {
  6745. if ($this->request->isPost()) {
  6746. $params = $this->request->post('row/a');
  6747. if (!is_array($params)) {
  6748. $this->error(__('Parameter %s can not be empty', ''));
  6749. }
  6750. try {
  6751. $sid = $this->saveManualPickOrder($params);
  6752. } catch (\InvalidArgumentException $e) {
  6753. $this->error($e->getMessage());
  6754. } catch (\Throwable $e) {
  6755. $this->error($e->getMessage());
  6756. }
  6757. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6758. }
  6759. return $this->view->fetch('procuremen/pick_add');
  6760. }
  6761. /**
  6762. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6763. */
  6764. public function pickSubmit()
  6765. {
  6766. if (!$this->request->isPost()) {
  6767. $this->error(__('Invalid parameters'));
  6768. }
  6769. // ---------- 接口订单数据 ----------
  6770. $rowJson = $this->request->post('row_json', '');
  6771. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6772. $companiesJson = $this->request->post('companies_json', '[]');
  6773. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6774. $companies = json_decode($companiesJson, true);
  6775. if (!is_array($companies)) {
  6776. $this->error('供应商数据无效');
  6777. }
  6778. $issueCompanies = $this->normalizePickCompanies($companies);
  6779. if ($issueCompanies === []) {
  6780. $this->error('请至少选择一家合作供应商');
  6781. }
  6782. $issueNameLabels = [];
  6783. foreach ($issueCompanies as $pc) {
  6784. $issueNameLabels[] = $pc['name'];
  6785. }
  6786. $issueNamesSummary = implode('、', $issueNameLabels);
  6787. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6788. if ($sysRq === '') {
  6789. $this->error('请选择招标截止日期');
  6790. }
  6791. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  6792. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  6793. (string)$this->request->post('delivery_deadline', ''),
  6794. true
  6795. );
  6796. $isMerge = count($mergeRows) > 1;
  6797. $ccydhLog = '';
  6798. foreach ($mergeRows as $row) {
  6799. if (!is_array($row)) {
  6800. continue;
  6801. }
  6802. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6803. if ($ccydhLog !== '') {
  6804. break;
  6805. }
  6806. }
  6807. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6808. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6809. $logMsg = '下发' . $orderPart . $procPart
  6810. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6811. $issueTime = date('Y-m-d H:i:s');
  6812. $logSidList = [];
  6813. foreach ($mergeRows as $row) {
  6814. if (!is_array($row)) {
  6815. continue;
  6816. }
  6817. $sid = $this->extractScydgyRowId($row);
  6818. if ($this->isValidScydgyRowId($sid)) {
  6819. $logSidList[$sid] = true;
  6820. }
  6821. }
  6822. $existingBySid = [];
  6823. if ($logSidList !== []) {
  6824. try {
  6825. $existingRows = Db::table('purchase_order')
  6826. ->where('scydgy_id', 'in', array_keys($logSidList))
  6827. ->select();
  6828. if (is_array($existingRows)) {
  6829. foreach ($existingRows as $poRow) {
  6830. if (!is_array($poRow)) {
  6831. continue;
  6832. }
  6833. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6834. if ($this->isValidScydgyRowId($sid)) {
  6835. $existingBySid[$sid] = $poRow;
  6836. }
  6837. }
  6838. }
  6839. } catch (\Throwable $e) {
  6840. $existingBySid = [];
  6841. }
  6842. }
  6843. Db::startTrans();
  6844. try {
  6845. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6846. foreach ($mergeRows as $row) {
  6847. if (!is_array($row)) {
  6848. continue;
  6849. }
  6850. $sid = $this->extractScydgyRowId($row);
  6851. $this->upsertPurchaseOrderFromRow(
  6852. $row,
  6853. $sysRqDb,
  6854. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6855. $issueTime,
  6856. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  6857. $deliveryDeadlineDb
  6858. );
  6859. }
  6860. foreach ($issueCompanies as $c) {
  6861. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6862. }
  6863. Db::commit();
  6864. } catch (\Throwable $e) {
  6865. Db::rollback();
  6866. $this->error($e->getMessage());
  6867. }
  6868. $poIdBySid = [];
  6869. if ($logSidList !== []) {
  6870. try {
  6871. $poIdBySid = Db::table('purchase_order')
  6872. ->where('scydgy_id', 'in', array_keys($logSidList))
  6873. ->column('id', 'scydgy_id');
  6874. } catch (\Throwable $e) {
  6875. $poIdBySid = [];
  6876. }
  6877. }
  6878. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6879. if ($logSidList !== []) {
  6880. list($adminId, $adminName) = $this->GetUseName();
  6881. $logRows = [];
  6882. $seenLogSid = [];
  6883. foreach ($mergeRows as $row) {
  6884. if (!is_array($row)) {
  6885. continue;
  6886. }
  6887. $ids = $this->extractScydgyRowId($row);
  6888. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6889. continue;
  6890. }
  6891. $seenLogSid[$ids] = true;
  6892. $poIdLog = null;
  6893. if (isset($poIdBySid[$ids])) {
  6894. $tid = (int)$poIdBySid[$ids];
  6895. $poIdLog = $tid > 0 ? $tid : null;
  6896. }
  6897. $logRows[] = ProcuremenOperLog::buildInsertRow(
  6898. $ids,
  6899. 'issue_submit',
  6900. $logMsg,
  6901. $poIdLog,
  6902. (int)$adminId,
  6903. (string)$adminName
  6904. );
  6905. }
  6906. if ($logRows !== []) {
  6907. try {
  6908. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6909. } catch (\Throwable $e) {
  6910. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6911. }
  6912. }
  6913. }
  6914. $notifyErrors = [];
  6915. $posNotify = [];
  6916. if ($logSidList !== []) {
  6917. try {
  6918. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6919. } catch (\Throwable $e) {
  6920. $posNotify = [];
  6921. }
  6922. }
  6923. if (!is_array($posNotify)) {
  6924. $posNotify = [];
  6925. }
  6926. foreach ($posNotify as $i => $prow) {
  6927. if (is_array($posNotify[$i])) {
  6928. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6929. }
  6930. }
  6931. $ccydhPick = '';
  6932. foreach ($mergeRows as $row) {
  6933. if (!is_array($row)) {
  6934. continue;
  6935. }
  6936. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6937. if ($ccydhPick !== '') {
  6938. break;
  6939. }
  6940. }
  6941. $notifyBundleBase = [
  6942. 'ccydh' => $ccydhPick,
  6943. 'pos' => $posNotify,
  6944. 'merge_rows' => $mergeRows,
  6945. ];
  6946. try {
  6947. $this->notifyDryRunPreview = [];
  6948. foreach ($issueCompanies as $c) {
  6949. if (!is_array($c)) {
  6950. continue;
  6951. }
  6952. $cname = trim((string)($c['name'] ?? ''));
  6953. if ($cname === '') {
  6954. continue;
  6955. }
  6956. try {
  6957. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6958. } catch (\Throwable $e) {
  6959. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6960. }
  6961. }
  6962. } catch (\Throwable $e) {
  6963. $this->error('通知发送失败:' . $e->getMessage());
  6964. }
  6965. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6966. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6967. }
  6968. if ($this->isProcuremenNotifyDryRun()) {
  6969. $this->success('【演练模式】已保存并生成通知预览', '', [
  6970. 'notify_dry_run' => true,
  6971. 'notify_preview' => $this->notifyDryRunPreview,
  6972. ]);
  6973. }
  6974. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6975. }
  6976. /**
  6977. * 确认供应商弹窗
  6978. */
  6979. public function auditIssue()
  6980. {
  6981. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6982. if (is_array($ids)) {
  6983. $ids = isset($ids[0]) ? $ids[0] : '';
  6984. }
  6985. $ids = trim((string)$ids);
  6986. if ($ids === '') {
  6987. $this->error(__('Invalid parameters'));
  6988. }
  6989. if ($this->request->isPost()) {
  6990. $this->error('请使用弹窗内「确认」提交');
  6991. }
  6992. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6993. $pos = $bundle['pos'];
  6994. if ($pos === []) {
  6995. $this->error('该订单不在待确认供应商状态');
  6996. }
  6997. $po = $pos[0];
  6998. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6999. if ($quoteGroups === []) {
  7000. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  7001. }
  7002. $pickedName = '';
  7003. foreach ($pos as $poRow) {
  7004. if (!is_array($poRow)) {
  7005. continue;
  7006. }
  7007. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7008. if ($pn !== '') {
  7009. $pickedName = $pn;
  7010. break;
  7011. }
  7012. }
  7013. $this->view->assign('po', $po);
  7014. $this->view->assign('scydgyId', $ids);
  7015. $this->view->assign('orderCcydh', $bundle['ccydh']);
  7016. $mergeRows = $bundle['merge_rows'];
  7017. $this->view->assign('processRows', $mergeRows);
  7018. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  7019. $this->view->assign('processCount', count($mergeRows));
  7020. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  7021. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  7022. $this->view->assign('pickedCompanyName', $pickedName);
  7023. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7024. if ($sysRqForView === '') {
  7025. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7026. }
  7027. $this->view->assign('sysRq', $sysRqForView);
  7028. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  7029. if ($deliveryDeadlineForView === '') {
  7030. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7031. }
  7032. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7033. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  7034. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  7035. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  7036. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  7037. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  7038. return $this->view->fetch('procuremen/audit_issue');
  7039. }
  7040. /**
  7041. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7042. *
  7043. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7044. */
  7045. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7046. {
  7047. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7048. }
  7049. /**
  7050. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7051. *
  7052. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7053. */
  7054. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7055. {
  7056. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7057. return false;
  7058. }
  7059. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7060. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7061. return true;
  7062. }
  7063. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7064. }
  7065. /**
  7066. * 确认页 — 补加供应商弹窗
  7067. */
  7068. public function auditAppend()
  7069. {
  7070. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7071. $this->error(__('You have no permission'));
  7072. }
  7073. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7074. if (is_array($ids)) {
  7075. $ids = isset($ids[0]) ? $ids[0] : '';
  7076. }
  7077. $ids = trim((string)$ids);
  7078. if ($ids === '') {
  7079. $this->error(__('Invalid parameters'));
  7080. }
  7081. if ($this->request->isPost()) {
  7082. $this->error('请使用弹窗内「确认」提交');
  7083. }
  7084. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7085. if (($bundle['pos'] ?? []) === []) {
  7086. $this->error('该订单不在待确认供应商状态');
  7087. }
  7088. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7089. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7090. $this->error('已开标验证,不能再补加供应商');
  7091. }
  7092. $this->error('已经超过了招标截止日期,不可操作');
  7093. }
  7094. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7095. $existingNames = [];
  7096. foreach ($quoteGroups as $g) {
  7097. if (!is_array($g)) {
  7098. continue;
  7099. }
  7100. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7101. if ($n !== '') {
  7102. $existingNames[$n] = true;
  7103. }
  7104. }
  7105. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7106. $mergeRows = $bundle['merge_rows'] ?? [];
  7107. $this->view->assign('scydgyId', $ids);
  7108. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7109. $this->view->assign('po', $po);
  7110. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7111. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7112. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7113. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7114. if ($sysRqForView === '') {
  7115. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7116. }
  7117. $this->view->assign('sysRq', $sysRqForView);
  7118. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7119. if ($deliveryDeadlineForView === '') {
  7120. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7121. }
  7122. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7123. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7124. }
  7125. /**
  7126. * 确认页 — 补加供应商提交
  7127. */
  7128. public function auditAppendSubmit()
  7129. {
  7130. if (!$this->request->isPost()) {
  7131. $this->error(__('Invalid parameters'));
  7132. }
  7133. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7134. $this->error(__('You have no permission'));
  7135. }
  7136. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7137. if ($ids === '') {
  7138. $this->error(__('Invalid parameters'));
  7139. }
  7140. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7141. if (($bundle['pos'] ?? []) === []) {
  7142. $this->error('该订单不在待确认供应商状态');
  7143. }
  7144. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7145. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7146. $this->error('已开标验证,不能再补加供应商');
  7147. }
  7148. $this->error('已经超过了招标截止日期,不可操作');
  7149. }
  7150. $companiesJson = $this->request->post('companies_json', '[]');
  7151. $companies = json_decode((string)$companiesJson, true);
  7152. if (!is_array($companies)) {
  7153. $this->error('供应商数据无效');
  7154. }
  7155. $issueCompanies = $this->normalizePickCompanies($companies);
  7156. if ($issueCompanies === []) {
  7157. $this->error('请至少选择一家合作供应商');
  7158. }
  7159. $mergeRows = $bundle['merge_rows'] ?? [];
  7160. if (!is_array($mergeRows) || $mergeRows === []) {
  7161. $this->error('未找到工序行,无法补加');
  7162. }
  7163. $existingNames = [];
  7164. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7165. if (!is_array($g)) {
  7166. continue;
  7167. }
  7168. $n = trim((string)($g['company_name'] ?? ''));
  7169. if ($n !== '') {
  7170. $existingNames[$n] = true;
  7171. }
  7172. }
  7173. $toAdd = [];
  7174. foreach ($issueCompanies as $c) {
  7175. if (!is_array($c)) {
  7176. continue;
  7177. }
  7178. $n = trim((string)($c['name'] ?? ''));
  7179. if ($n === '' || isset($existingNames[$n])) {
  7180. continue;
  7181. }
  7182. $toAdd[] = $c;
  7183. }
  7184. if ($toAdd === []) {
  7185. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7186. }
  7187. $addedNames = [];
  7188. Db::startTrans();
  7189. try {
  7190. foreach ($toAdd as $c) {
  7191. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7192. $addedNames[] = trim((string)($c['name'] ?? ''));
  7193. }
  7194. Db::commit();
  7195. } catch (\Throwable $e) {
  7196. Db::rollback();
  7197. $this->error($e->getMessage());
  7198. }
  7199. $notifyErrors = [];
  7200. $notifyBundleBase = [
  7201. 'ccydh' => $bundle['ccydh'] ?? '',
  7202. 'pos' => $bundle['pos'] ?? [],
  7203. 'merge_rows' => $mergeRows,
  7204. ];
  7205. foreach ($toAdd as $c) {
  7206. if (!is_array($c)) {
  7207. continue;
  7208. }
  7209. $cname = trim((string)($c['name'] ?? ''));
  7210. if ($cname === '') {
  7211. continue;
  7212. }
  7213. try {
  7214. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7215. } catch (\Throwable $e) {
  7216. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7217. }
  7218. }
  7219. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7220. $seenLogSid = [];
  7221. foreach ($bundle['pos'] ?? [] as $poRow) {
  7222. if (!is_array($poRow)) {
  7223. continue;
  7224. }
  7225. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7226. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7227. continue;
  7228. }
  7229. $seenLogSid[$sid] = true;
  7230. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7231. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7232. }
  7233. if ($seenLogSid === []) {
  7234. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7235. if ($this->isValidScydgyRowId($logSid)) {
  7236. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7237. }
  7238. }
  7239. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7240. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7241. }
  7242. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7243. }
  7244. /**
  7245. * 开标双重验证 — 可选验证人列表
  7246. */
  7247. public function bidOpenUsers()
  7248. {
  7249. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7250. $this->error('无权限');
  7251. }
  7252. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7253. if ($scydgyId !== '') {
  7254. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7255. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7256. $this->success('已完成开标验证', null, [
  7257. 'verified' => 1,
  7258. 'users' => [],
  7259. ]);
  7260. }
  7261. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7262. }
  7263. $this->success('', null, [
  7264. 'verified' => 0,
  7265. 'users' => $this->listBidOpenVerifierCandidates(),
  7266. ]);
  7267. }
  7268. /**
  7269. * 开标双重验证 — 向指定管理员发送短信验证码
  7270. */
  7271. public function bidOpenSendCode()
  7272. {
  7273. if (!$this->request->isPost()) {
  7274. $this->error(__('Invalid parameters'));
  7275. }
  7276. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7277. $this->error('无权限');
  7278. }
  7279. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7280. $adminId = (int)$this->request->post('admin_id', 0);
  7281. if ($scydgyId === '' || $adminId <= 0) {
  7282. $this->error('参数无效');
  7283. }
  7284. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7285. if ($bundle['pos'] === []) {
  7286. $this->error('该订单不在待确认供应商状态');
  7287. }
  7288. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7289. $this->success('已完成开标验证,无需重复发送');
  7290. }
  7291. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7292. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7293. if ($ccydh === '') {
  7294. $this->error('订单号无效');
  7295. }
  7296. $admin = $this->loadBidOpenAdminUser($adminId);
  7297. if ($admin === null) {
  7298. $this->error('验证人无效或未绑定手机号');
  7299. }
  7300. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7301. $cd = max(30, min(120, $cd));
  7302. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7303. $this->error('发送过于频繁,请稍后再试');
  7304. }
  7305. $code = (string)random_int(100000, 999999);
  7306. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7307. $ttl = max(60, min(600, $ttl));
  7308. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7309. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7310. try {
  7311. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7312. } catch (\Throwable $e) {
  7313. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7314. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7315. $this->error($e->getMessage());
  7316. }
  7317. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7318. }
  7319. /**
  7320. * 开标双重验证 — 两人验证码校验并记录
  7321. */
  7322. public function bidOpenVerify()
  7323. {
  7324. if (!$this->request->isPost()) {
  7325. $this->error(__('Invalid parameters'));
  7326. }
  7327. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7328. $this->error('无权限');
  7329. }
  7330. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7331. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7332. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7333. $code1 = trim((string)$this->request->post('code1', ''));
  7334. $code2 = trim((string)$this->request->post('code2', ''));
  7335. if ($scydgyId === '') {
  7336. $this->error('参数无效');
  7337. }
  7338. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7339. $this->error('请选择两位验证人');
  7340. }
  7341. if ($verifier1Id === $verifier2Id) {
  7342. $this->error('两位验证人不能相同');
  7343. }
  7344. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7345. $this->error('请输入6位短信验证码');
  7346. }
  7347. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7348. if ($bundle['pos'] === []) {
  7349. $this->error('该订单不在待确认供应商状态');
  7350. }
  7351. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7352. if ($ccydh === '') {
  7353. $this->error('订单号无效');
  7354. }
  7355. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7356. $this->success('已完成开标验证');
  7357. }
  7358. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7359. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7360. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7361. if ($verifier1 === null || $verifier2 === null) {
  7362. $this->error('验证人无效或未绑定手机号');
  7363. }
  7364. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7365. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7366. }
  7367. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7368. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7369. }
  7370. try {
  7371. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7372. } catch (\Throwable $e) {
  7373. $this->error($e->getMessage());
  7374. }
  7375. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7376. }
  7377. /**
  7378. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7379. */
  7380. public function auditSubmit()
  7381. {
  7382. if (!$this->request->isPost()) {
  7383. $this->error(__('Invalid parameters'));
  7384. }
  7385. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7386. if ($scydgyId === '') {
  7387. $this->error('参数无效');
  7388. }
  7389. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7390. $pos = $bundle['pos'];
  7391. $mergeRows = $bundle['merge_rows'];
  7392. if ($pos === [] || $mergeRows === []) {
  7393. $this->error('该订单不在待确认供应商状态');
  7394. }
  7395. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7396. if ($quoteGroups === []) {
  7397. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7398. }
  7399. $companyName = trim((string)$this->request->post('selected_company', ''));
  7400. if ($companyName === '') {
  7401. $this->error('请选择一家供应商');
  7402. }
  7403. $matched = null;
  7404. foreach ($quoteGroups as $g) {
  7405. if (!is_array($g)) {
  7406. continue;
  7407. }
  7408. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7409. $matched = $g;
  7410. break;
  7411. }
  7412. }
  7413. if ($matched === null) {
  7414. $this->error('所选供应商不在本单报价列表中');
  7415. }
  7416. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7417. if ($sysRqDb === '') {
  7418. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  7419. } else {
  7420. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  7421. }
  7422. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7423. $this->error('请先完成开标双重验证后再确认供应商');
  7424. }
  7425. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7426. $procCnt = count($mergeRows);
  7427. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7428. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7429. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  7430. Db::startTrans();
  7431. try {
  7432. foreach ($pos as $poRow) {
  7433. if (!is_array($poRow)) {
  7434. continue;
  7435. }
  7436. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7437. if (!$this->isValidScydgyRowId($sid)) {
  7438. continue;
  7439. }
  7440. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7441. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7442. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7443. 'pick_company_name' => $companyName,
  7444. 'sys_rq' => $sysRqDb,
  7445. ]);
  7446. }
  7447. Db::commit();
  7448. } catch (\Throwable $e) {
  7449. Db::rollback();
  7450. $this->error($e->getMessage());
  7451. }
  7452. foreach ($pos as $poRow) {
  7453. if (!is_array($poRow)) {
  7454. continue;
  7455. }
  7456. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7457. if (!$this->isValidScydgyRowId($sid)) {
  7458. continue;
  7459. }
  7460. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7461. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7462. }
  7463. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7464. }
  7465. /**
  7466. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7467. */
  7468. public function auditResendSms()
  7469. {
  7470. if (!$this->request->isPost()) {
  7471. $this->error(__('Invalid parameters'));
  7472. }
  7473. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7474. if ($scydgyId === '') {
  7475. $this->error('参数无效');
  7476. }
  7477. $loaded = $this->loadAuditResendBundle($scydgyId);
  7478. $mergeRows = $loaded['merge_rows'];
  7479. $bundle = $loaded['bundle'];
  7480. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7481. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7482. if ($quoteGroups === []) {
  7483. $this->error('暂无可通知的供应商');
  7484. }
  7485. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7486. $companiesJson = (string)$this->request->post('companies_json', '');
  7487. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7488. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7489. }
  7490. /**
  7491. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7492. */
  7493. public function auditResendEmail()
  7494. {
  7495. if (!$this->request->isPost()) {
  7496. $this->error(__('Invalid parameters'));
  7497. }
  7498. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7499. if ($scydgyId === '') {
  7500. $this->error('参数无效');
  7501. }
  7502. $loaded = $this->loadAuditResendBundle($scydgyId);
  7503. $mergeRows = $loaded['merge_rows'];
  7504. $bundle = $loaded['bundle'];
  7505. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7506. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7507. if ($quoteGroups === []) {
  7508. $this->error('暂无可通知的供应商');
  7509. }
  7510. $companiesJson = (string)$this->request->post('companies_json', '');
  7511. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7512. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7513. if ($companiesJson === '' && $selectedCompany === '') {
  7514. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7515. }
  7516. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7517. }
  7518. /**
  7519. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7520. *
  7521. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7522. * @return array<int, true> 已处理的 scydgy_id 集合
  7523. */
  7524. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7525. {
  7526. $pos = $bundle['pos'] ?? [];
  7527. if (!is_array($pos) || $pos === []) {
  7528. return [];
  7529. }
  7530. $sids = [];
  7531. foreach ($pos as $poRow) {
  7532. if (!is_array($poRow)) {
  7533. continue;
  7534. }
  7535. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7536. if ($this->isValidScydgyRowId($sid)) {
  7537. $sids[$sid] = true;
  7538. }
  7539. }
  7540. if ($sids === []) {
  7541. return [];
  7542. }
  7543. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7544. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7545. $suffix = trim((string)$logSuffix, ',, ');
  7546. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7547. $logMsg .= ':从历史存证退回协助初选';
  7548. } else {
  7549. $logMsg .= ':退回协助初选';
  7550. }
  7551. Db::table('purchase_order')
  7552. ->where('scydgy_id', 'in', array_keys($sids))
  7553. ->update([
  7554. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7555. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7556. 'pick_company_name' => '',
  7557. 'pick_time' => null,
  7558. 'sys_rq' => null,
  7559. 'mod_rq' => null,
  7560. ]);
  7561. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7562. foreach (array_keys($sids) as $sid) {
  7563. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7564. }
  7565. return $sids;
  7566. }
  7567. /**
  7568. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7569. *
  7570. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7571. */
  7572. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7573. {
  7574. $scydgyId = trim($scydgyId);
  7575. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7576. if ($scydgyId === '') {
  7577. return $empty;
  7578. }
  7579. try {
  7580. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7581. } catch (\Throwable $e) {
  7582. $anchor = null;
  7583. }
  7584. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7585. return $empty;
  7586. }
  7587. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7588. if ($ccydh === '') {
  7589. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7590. }
  7591. try {
  7592. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7593. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7594. $pos = $query->order('scydgy_id', 'asc')->select();
  7595. } catch (\Throwable $e) {
  7596. $pos = [$anchor];
  7597. }
  7598. if (!is_array($pos) || $pos === []) {
  7599. $pos = [$anchor];
  7600. }
  7601. return [
  7602. 'ccydh' => $ccydh,
  7603. 'pos' => $pos,
  7604. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7605. ];
  7606. }
  7607. protected function purchaseOrderRowIsCompleted(array $po): bool
  7608. {
  7609. $st = $po['status'] ?? null;
  7610. if ($st === 1 || $st === '1') {
  7611. return true;
  7612. }
  7613. if (is_string($st) && trim($st) === '1') {
  7614. return true;
  7615. }
  7616. return is_numeric($st) && (int)$st === 1;
  7617. }
  7618. /**
  7619. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7620. */
  7621. public function auditAbandon()
  7622. {
  7623. if (!$this->request->isPost()) {
  7624. $this->error(__('Invalid parameters'));
  7625. }
  7626. $anchorIds = [];
  7627. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7628. if ($batchRaw !== '') {
  7629. $decoded = json_decode($batchRaw, true);
  7630. if (is_array($decoded)) {
  7631. foreach ($decoded as $id) {
  7632. $s = trim((string)$id);
  7633. if ($s !== '') {
  7634. $anchorIds[] = $s;
  7635. }
  7636. }
  7637. }
  7638. }
  7639. if ($anchorIds === []) {
  7640. $single = trim((string)$this->request->post('scydgy_id', ''));
  7641. if ($single !== '') {
  7642. $anchorIds[] = $single;
  7643. }
  7644. }
  7645. if ($anchorIds === []) {
  7646. $this->error('请至少选择一条订单');
  7647. }
  7648. $processedCcydh = [];
  7649. $doneOrders = 0;
  7650. $allSids = [];
  7651. Db::startTrans();
  7652. try {
  7653. foreach ($anchorIds as $anchorId) {
  7654. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7655. if (($bundle['pos'] ?? []) === []) {
  7656. continue;
  7657. }
  7658. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7659. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7660. if (isset($processedCcydh[$dedupeKey])) {
  7661. continue;
  7662. }
  7663. $processedCcydh[$dedupeKey] = true;
  7664. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7665. if ($sids === []) {
  7666. continue;
  7667. }
  7668. $doneOrders++;
  7669. foreach (array_keys($sids) as $sid) {
  7670. $allSids[(int)$sid] = true;
  7671. }
  7672. }
  7673. if ($doneOrders < 1) {
  7674. throw new \Exception('所选订单均不在待确认供应商状态');
  7675. }
  7676. Db::commit();
  7677. } catch (\Throwable $e) {
  7678. Db::rollback();
  7679. $this->error($e->getMessage());
  7680. }
  7681. $this->pickHiddenScydgySetCache = null;
  7682. $msg = $doneOrders > 1
  7683. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7684. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7685. $this->success($msg);
  7686. }
  7687. /**
  7688. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7689. */
  7690. public function archiveAbandon()
  7691. {
  7692. if (!$this->request->isPost()) {
  7693. $this->error(__('Invalid parameters'));
  7694. }
  7695. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7696. $this->error(__('You have no permission'));
  7697. }
  7698. $anchorIds = [];
  7699. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7700. if ($batchRaw !== '') {
  7701. $decoded = json_decode($batchRaw, true);
  7702. if (is_array($decoded)) {
  7703. foreach ($decoded as $id) {
  7704. $s = trim((string)$id);
  7705. if ($s !== '') {
  7706. $anchorIds[] = $s;
  7707. }
  7708. }
  7709. }
  7710. }
  7711. if ($anchorIds === []) {
  7712. $single = trim((string)$this->request->post('scydgy_id', ''));
  7713. if ($single !== '') {
  7714. $anchorIds[] = $single;
  7715. }
  7716. }
  7717. if ($anchorIds === []) {
  7718. $this->error('请至少选择一条订单');
  7719. }
  7720. $processedCcydh = [];
  7721. $doneOrders = 0;
  7722. Db::startTrans();
  7723. try {
  7724. foreach ($anchorIds as $anchorId) {
  7725. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7726. if (($bundle['pos'] ?? []) === []) {
  7727. continue;
  7728. }
  7729. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7730. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7731. if (isset($processedCcydh[$dedupeKey])) {
  7732. continue;
  7733. }
  7734. $processedCcydh[$dedupeKey] = true;
  7735. $sids = $this->abandonOrderBundleToPick(
  7736. $bundle,
  7737. 'archive_abandon',
  7738. ',从历史存证退回协助初选'
  7739. );
  7740. if ($sids === []) {
  7741. continue;
  7742. }
  7743. $doneOrders++;
  7744. }
  7745. if ($doneOrders < 1) {
  7746. throw new \Exception('所选订单均不是已完结状态');
  7747. }
  7748. Db::commit();
  7749. } catch (\Throwable $e) {
  7750. Db::rollback();
  7751. $this->error($e->getMessage());
  7752. }
  7753. $this->pickHiddenScydgySetCache = null;
  7754. $msg = $doneOrders > 1
  7755. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7756. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7757. $this->success($msg);
  7758. }
  7759. /**
  7760. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7761. */
  7762. public function purchaseApprovalReject()
  7763. {
  7764. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7765. $this->error(__('Invalid parameters'));
  7766. }
  7767. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7768. $this->error(__('You have no permission'));
  7769. }
  7770. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7771. $decoded = json_decode($batchRaw, true);
  7772. if (!is_array($decoded) || $decoded === []) {
  7773. $this->error('提交数据无效');
  7774. }
  7775. $done = 0;
  7776. Db::startTrans();
  7777. try {
  7778. foreach ($decoded as $item) {
  7779. if (!is_array($item)) {
  7780. continue;
  7781. }
  7782. $sid = (int)($item['scydgy_id'] ?? 0);
  7783. if (!$this->isValidScydgyRowId($sid)) {
  7784. continue;
  7785. }
  7786. $this->runPurchaseApprovalRejectForSid($sid);
  7787. $done++;
  7788. }
  7789. if ($done < 1) {
  7790. throw new \Exception('所选订单均不在待审批状态');
  7791. }
  7792. Db::commit();
  7793. } catch (\Throwable $e) {
  7794. Db::rollback();
  7795. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7796. }
  7797. $this->pickHiddenScydgySetCache = null;
  7798. $this->success('已驳回并退回「协助审批下发」');
  7799. }
  7800. /**
  7801. * @throws \Exception
  7802. */
  7803. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7804. {
  7805. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7806. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7807. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7808. $allIds = $this->purchaseOrderDetail($sid);
  7809. if ($allIds === []) {
  7810. throw new \Exception('未找到下发明细');
  7811. }
  7812. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7813. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7814. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7815. 'pick_company_name' => '',
  7816. ]);
  7817. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7818. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7819. $poId = 0;
  7820. try {
  7821. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7822. if (is_array($po)) {
  7823. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7824. }
  7825. } catch (\Throwable $e) {
  7826. }
  7827. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7828. }
  7829. /**
  7830. * 审核弹窗(旧入口,POST 已关闭)
  7831. */
  7832. public function review()
  7833. {
  7834. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7835. $this->error(__('You have no permission'));
  7836. }
  7837. if ($this->request->isPost()) {
  7838. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7839. }
  7840. $this->view->assign('pickMode', 0);
  7841. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  7842. }
  7843. /**
  7844. * 审核弹窗获取公司列表
  7845. */
  7846. public function reviewCompanies()
  7847. {
  7848. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  7849. $this->error(__('You have no permission'));
  7850. }
  7851. if (!$this->request->isAjax()) {
  7852. $this->error(__('Invalid parameters'));
  7853. }
  7854. $list = [];
  7855. try {
  7856. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7857. $rows = Db::table('customer')
  7858. ->where(function ($q) {
  7859. $q->where('status', 1)
  7860. ->whereOr('status', '1')
  7861. ->whereOr('status', '')
  7862. ->whereNull('status');
  7863. })
  7864. ->order('id', 'desc')
  7865. ->select();
  7866. } catch (\Throwable $e) {
  7867. $this->success('', '', []);
  7868. return;
  7869. }
  7870. if (!is_array($rows)) {
  7871. $this->success('', '', []);
  7872. return;
  7873. }
  7874. $detailColCandidates = [
  7875. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7876. 'company_detail', 'company_desc', 'address',
  7877. ];
  7878. foreach ($rows as $row) {
  7879. if (!is_array($row)) {
  7880. continue;
  7881. }
  7882. $norm = [];
  7883. foreach ($row as $k => $v) {
  7884. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7885. }
  7886. $row = $norm;
  7887. $st = $row['status'] ?? '';
  7888. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7889. continue;
  7890. }
  7891. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7892. if ($payload === null) {
  7893. continue;
  7894. }
  7895. $detail = '';
  7896. foreach ($detailColCandidates as $dk) {
  7897. if (!isset($row[$dk])) {
  7898. continue;
  7899. }
  7900. $dv = trim((string)$row[$dk]);
  7901. if ($dv !== '') {
  7902. $detail = $dv;
  7903. break;
  7904. }
  7905. }
  7906. $payload['detail'] = $detail;
  7907. $list[] = $this->maskSupplierContactFields($payload);
  7908. }
  7909. $this->success('', '', $list);
  7910. }
  7911. /**
  7912. * 采购确认-下发明细弹窗:
  7913. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7914. */
  7915. public function outward_detail()
  7916. {
  7917. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7918. if (is_array($ids)) {
  7919. $ids = isset($ids[0]) ? $ids[0] : '';
  7920. }
  7921. $ids = trim((string)$ids);
  7922. if ($ids === '') {
  7923. $this->error(__('Invalid parameters'));
  7924. }
  7925. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7926. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7927. $wffTab = 'all';
  7928. }
  7929. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7930. $purchaseOrderId = 0;
  7931. $po = null;
  7932. try {
  7933. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7934. if (is_array($po)) {
  7935. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7936. }
  7937. } catch (\Throwable $e) {
  7938. $purchaseOrderId = 0;
  7939. $po = null;
  7940. }
  7941. if (!$isPurchaseConfirm && is_array($po)) {
  7942. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7943. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7944. $isPurchaseConfirm = true;
  7945. }
  7946. }
  7947. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7948. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7949. $confirmProcessCount = 1;
  7950. $confirmPickGroups = [];
  7951. $processDisplayRows = [];
  7952. $allDetailsBySid = [];
  7953. $requiredSidList = [];
  7954. $sidList = [$ids];
  7955. if ($isPurchaseConfirm) {
  7956. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7957. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7958. if ($mergeRows !== []) {
  7959. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7960. }
  7961. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7962. if ($confirmBundle['pos'] !== []) {
  7963. $sidList = [];
  7964. foreach ($confirmBundle['pos'] as $poRow) {
  7965. if (!is_array($poRow)) {
  7966. continue;
  7967. }
  7968. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7969. if (!$this->isValidScydgyRowId($sid)) {
  7970. continue;
  7971. }
  7972. $sidList[] = (string)$sid;
  7973. $requiredSidList[] = $sid;
  7974. }
  7975. }
  7976. if ($sidList === []) {
  7977. $sidList = [$ids];
  7978. $requiredSidList = [(int)$ids];
  7979. }
  7980. $confirmProcessCount = max(1, count($requiredSidList));
  7981. if (is_array($po) && $purchaseOrderId <= 0) {
  7982. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7983. }
  7984. }
  7985. $rows = [];
  7986. try {
  7987. if (count($sidList) === 1) {
  7988. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7989. } else {
  7990. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7991. }
  7992. } catch (\Throwable $e) {
  7993. $rows = [];
  7994. }
  7995. if ($isPurchaseConfirm) {
  7996. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7997. }
  7998. foreach ($rows as &$r) {
  7999. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  8000. $r['id'] = $r['ID'];
  8001. }
  8002. if (isset($r['createtime'])) {
  8003. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  8004. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  8005. } else {
  8006. $r['createtime_text'] = (string)$r['createtime'];
  8007. }
  8008. } else {
  8009. $r['createtime_text'] = '';
  8010. }
  8011. if (is_array($r)) {
  8012. $r = $this->maskSupplierContactFields($r);
  8013. }
  8014. }
  8015. unset($r);
  8016. $pickedCompanyName = '';
  8017. if ($isPurchaseConfirm) {
  8018. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  8019. if (!is_array($poRow)) {
  8020. continue;
  8021. }
  8022. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  8023. if ($pn !== '') {
  8024. $pickedCompanyName = $pn;
  8025. break;
  8026. }
  8027. }
  8028. }
  8029. $this->view->assign('rows', $rows ?: []);
  8030. $this->view->assign('rowCount', count($rows ?: []));
  8031. $this->view->assign('scydgyId', $ids);
  8032. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  8033. $this->view->assign('headTitle', $headTitle);
  8034. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  8035. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  8036. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  8037. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  8038. $this->view->assign('processDisplayRows', $processDisplayRows);
  8039. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8040. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8041. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8042. $sysRqDisplay = '—';
  8043. if ($isPurchaseConfirm) {
  8044. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8045. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8046. );
  8047. }
  8048. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8049. $this->view->assign('sysRq', $isPurchaseConfirm
  8050. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8051. : '');
  8052. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8053. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8054. : '');
  8055. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8056. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8057. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8058. if ($isPurchaseConfirm) {
  8059. return $this->view->fetch();
  8060. }
  8061. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8062. $this->view->engine->layout(false);
  8063. try {
  8064. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8065. $this->view->assign('dialogBody', $bodyHtml);
  8066. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8067. } finally {
  8068. if ($restoreLayout) {
  8069. $this->view->engine->layout($restoreLayout);
  8070. }
  8071. }
  8072. }
  8073. /**
  8074. * 月度导出记录表(不存在时自动创建)
  8075. */
  8076. protected function ensurePurchaseMonthExportLogTable(): void
  8077. {
  8078. try {
  8079. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8080. } catch (\Throwable $e) {
  8081. Db::execute(
  8082. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8083. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8084. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8085. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8086. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8087. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8088. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8089. `createtime` int(10) unsigned DEFAULT NULL,
  8090. PRIMARY KEY (`id`),
  8091. KEY `idx_ym` (`ym`),
  8092. KEY `idx_ct` (`createtime`)
  8093. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8094. );
  8095. }
  8096. }
  8097. /**
  8098. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8099. *
  8100. * @param array<int, mixed> $dbRows
  8101. * @return array<int, array<string, mixed>>
  8102. */
  8103. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8104. {
  8105. $keyword = trim((string)$this->request->get('search', ''));
  8106. if ($keyword === '') {
  8107. $keyword = trim((string)$this->request->request('search', ''));
  8108. }
  8109. $filter = $this->request->get('filter', '');
  8110. $op = $this->request->get('op', '');
  8111. if (is_string($filter) && $filter !== '') {
  8112. $filterArr = (array)json_decode($filter, true);
  8113. } else {
  8114. $filterArr = is_array($filter) ? $filter : [];
  8115. }
  8116. if (is_string($op) && $op !== '') {
  8117. $opArr = (array)json_decode($op, true);
  8118. } else {
  8119. $opArr = is_array($op) ? $op : [];
  8120. }
  8121. if ($keyword === '' && $filterArr === []) {
  8122. return array_values(array_filter($dbRows, 'is_array'));
  8123. }
  8124. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8125. $out = [];
  8126. foreach ($dbRows as $row) {
  8127. if (!is_array($row)) {
  8128. continue;
  8129. }
  8130. if ($keyword !== '') {
  8131. $hit = false;
  8132. foreach ($searchFields as $f) {
  8133. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8134. $hit = true;
  8135. break;
  8136. }
  8137. }
  8138. if (!$hit) {
  8139. continue;
  8140. }
  8141. }
  8142. $passFilter = true;
  8143. foreach ($filterArr as $field => $val) {
  8144. $field = (string)$field;
  8145. $val = trim((string)$val);
  8146. if ($field === '' || $val === '') {
  8147. continue;
  8148. }
  8149. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8150. continue;
  8151. }
  8152. $cell = (string)($row[$field] ?? '');
  8153. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8154. if ($mode === '=' || $mode === 'EQUAL') {
  8155. if (strcasecmp($cell, $val) !== 0) {
  8156. $passFilter = false;
  8157. break;
  8158. }
  8159. } elseif (mb_stripos($cell, $val) === false) {
  8160. $passFilter = false;
  8161. break;
  8162. }
  8163. }
  8164. if (!$passFilter) {
  8165. continue;
  8166. }
  8167. $out[] = $row;
  8168. }
  8169. return $out;
  8170. }
  8171. /**
  8172. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8173. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8174. */
  8175. public function export_month_outward()
  8176. {
  8177. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8178. $this->error(__('You have no permission'));
  8179. }
  8180. $this->request->filter(['strip_tags', 'trim']);
  8181. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8182. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8183. $ym = date('Y-m');
  8184. }
  8185. $dbRows = [];
  8186. try {
  8187. $query = Db::table('purchase_order');
  8188. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8189. $dbRows = $query->select();
  8190. } catch (\Throwable $e) {
  8191. $dbRows = [];
  8192. }
  8193. if (!is_array($dbRows)) {
  8194. $dbRows = [];
  8195. }
  8196. $completeTsMap = [];
  8197. $sidList = [];
  8198. foreach ($dbRows as $dbRow) {
  8199. if (!is_array($dbRow)) {
  8200. continue;
  8201. }
  8202. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8203. if ($sid > 0) {
  8204. $sidList[$sid] = true;
  8205. }
  8206. }
  8207. if ($sidList !== []) {
  8208. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8209. }
  8210. $searchKw = trim((string)$this->request->get('search', ''));
  8211. if ($searchKw === '') {
  8212. $searchKw = trim((string)$this->request->request('search', ''));
  8213. }
  8214. $filterRaw = $this->request->get('filter', '');
  8215. $filterArrTmp = [];
  8216. if (is_string($filterRaw) && $filterRaw !== '') {
  8217. $filterArrTmp = (array)json_decode($filterRaw, true);
  8218. } elseif (is_array($filterRaw)) {
  8219. $filterArrTmp = $filterRaw;
  8220. }
  8221. $hasSearch = ($searchKw !== '');
  8222. if (!$hasSearch) {
  8223. foreach ($filterArrTmp as $fv) {
  8224. if (trim((string)$fv) !== '') {
  8225. $hasSearch = true;
  8226. break;
  8227. }
  8228. }
  8229. }
  8230. // 有搜索时跨月份导出(与列表一致);无搜索时仍按查看月份
  8231. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8232. if (!is_array($dbRow)) {
  8233. return false;
  8234. }
  8235. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8236. if ($done['ts'] <= 0) {
  8237. return false;
  8238. }
  8239. if ($hasSearch) {
  8240. return true;
  8241. }
  8242. return date('Y-m', $done['ts']) === $ym;
  8243. }));
  8244. // 与列表页一致:按搜索关键字 / 通用搜索过滤
  8245. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8246. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8247. $filtered = $pool;
  8248. $mainBySid = [];
  8249. foreach ($filtered as $rw) {
  8250. if (!is_array($rw)) {
  8251. continue;
  8252. }
  8253. $rid = (int)($rw['ID'] ?? 0);
  8254. if ($rid > 0) {
  8255. $mainBySid[$rid] = $rw;
  8256. }
  8257. }
  8258. if ($mainBySid === []) {
  8259. $detailRows = [];
  8260. } else {
  8261. try {
  8262. $detailRows = Db::table('purchase_order_detail')
  8263. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8264. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8265. ->order('status', 'desc')
  8266. ->order('CCYDH', 'asc')
  8267. ->order('company_name', 'asc')
  8268. ->order('id', 'asc')
  8269. ->select();
  8270. } catch (\Throwable $e) {
  8271. try {
  8272. $detailRows = Db::table('purchase_order_detail')
  8273. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8274. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8275. ->order('status', 'desc')
  8276. ->order('CCYDH', 'asc')
  8277. ->order('company_name', 'asc')
  8278. ->order('ID', 'asc')
  8279. ->select();
  8280. } catch (\Throwable $e2) {
  8281. $detailRows = [];
  8282. }
  8283. }
  8284. }
  8285. if (!is_array($detailRows)) {
  8286. $detailRows = [];
  8287. }
  8288. $exportLines = [];
  8289. $detailSidSeen = [];
  8290. foreach ($detailRows as $dr) {
  8291. if (!is_array($dr)) {
  8292. continue;
  8293. }
  8294. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8295. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8296. continue;
  8297. }
  8298. if (isset($detailSidSeen[$sid])) {
  8299. continue;
  8300. }
  8301. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8302. continue;
  8303. }
  8304. $detailSidSeen[$sid] = true;
  8305. $m = $mainBySid[$sid];
  8306. $exportLines[] = [
  8307. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8308. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8309. 'company_name' => (string)($dr['company_name'] ?? ''),
  8310. 'CDF' => (string)($m['CDF'] ?? ''),
  8311. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8312. 'gx' => $this->procuremenExportGxText($m),
  8313. 'detail' => $dr,
  8314. ];
  8315. }
  8316. foreach ($detailRows as $dr) {
  8317. if (!is_array($dr)) {
  8318. continue;
  8319. }
  8320. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8321. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8322. continue;
  8323. }
  8324. $detailSidSeen[$sid] = true;
  8325. $m = $mainBySid[$sid];
  8326. $exportLines[] = [
  8327. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8328. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8329. 'company_name' => (string)($dr['company_name'] ?? ''),
  8330. 'CDF' => (string)($m['CDF'] ?? ''),
  8331. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8332. 'gx' => $this->procuremenExportGxText($m),
  8333. 'detail' => $dr,
  8334. ];
  8335. }
  8336. foreach ($mainBySid as $sid => $m) {
  8337. if (isset($detailSidSeen[$sid])) {
  8338. continue;
  8339. }
  8340. $company = trim((string)($m['pick_company_name'] ?? ''));
  8341. $exportLines[] = [
  8342. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8343. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8344. 'company_name' => $company,
  8345. 'CDF' => (string)($m['CDF'] ?? ''),
  8346. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8347. 'gx' => $this->procuremenExportGxText($m),
  8348. 'detail' => [],
  8349. ];
  8350. }
  8351. $groups = [];
  8352. foreach ($exportLines as $line) {
  8353. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8354. if (!isset($groups[$k])) {
  8355. $groups[$k] = [];
  8356. }
  8357. $groups[$k][] = $line;
  8358. }
  8359. ksort($groups, SORT_STRING);
  8360. $spreadsheet = new Spreadsheet();
  8361. $sheet = $spreadsheet->getActiveSheet();
  8362. $sheet->setTitle('外协加工明细');
  8363. $mon = (int)substr($ym, 5, 2);
  8364. $sheet->mergeCells('A1:H1');
  8365. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8366. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8367. $sheet->getStyle('A1')->getAlignment()
  8368. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8369. ->setVertical(Alignment::VERTICAL_CENTER);
  8370. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8371. $col = 'A';
  8372. foreach ($headers as $h) {
  8373. $sheet->setCellValue($col . '2', $h);
  8374. $col++;
  8375. }
  8376. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8377. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8378. $rowNum = 3;
  8379. $sumSubtotalCounts = 0;
  8380. $grandAmount = 0.0;
  8381. $globalSeq = 0;
  8382. if ($groups === []) {
  8383. $sheet->mergeCells('A3:H3');
  8384. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8385. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8386. $rowNum = 4;
  8387. } else {
  8388. foreach ($groups as $items) {
  8389. if ($items === []) {
  8390. continue;
  8391. }
  8392. $groupLineCount = count($items);
  8393. $subAmount = 0.0;
  8394. foreach ($items as $line) {
  8395. $globalSeq++;
  8396. $dr = $line['detail'];
  8397. $amt = $this->procuremenExportAmount($dr);
  8398. $subAmount += $amt;
  8399. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8400. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8401. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8402. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8403. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8404. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8405. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8406. $sheet->setCellValue('H' . $rowNum, $amt);
  8407. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8408. $rowNum++;
  8409. }
  8410. $sumSubtotalCounts += $groupLineCount;
  8411. $grandAmount += $subAmount;
  8412. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8413. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8414. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8415. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8416. ->setVertical(Alignment::VERTICAL_CENTER);
  8417. $rowNum++;
  8418. }
  8419. }
  8420. $sheet->setCellValue('A' . $rowNum, '总计');
  8421. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8422. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8423. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8424. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8425. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8426. $lastRow = $rowNum;
  8427. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8428. 'borders' => [
  8429. 'allBorders' => [
  8430. 'borderStyle' => Border::BORDER_THIN,
  8431. 'color' => ['rgb' => '000000'],
  8432. ],
  8433. ],
  8434. ]);
  8435. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8436. if ($lastRow >= 3) {
  8437. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8438. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8439. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8440. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8441. }
  8442. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8443. $sheet->getColumnDimension('A')->setWidth(7);
  8444. $sheet->getColumnDimension('B')->setWidth(16);
  8445. $sheet->getColumnDimension('C')->setWidth(52);
  8446. $sheet->getColumnDimension('D')->setWidth(32);
  8447. $sheet->getColumnDimension('E')->setWidth(12);
  8448. $sheet->getColumnDimension('F')->setWidth(44);
  8449. $sheet->getColumnDimension('G')->setWidth(26);
  8450. $sheet->getColumnDimension('H')->setWidth(13);
  8451. $sheet->getRowDimension(1)->setRowHeight(28);
  8452. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8453. $quoteStartRow = $lastRow + 3;
  8454. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  8455. if ($quoteLastRow >= $quoteStartRow) {
  8456. $sheet->getColumnDimension('E')->setWidth(28);
  8457. }
  8458. $ymCompact = str_replace('-', '', $ym);
  8459. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8460. $filename = $fileBase . '.xlsx';
  8461. try {
  8462. $this->ensurePurchaseMonthExportLogTable();
  8463. list($adminId, $adminName) = $this->GetUseName();
  8464. Db::table('purchase_month_export_log')->insert([
  8465. 'ym' => $ym,
  8466. 'admin_id' => (int)$adminId,
  8467. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8468. 'row_count' => count($exportLines),
  8469. 'total_amount' => round($grandAmount, 2),
  8470. 'createtime' => time(),
  8471. ]);
  8472. } catch (\Throwable $e) {
  8473. Log::write('month export log: ' . $e->getMessage(), 'error');
  8474. }
  8475. if (ob_get_length()) {
  8476. ob_end_clean();
  8477. }
  8478. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8479. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8480. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8481. header('Cache-Control: max-age=0');
  8482. $writer = new Xlsx($spreadsheet);
  8483. $writer->save('php://output');
  8484. $spreadsheet->disconnectWorksheets();
  8485. unset($spreadsheet);
  8486. exit;
  8487. }
  8488. /**
  8489. * 导出用:工序列文案
  8490. */
  8491. protected function procuremenExportGxText(array $r)
  8492. {
  8493. $a = trim((string)($r['CDXMC'] ?? ''));
  8494. $b = trim((string)($r['CGYMC'] ?? ''));
  8495. if ($a !== '' && $b !== '') {
  8496. return $a . ':' . $b;
  8497. }
  8498. return $a !== '' ? $a : $b;
  8499. }
  8500. /**
  8501. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8502. */
  8503. protected function procuremenExportAmount(array $r)
  8504. {
  8505. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8506. if (!array_key_exists($k, $r)) {
  8507. continue;
  8508. }
  8509. $v = $r[$k];
  8510. if ($v === null || $v === '') {
  8511. continue;
  8512. }
  8513. if (is_numeric($v)) {
  8514. return (float)$v;
  8515. }
  8516. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8517. if ($v !== '' && is_numeric($v)) {
  8518. return (float)$v;
  8519. }
  8520. }
  8521. return 0.0;
  8522. }
  8523. /**
  8524. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8525. *
  8526. * @param array<int, array<string, mixed>> $detailRows
  8527. * @param array<int, array<string, mixed>> $mainBySid
  8528. * @return array<int, array<string, mixed>>
  8529. */
  8530. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8531. {
  8532. $lines = [];
  8533. foreach ($detailRows as $dr) {
  8534. if (!is_array($dr)) {
  8535. continue;
  8536. }
  8537. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8538. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8539. continue;
  8540. }
  8541. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8542. continue;
  8543. }
  8544. $cn = trim((string)($dr['company_name'] ?? ''));
  8545. if ($cn === '') {
  8546. continue;
  8547. }
  8548. $m = $mainBySid[$sid];
  8549. $am = trim((string)($dr['amount'] ?? ''));
  8550. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8551. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8552. $amountText = $amountFilled
  8553. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8554. : '未填写';
  8555. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8556. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8557. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8558. $deliveryShow = $deliveryRaw;
  8559. }
  8560. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8561. ? $deliveryShow
  8562. : '未填写';
  8563. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8564. $lines[] = [
  8565. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8566. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8567. 'gx' => $this->procuremenExportGxText($m),
  8568. 'company_name' => $cn,
  8569. 'amount_text' => $amountText,
  8570. 'amount_num' => $amountFilled ? $amountNum : null,
  8571. 'delivery_text' => $deliveryText,
  8572. 'picked_text' => $picked ? '中标' : '未中标',
  8573. 'picked' => $picked,
  8574. ];
  8575. }
  8576. $winnerSupplierByOrder = [];
  8577. foreach ($lines as $line) {
  8578. $dh = trim((string)($line['CCYDH'] ?? ''));
  8579. $cn = trim((string)($line['company_name'] ?? ''));
  8580. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8581. $winnerSupplierByOrder[$dh][$cn] = true;
  8582. }
  8583. }
  8584. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8585. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8586. if ($c !== 0) {
  8587. return $c;
  8588. }
  8589. $dh = trim((string)($a['CCYDH'] ?? ''));
  8590. $aCn = trim((string)($a['company_name'] ?? ''));
  8591. $bCn = trim((string)($b['company_name'] ?? ''));
  8592. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8593. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8594. if ($aSupplierWin !== $bSupplierWin) {
  8595. return $aSupplierWin ? -1 : 1;
  8596. }
  8597. $c = strcmp($aCn, $bCn);
  8598. if ($c !== 0) {
  8599. return $c;
  8600. }
  8601. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8602. return !empty($a['picked']) ? -1 : 1;
  8603. }
  8604. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8605. if ($c !== 0) {
  8606. return $c;
  8607. }
  8608. return 0;
  8609. });
  8610. return $lines;
  8611. }
  8612. /**
  8613. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8614. *
  8615. * @param array<int, array<string, mixed>> $quoteLines
  8616. */
  8617. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8618. {
  8619. $mon = (int)substr($ym, 5, 2);
  8620. $titleRow = $startRow;
  8621. $headerRow = $startRow + 1;
  8622. $dataStartRow = $startRow + 2;
  8623. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8624. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8625. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8626. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8627. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8628. ->setVertical(Alignment::VERTICAL_CENTER);
  8629. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8630. $col = 'A';
  8631. foreach ($headers as $h) {
  8632. $sheet->setCellValue($col . $headerRow, $h);
  8633. $col++;
  8634. }
  8635. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8636. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8637. $rowNum = $dataStartRow;
  8638. if ($quoteLines === []) {
  8639. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8640. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8641. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8642. $rowNum = $dataStartRow + 1;
  8643. } else {
  8644. $i = 0;
  8645. foreach ($quoteLines as $line) {
  8646. $i++;
  8647. $sheet->setCellValue('A' . $rowNum, $i);
  8648. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8649. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8650. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8651. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8652. if ($line['amount_num'] !== null) {
  8653. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8654. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8655. } else {
  8656. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8657. }
  8658. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8659. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8660. if (!empty($line['picked'])) {
  8661. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8662. }
  8663. $rowNum++;
  8664. }
  8665. }
  8666. $lastRow = $rowNum - 1;
  8667. if ($lastRow >= $headerRow) {
  8668. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8669. 'borders' => [
  8670. 'allBorders' => [
  8671. 'borderStyle' => Border::BORDER_THIN,
  8672. 'color' => ['rgb' => '000000'],
  8673. ],
  8674. ],
  8675. ]);
  8676. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8677. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8678. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8679. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8680. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8681. if ($lastRow >= $dataStartRow) {
  8682. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8683. }
  8684. }
  8685. return $lastRow;
  8686. }
  8687. /**
  8688. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8689. */
  8690. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8691. {
  8692. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8693. return;
  8694. }
  8695. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8696. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8697. ->setVertical(Alignment::VERTICAL_CENTER);
  8698. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8699. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8700. ->setVertical(Alignment::VERTICAL_CENTER);
  8701. if ($lastCol > 'B') {
  8702. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8703. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8704. ->setVertical(Alignment::VERTICAL_CENTER);
  8705. }
  8706. }
  8707. /**
  8708. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8709. */
  8710. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8711. {
  8712. $s = trim($ccydh);
  8713. if ($s === '') {
  8714. return 'ORDER';
  8715. }
  8716. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8717. $s = trim($s, '._-');
  8718. if ($s === '') {
  8719. return 'ORDER';
  8720. }
  8721. if (function_exists('mb_substr')) {
  8722. return mb_substr($s, 0, 80, 'UTF-8');
  8723. }
  8724. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8725. }
  8726. /**
  8727. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8728. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8729. *
  8730. * @return array{objectKey: string, webPath: string}
  8731. */
  8732. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8733. {
  8734. $sid = (int)$scydgyId;
  8735. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8736. $y = date('Y');
  8737. $m = date('m');
  8738. $d = date('d');
  8739. $basename = $safeOrder . '_' . $sid . '.pdf';
  8740. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8741. return [
  8742. 'objectKey' => $objectKey,
  8743. 'webPath' => '/' . $objectKey,
  8744. ];
  8745. }
  8746. /**
  8747. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8748. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8749. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8750. *
  8751. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8752. */
  8753. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8754. {
  8755. if (!$this->isValidScydgyRowId($scydgyId)) {
  8756. return '';
  8757. }
  8758. $ids = trim((string)$scydgyId);
  8759. $prep = $this->prepareProcuremenDetailsView($ids);
  8760. if (!$prep['ok']) {
  8761. return '';
  8762. }
  8763. $ccydh = $prep['ccydh'];
  8764. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8765. $objectKey = $paths['objectKey'];
  8766. $webPath = $paths['webPath'];
  8767. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8768. $this->view->assign([
  8769. 'pdf_export' => 1,
  8770. 'pdfMetaLine' => $meta,
  8771. ]);
  8772. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8773. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8774. $this->view->engine->layout(false);
  8775. try {
  8776. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8777. } catch (\Throwable $e) {
  8778. if ($restoreLayout) {
  8779. $this->view->engine->layout($restoreLayout);
  8780. }
  8781. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8782. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8783. return '';
  8784. }
  8785. if ($restoreLayout) {
  8786. $this->view->engine->layout($restoreLayout);
  8787. }
  8788. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8789. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8790. if (!is_dir($tempDir)) {
  8791. @mkdir($tempDir, 0755, true);
  8792. }
  8793. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8794. try {
  8795. $mpdf = new \Mpdf\Mpdf([
  8796. 'mode' => 'utf-8',
  8797. 'format' => 'A4',
  8798. 'margin_left' => 12,
  8799. 'margin_right' => 12,
  8800. 'margin_top' => 14,
  8801. 'margin_bottom' => 14,
  8802. 'tempDir' => $tempDir,
  8803. 'autoScriptToLang' => true,
  8804. 'autoLangToFont' => true,
  8805. ]);
  8806. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8807. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8808. $mpdf->SetBasePath('http://127.0.0.1/');
  8809. $mpdf->WriteHTML($html);
  8810. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8811. } catch (\Throwable $e) {
  8812. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8813. if (is_file($tempPdf)) {
  8814. @unlink($tempPdf);
  8815. }
  8816. return '';
  8817. }
  8818. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8819. if ($ossUrl !== '') {
  8820. @unlink($tempPdf);
  8821. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8822. return $ossUrl;
  8823. }
  8824. $pi = pathinfo($objectKey);
  8825. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8826. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8827. if ($baseFile === '') {
  8828. @unlink($tempPdf);
  8829. return '';
  8830. }
  8831. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8832. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8833. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8834. @unlink($tempPdf);
  8835. return '';
  8836. }
  8837. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8838. if (!@copy($tempPdf, $fullPath)) {
  8839. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8840. @unlink($tempPdf);
  8841. return '';
  8842. }
  8843. @unlink($tempPdf);
  8844. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8845. return $webPath;
  8846. }
  8847. /**
  8848. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8849. */
  8850. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8851. {
  8852. if ($scydgyId <= 0 || $webPath === '') {
  8853. return;
  8854. }
  8855. try {
  8856. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8857. } catch (\Throwable $e) {
  8858. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8859. }
  8860. }
  8861. /**
  8862. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8863. *
  8864. * @param array<string, string> $vars
  8865. * @return array<string, string>
  8866. */
  8867. protected function normalizeSmsTemplateVars(array $vars): array
  8868. {
  8869. $out = [];
  8870. foreach ($vars as $k => $v) {
  8871. $out[(string)$k] = trim((string)$v);
  8872. }
  8873. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8874. $out['contact_name'] = $out['company_name'];
  8875. }
  8876. return $out;
  8877. }
  8878. /**
  8879. * 按手机号或公司名称查 customer 表联系人姓名
  8880. */
  8881. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8882. {
  8883. $phone = trim($phone);
  8884. $companyName = trim($companyName);
  8885. try {
  8886. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8887. $row = Db::table('customer')
  8888. ->where(function ($q) use ($phone) {
  8889. $q->where('phone', $phone)->whereOr('account', $phone);
  8890. })
  8891. ->order('id', 'asc')
  8892. ->find();
  8893. if (is_array($row)) {
  8894. $nm = trim((string)($row['username'] ?? ''));
  8895. if ($nm !== '') {
  8896. return $nm;
  8897. }
  8898. }
  8899. }
  8900. if ($companyName !== '') {
  8901. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8902. if (is_array($row)) {
  8903. return trim((string)($row['username'] ?? ''));
  8904. }
  8905. }
  8906. } catch (\Throwable $e) {
  8907. }
  8908. return '';
  8909. }
  8910. /**
  8911. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8912. */
  8913. protected function plainTextToHtmlEmailBody(string $text): string
  8914. {
  8915. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8916. $parts = explode("\n", $text);
  8917. $out = [];
  8918. foreach ($parts as $line) {
  8919. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8920. $out[] = $line;
  8921. } else {
  8922. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8923. }
  8924. }
  8925. return implode("<br>\n", $out);
  8926. }
  8927. /**
  8928. * 短信场景:去掉链接类变量,避免误填 URL
  8929. *
  8930. * @param array<string, string> $vars
  8931. * @return array<string, string>
  8932. */
  8933. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8934. {
  8935. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8936. return $vars;
  8937. }
  8938. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8939. $vars[$k] = '';
  8940. }
  8941. return $vars;
  8942. }
  8943. /**
  8944. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8945. *
  8946. * @param array<string, string> $vars
  8947. */
  8948. protected function renderNotifyTemplate(string $scene, array $vars): string
  8949. {
  8950. $vars = $this->normalizeSmsTemplateVars($vars);
  8951. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8952. $row = $this->loadNotifyTemplateRow($scene);
  8953. if ($row === null) {
  8954. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8955. }
  8956. $tpl = trim((string)($row['content'] ?? ''));
  8957. if ($tpl === '') {
  8958. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8959. }
  8960. foreach ($vars as $k => $v) {
  8961. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8962. }
  8963. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8964. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8965. return $tpl;
  8966. }
  8967. protected function resolveProcuremenEmailSubject(string $scene): string
  8968. {
  8969. $map = [
  8970. 'review_email' => '您有新的协助加工订单',
  8971. ];
  8972. $subject = trim((string)($map[$scene] ?? ''));
  8973. if ($subject === '') {
  8974. $this->error('未配置邮件主题:' . $scene);
  8975. }
  8976. return $subject;
  8977. }
  8978. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8979. {
  8980. $map = [
  8981. 'review_email' => '协助下发-邮箱',
  8982. 'review_sms' => '协助下发-短信',
  8983. 'confirm_ok' => '采购确认-通过',
  8984. 'confirm_fail' => '采购确认-未通过',
  8985. 'bid_open' => '开标双重验证',
  8986. ];
  8987. $label = $map[$scene] ?? $scene;
  8988. if ($titleRequired) {
  8989. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8990. }
  8991. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8992. }
  8993. /**
  8994. * 是否开启协助通知演练(不发真实短信/邮件)
  8995. */
  8996. protected function isProcuremenNotifyDryRun(): bool
  8997. {
  8998. return (bool)Config::get('procuremen_notify_dry_run');
  8999. }
  9000. /**
  9001. * @param array<string, mixed> $payload
  9002. */
  9003. protected function recordNotifyDryRunPreview(array $payload): void
  9004. {
  9005. $this->notifyDryRunPreview[] = $payload;
  9006. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9007. }
  9008. /**
  9009. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  9010. * @throws \Exception
  9011. */
  9012. protected function smsbao($phone, $content)
  9013. {
  9014. if ($this->isProcuremenNotifyDryRun()) {
  9015. $this->recordNotifyDryRunPreview([
  9016. 'scene' => 'sms_only',
  9017. 'phone' => $phone,
  9018. 'sms_content' => $content,
  9019. ]);
  9020. return;
  9021. }
  9022. $statusStr = [
  9023. '0' => '短信发送成功',
  9024. '-1' => '参数不全',
  9025. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  9026. '30' => '密码错误',
  9027. '40' => '账号不存在',
  9028. '41' => '余额不足',
  9029. '42' => '帐户已过期',
  9030. '43' => 'IP地址限制',
  9031. '50' => '内容含有敏感词',
  9032. ];
  9033. $smsapi = 'http://api.smsbao.com/';
  9034. $user = 'zhuwei123';
  9035. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  9036. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  9037. $result = @file_get_contents($sendurl);
  9038. if ($result === false) {
  9039. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9040. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9041. }
  9042. $result = trim((string)$result);
  9043. if ($result !== '0') {
  9044. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9045. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9046. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9047. }
  9048. }
  9049. }