Procuremen.php 286 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenStatus;
  6. use PHPMailer\PHPMailer\PHPMailer;
  7. use think\Config;
  8. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  9. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  10. use PhpOffice\PhpSpreadsheet\Style\Border;
  11. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  12. use think\Db;
  13. use think\Log;
  14. class Procuremen extends Backend
  15. {
  16. /**
  17. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  18. */
  19. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  20. /**
  21. * Procuremen模型对象
  22. * @var \app\admin\model\Procuremen
  23. */
  24. protected $model = null;
  25. /**
  26. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  27. */
  28. protected $notifyDryRunPreview = [];
  29. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  30. protected $procuremenRedisCache = null;
  31. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  32. protected $pickHiddenScydgySetCache = null;
  33. /**
  34. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  35. * @var array
  36. */
  37. protected $noNeedRight = [
  38. 'pickreview', 'review', 'reviewcompanies',
  39. ];
  40. public function _initialize()
  41. {
  42. parent::_initialize();
  43. $this->model = new \app\admin\model\Procuremen;
  44. $this->assignProcuremenAuthConfig();
  45. }
  46. /**
  47. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  48. *
  49. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  50. */
  51. protected function hasProcuremenPerm(array $actions): bool
  52. {
  53. foreach ($actions as $action) {
  54. $action = strtolower(trim((string)$action));
  55. if ($action === '') {
  56. continue;
  57. }
  58. if (strpos($action, 'procuremen/') !== 0) {
  59. $action = 'procuremen/' . $action;
  60. }
  61. if ($this->auth->check($action)) {
  62. return true;
  63. }
  64. }
  65. $suffixes = [];
  66. foreach ($actions as $action) {
  67. $action = strtolower(trim((string)$action));
  68. $action = preg_replace('#^procuremen/#', '', $action);
  69. if ($action !== '') {
  70. $suffixes[$action] = true;
  71. }
  72. }
  73. if ($suffixes === []) {
  74. return false;
  75. }
  76. try {
  77. foreach ($this->auth->getRuleList() as $rule) {
  78. $rule = strtolower((string)$rule);
  79. if (strpos($rule, 'procuremen/') !== 0) {
  80. continue;
  81. }
  82. foreach (array_keys($suffixes) as $suffix) {
  83. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  84. return true;
  85. }
  86. }
  87. }
  88. } catch (\Throwable $e) {
  89. }
  90. return false;
  91. }
  92. /**
  93. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  94. *
  95. * @param string[] $actions
  96. */
  97. protected function hasProcuremenPermStrict(array $actions): bool
  98. {
  99. foreach ($actions as $action) {
  100. $action = strtolower(trim((string)$action));
  101. if ($action === '') {
  102. continue;
  103. }
  104. if (strpos($action, 'procuremen/') !== 0) {
  105. $action = 'procuremen/' . $action;
  106. }
  107. if ($this->auth->check($action)) {
  108. return true;
  109. }
  110. }
  111. return false;
  112. }
  113. /**
  114. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  115. *
  116. * @param string[] $titles
  117. */
  118. protected function authHasAssignedRuleTitle(array $titles): bool
  119. {
  120. $titles = array_values(array_filter(array_map('trim', $titles)));
  121. if ($titles === []) {
  122. return false;
  123. }
  124. try {
  125. $ids = $this->auth->getRuleIds();
  126. if (in_array('*', $ids, true)) {
  127. return true;
  128. }
  129. if ($ids === []) {
  130. return false;
  131. }
  132. $rows = Db::name('auth_rule')
  133. ->where('status', 'normal')
  134. ->whereIn('id', $ids)
  135. ->column('title');
  136. foreach ($rows as $title) {
  137. $t = trim((string)$title);
  138. if ($t !== '' && in_array($t, $titles, true)) {
  139. return true;
  140. }
  141. }
  142. } catch (\Throwable $e) {
  143. }
  144. return false;
  145. }
  146. protected function procuremenCanPickDelete(): bool
  147. {
  148. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  149. return true;
  150. }
  151. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  152. }
  153. protected function procuremenCanComplete(): bool
  154. {
  155. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  156. return true;
  157. }
  158. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  159. }
  160. protected function procuremenCanDispatch(): bool
  161. {
  162. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  163. }
  164. /**
  165. * 前端按钮显隐(Config.procuremenAuth)
  166. */
  167. protected function assignProcuremenAuthConfig(): void
  168. {
  169. $authMap = [
  170. 'pickreview' => $this->procuremenCanDispatch(),
  171. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  172. 'pickdelete' => $this->procuremenCanPickDelete(),
  173. 'completedirectly' => $this->procuremenCanComplete(),
  174. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  175. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  176. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  177. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  178. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  179. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  180. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  181. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  182. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  183. 'details' => $this->hasProcuremenPerm(['details']),
  184. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon']),
  185. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  186. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  187. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  188. 'add' => $this->hasProcuremenPerm(['add']),
  189. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  190. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  191. ];
  192. $this->assignconfig('procuremenAuth', $authMap);
  193. }
  194. /**
  195. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  196. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  197. *
  198. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  199. */
  200. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  201. {
  202. static $mprocCfgLoaded = false;
  203. if (!$mprocCfgLoaded) {
  204. $mprocCfgLoaded = true;
  205. if (is_file(APP_PATH . 'extra/mproc.php')) {
  206. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  207. }
  208. }
  209. $eid = (int)$purchaseOrderDetailId;
  210. $base = $this->resolveMprocMobilePublicBaseUrl();
  211. if ($base === '') {
  212. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  213. }
  214. $path = trim((string)Config::get('mproc.mobile_index_path'));
  215. if ($path === '') {
  216. $path = '/index.php/index/index/index';
  217. } else {
  218. $path = '/' . ltrim($path, '/');
  219. }
  220. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  221. if ($eid > 0) {
  222. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  223. }
  224. return $base . $path . '?main_tab=orders';
  225. }
  226. /**
  227. * 邮件/短信外链:须为带点的公网域名
  228. */
  229. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  230. {
  231. $u = trim((string)$baseUrl);
  232. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  233. return false;
  234. }
  235. $host = parse_url($u, PHP_URL_HOST);
  236. if (!is_string($host) || $host === '') {
  237. return false;
  238. }
  239. if (strcasecmp($host, 'localhost') === 0) {
  240. return false;
  241. }
  242. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  243. return false;
  244. }
  245. if (strpos($host, '.') === false) {
  246. return false;
  247. }
  248. return true;
  249. }
  250. /**
  251. * 解析用于协助邮件/短信的手机端站点根
  252. */
  253. protected function resolveMprocMobilePublicBaseUrl()
  254. {
  255. $candidates = [];
  256. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  257. $candidates[] = trim((string)Config::get('site.indexurl'));
  258. $cdn = trim((string)Config::get('site.cdnurl'));
  259. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  260. $candidates[] = rtrim($cdn, '/');
  261. }
  262. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  263. $candidates[] = $reqBase;
  264. foreach ($candidates as $c) {
  265. if ($c === '') {
  266. continue;
  267. }
  268. $c = rtrim($c, '/');
  269. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  270. return $c;
  271. }
  272. }
  273. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  274. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  275. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  276. return $reqBase;
  277. }
  278. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  279. return '';
  280. }
  281. /**
  282. * 排除 mcyd.dputrecord 空串、零日期等非法值,避免 MySQL 1525(DATE_FORMAT/BETWEEN 遇 '' 报错)
  283. */
  284. protected function whereMcydDputrecordValid($query, $alias = 'a')
  285. {
  286. $c = $alias . '.dStamp';
  287. // 先转成 CHAR 再判断,避免 DATETIME 列里存 '' / 0000-00-00 时参与日期函数报错
  288. return $query->whereRaw(
  289. $c . ' IS NOT NULL'
  290. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) <> \'\''
  291. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) NOT LIKE \'0000-00-00%\''
  292. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) REGEXP \'^[12][0-9]{3}-[01][0-9]-[0-3][0-9]\''
  293. );
  294. }
  295. /**
  296. * 获取 Redis 中 procuremen_redis
  297. */
  298. protected function ProcuremenRedis(): array
  299. {
  300. if ($this->procuremenRedisCache !== null) {
  301. return $this->procuremenRedisCache;
  302. }
  303. try {
  304. $redis = redis();
  305. $raw = $redis->get('procuremen_redis');
  306. if ($raw === false || $raw === '') {
  307. $this->procuremenRedisCache = [];
  308. return $this->procuremenRedisCache;
  309. }
  310. $decoded = json_decode($raw, true);
  311. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  312. $this->procuremenRedisCache = [];
  313. return $this->procuremenRedisCache;
  314. }
  315. $this->procuremenRedisCache = $decoded['data'];
  316. return $this->procuremenRedisCache;
  317. } catch (\Throwable $e) {
  318. $this->procuremenRedisCache = [];
  319. return $this->procuremenRedisCache;
  320. }
  321. }
  322. /**
  323. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  324. *
  325. * @return array<int, array<string, mixed>>
  326. */
  327. protected function procuremenFetchErpPoolFromDb(): array
  328. {
  329. try {
  330. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  331. $endTime = date('Y-m-d 23:59:59');
  332. $list = Db::table('scydgy')
  333. ->alias('a')
  334. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  335. ->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')
  336. ->where([
  337. 'a.bwjg' => 1,
  338. 'a.iEndBz' => 0,
  339. 'a.iType' => 0,
  340. 'a.iStatus' => 10,
  341. ])
  342. ->where('a.dStamp', '>=', $startTime)
  343. ->where('a.dStamp', '<=', $endTime)
  344. ->order('a.dStamp', 'desc')
  345. ->select();
  346. if (!is_array($list)) {
  347. return [];
  348. }
  349. try {
  350. $redis = redis();
  351. $payload = [
  352. 'code' => 200,
  353. 'msg' => 'success',
  354. 'data' => $list,
  355. ];
  356. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  357. $this->procuremenRedisCache = $list;
  358. } catch (\Throwable $e) {
  359. }
  360. return $list;
  361. } catch (\Throwable $e) {
  362. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  363. return [];
  364. }
  365. }
  366. /**
  367. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  368. *
  369. * @return array<int, array<string, mixed>>
  370. */
  371. protected function procuremenEnsureRedisPool(): array
  372. {
  373. $pool = $this->ProcuremenRedis();
  374. if (is_array($pool) && $pool !== []) {
  375. return $pool;
  376. }
  377. static $warmed = false;
  378. if ($warmed) {
  379. return is_array($pool) ? $pool : [];
  380. }
  381. $warmed = true;
  382. return $this->procuremenFetchErpPoolFromDb();
  383. }
  384. /**
  385. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  386. *
  387. * @param array<string, mixed> $row
  388. */
  389. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  390. {
  391. $t = $this->procuremenRowListSortTime($row, $primary);
  392. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  393. return null;
  394. }
  395. $mo = (int)$m[2];
  396. if ($mo < 1 || $mo > 12) {
  397. return null;
  398. }
  399. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  400. }
  401. /**
  402. * @param array<int, array{year:string, months:array}> $sidebar
  403. * @return array<int, array{year:string, months:array}>
  404. */
  405. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  406. {
  407. $ym = trim($ym);
  408. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  409. return $sidebar;
  410. }
  411. foreach ($sidebar as $block) {
  412. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  413. continue;
  414. }
  415. foreach ($block['months'] as $item) {
  416. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  417. return $sidebar;
  418. }
  419. }
  420. }
  421. $y = substr($ym, 0, 4);
  422. $mo = (int)substr($ym, 5, 2);
  423. $sidebar[] = [
  424. 'year' => $y,
  425. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  426. ];
  427. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  428. }
  429. /**
  430. * @param array<int, array{year:string, months:array}> $sidebar
  431. * @return string[]
  432. */
  433. protected function flattenProcuremenSidebarYms(array $sidebar): array
  434. {
  435. $yms = [];
  436. foreach ($sidebar as $block) {
  437. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  438. continue;
  439. }
  440. foreach ($block['months'] as $item) {
  441. if (!is_array($item)) {
  442. continue;
  443. }
  444. $ym = trim((string)($item['ym'] ?? ''));
  445. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  446. $yms[$ym] = true;
  447. }
  448. }
  449. }
  450. return array_keys($yms);
  451. }
  452. /**
  453. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  454. */
  455. protected function GetIndexYearMonths()
  456. {
  457. $ymSet = [];
  458. $pool = $this->procuremenEnsureRedisPool();
  459. foreach ($pool as $r) {
  460. if (!is_array($r)) {
  461. continue;
  462. }
  463. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  464. if ($ym !== null) {
  465. $ymSet[$ym] = true;
  466. }
  467. }
  468. foreach ($this->loadPickManualOrderRows() as $r) {
  469. if (!is_array($r)) {
  470. continue;
  471. }
  472. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  473. if ($ym !== null) {
  474. $ymSet[$ym] = true;
  475. }
  476. }
  477. $ymList = array_keys($ymSet);
  478. if ($ymList === []) {
  479. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  480. }
  481. return $this->buildYearMonthSidebar($ymList);
  482. }
  483. /**
  484. * @param string[] $ymList 形如 2026-06
  485. * @return array<int, array{year:string, months:array}>
  486. */
  487. protected function buildYearMonthSidebar(array $ymList): array
  488. {
  489. rsort($ymList, SORT_STRING);
  490. $byYear = [];
  491. foreach ($ymList as $ym) {
  492. $y = substr($ym, 0, 4);
  493. $mo = (int)substr($ym, 5, 2);
  494. if (!isset($byYear[$y])) {
  495. $byYear[$y] = [];
  496. }
  497. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  498. }
  499. krsort($byYear, SORT_NUMERIC);
  500. foreach ($byYear as $y => $items) {
  501. usort($byYear[$y], function ($a, $b) {
  502. return strcmp($b['ym'], $a['ym']);
  503. });
  504. }
  505. $sidebar = [];
  506. foreach ($byYear as $y => $months) {
  507. $sidebar[] = ['year' => $y, 'months' => $months];
  508. }
  509. return $sidebar;
  510. }
  511. /**
  512. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  513. */
  514. protected function GetIssuedOrderYearMonths(string $stage): array
  515. {
  516. $ymSet = [];
  517. try {
  518. $query = Db::table('purchase_order');
  519. $this->applyPurchaseOrderNotDeletedWhere($query);
  520. if ($stage === 'audit') {
  521. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  522. } elseif ($stage === 'confirm') {
  523. $query->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))->where(function ($q) {
  524. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  525. ->whereOr(function ($q2) {
  526. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  527. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  528. });
  529. });
  530. } else {
  531. return $this->GetIndexYearMonths();
  532. }
  533. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  534. if (is_array($rows)) {
  535. foreach ($rows as $r) {
  536. if (!is_array($r)) {
  537. continue;
  538. }
  539. $ym = $this->procuremenRowYearMonth($r, 'pick_time');
  540. if ($ym !== null) {
  541. $ymSet[$ym] = true;
  542. }
  543. }
  544. }
  545. } catch (\Throwable $e) {
  546. $ymSet = [];
  547. }
  548. $ymList = array_keys($ymSet);
  549. if ($ymList === []) {
  550. $def = $this->resolveProcuremenDefaultYm($stage);
  551. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  552. }
  553. return $this->buildYearMonthSidebar($ymList);
  554. }
  555. /**
  556. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  557. */
  558. protected function resolveProcuremenDefaultYm(string $stage): string
  559. {
  560. if ($stage === 'pick') {
  561. return date('Y-m');
  562. }
  563. try {
  564. $query = Db::table('purchase_order');
  565. $this->applyPurchaseOrderNotDeletedWhere($query);
  566. if ($stage === 'audit') {
  567. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  568. } elseif ($stage === 'confirm') {
  569. $query->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))->where(function ($q) {
  570. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  571. ->whereOr(function ($q2) {
  572. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  573. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  574. });
  575. });
  576. } else {
  577. return date('Y-m');
  578. }
  579. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  580. if ($latest === null || $latest === '') {
  581. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  582. }
  583. $t = $this->formatProcuremenDetailTime($latest);
  584. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  585. return $m[1] . '-' . $m[2];
  586. }
  587. } catch (\Throwable $e) {
  588. }
  589. return date('Y-m');
  590. }
  591. protected function applyPurchaseOrderNotDeletedWhere($query): void
  592. {
  593. $query->whereRaw(
  594. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  595. );
  596. }
  597. /** @deprecated 使用 {@see ProcuremenStatus::POD_VOID} */
  598. protected const PURCHASE_DETAIL_STATUS_VOID = '已废弃';
  599. protected function isPurchaseOrderDetailVoid(array $row): bool
  600. {
  601. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  602. return true;
  603. }
  604. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  605. }
  606. /**
  607. * 仅当前有效下发明细(排除废弃归档)
  608. */
  609. protected function applyActivePurchaseOrderDetailWhere($query): void
  610. {
  611. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  612. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  613. }
  614. /**
  615. * 列表/流程判定:存在有效下发明细
  616. */
  617. protected function purchaseOrderDetailActiveExistsSql(string $detailAlias = 'd'): string
  618. {
  619. $void = ProcuremenStatus::POD_VOID;
  620. return 'EXISTS (SELECT 1 FROM purchase_order_detail ' . $detailAlias
  621. . ' WHERE ' . $detailAlias . '.scydgy_id = purchase_order.scydgy_id'
  622. . ' AND ' . str_replace('`status`', $detailAlias . '.`status`', ProcuremenStatus::sqlPodNotVoid($detailAlias . '.status'))
  623. . ' AND (' . $detailAlias . '.status_name IS NULL OR TRIM(' . $detailAlias . '.status_name) = \'\' OR ' . $detailAlias . '.status_name <> \'' . $void . '\')'
  624. . ' LIMIT 1)';
  625. }
  626. /**
  627. * 废弃退回初选:下发明细标记归档,不物理删除
  628. *
  629. * @param array<int, int|string> $scydgyIds
  630. */
  631. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  632. {
  633. $ids = [];
  634. foreach ($scydgyIds as $sid) {
  635. $n = (int)$sid;
  636. if ($this->isValidScydgyRowId($n) || $n < 0) {
  637. $ids[$n] = true;
  638. }
  639. }
  640. if ($ids === []) {
  641. return;
  642. }
  643. $void = ProcuremenStatus::POD_VOID;
  644. Db::table('purchase_order_detail')
  645. ->where('scydgy_id', 'in', array_keys($ids))
  646. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  647. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  648. ->update([
  649. 'status' => $void,
  650. 'status_name' => $void,
  651. ]);
  652. }
  653. /**
  654. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  655. */
  656. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  657. {
  658. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  659. $norm = function (string $col) use ($p): string {
  660. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  661. };
  662. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  663. $parts = [];
  664. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  665. if ($key === 'createtime') {
  666. $parts[] = $createtime;
  667. } else {
  668. $parts[] = $norm($key);
  669. }
  670. }
  671. return 'COALESCE(' . implode(', ', $parts) . ')';
  672. }
  673. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  674. {
  675. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  676. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  677. }
  678. /**
  679. * @return array<int, array<string, mixed>>
  680. */
  681. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  682. {
  683. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  684. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  685. try {
  686. $query = Db::table('purchase_order')->field($fields);
  687. $this->applyPurchaseOrderNotDeletedWhere($query);
  688. if ($stage === 'audit') {
  689. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('pick_time', 'desc')->order('id', 'desc');
  690. } elseif ($stage === 'confirm') {
  691. $query->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))->where(function ($q) {
  692. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  693. ->whereOr(function ($q2) {
  694. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  695. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  696. });
  697. })->order('pick_time', 'desc')->order('id', 'desc');
  698. } else {
  699. return [];
  700. }
  701. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  702. $monthStart = $ym . '-01 00:00:00';
  703. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  704. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  705. }
  706. $rows = $query->select();
  707. } catch (\Throwable $e) {
  708. $rows = [];
  709. }
  710. return is_array($rows) ? $rows : [];
  711. }
  712. /**
  713. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  714. */
  715. protected function resolveProcuremenListStage(): string
  716. {
  717. $action = strtolower((string)$this->request->action());
  718. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  719. return $action;
  720. }
  721. $tab = trim((string)$this->request->request('wff_tab', 'pick'));
  722. return in_array($tab, ['pick', 'audit', 'confirm'], true) ? $tab : 'pick';
  723. }
  724. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  725. {
  726. $rootTrue = rtrim((string)$this->request->root(true), '/');
  727. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  728. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  729. $indexPhpRoot = $rootTrue . '/index.php';
  730. }
  731. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  732. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  733. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  734. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  735. $this->view->assign('defaultYm', $defaultYm);
  736. $this->view->assign('sidebarYearMonths', $sidebar);
  737. $this->view->assign('procuremenStage', $stage);
  738. $this->view->assign('procuremenPageTitle', $pageTitle);
  739. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  740. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  741. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  742. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  743. }
  744. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  745. public function pick()
  746. {
  747. $this->request->filter(['strip_tags', 'trim']);
  748. if (!$this->request->isAjax()) {
  749. $this->assignProcuremenListPage('pick', '协助下发');
  750. return $this->view->fetch('procuremen/index');
  751. }
  752. return $this->index();
  753. }
  754. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  755. public function audit()
  756. {
  757. $this->request->filter(['strip_tags', 'trim']);
  758. if (!$this->request->isAjax()) {
  759. $this->assignProcuremenListPage('audit', '确认供应商');
  760. return $this->view->fetch('procuremen/index');
  761. }
  762. return $this->index();
  763. }
  764. /** 采购确认(定标) */
  765. public function confirm()
  766. {
  767. $this->request->filter(['strip_tags', 'trim']);
  768. if (!$this->request->isAjax()) {
  769. $this->assignProcuremenListPage('confirm', '采购确认');
  770. return $this->view->fetch('procuremen/index');
  771. }
  772. return $this->index();
  773. }
  774. /**
  775. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  776. */
  777. public function index()
  778. {
  779. $this->request->filter(['strip_tags', 'trim']);
  780. if (!$this->request->isAjax()) {
  781. $this->assignProcuremenListPage('pick', '协助下发');
  782. return $this->view->fetch('procuremen/index');
  783. }
  784. if ($this->request->request('keyField')) {
  785. return $this->selectpage();
  786. }
  787. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  788. $limit = max(10, min(500, (int)$limit));
  789. $ym = $this->request->request('ym', date('Y-m'));
  790. $ym = is_string($ym) ? trim($ym) : '';
  791. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  792. $ym = date('Y-m');
  793. }
  794. $monthStart = $ym . '-01 00:00:00';
  795. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  796. $search = trim((string)$this->request->get('search', ''));
  797. $hasActiveSearch = ($search !== '');
  798. if (!$hasActiveSearch) {
  799. $filterStr = $this->request->get('filter', '');
  800. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  801. $arr = json_decode($filterStr, true);
  802. if (is_array($arr) && count($arr) > 0) {
  803. foreach ($arr as $v) {
  804. if (is_array($v)) {
  805. if (array_filter($v, function ($x) {
  806. return $x !== '' && $x !== null;
  807. })) {
  808. $hasActiveSearch = true;
  809. break;
  810. }
  811. } elseif ($v !== '' && $v !== null) {
  812. $hasActiveSearch = true;
  813. break;
  814. }
  815. }
  816. }
  817. }
  818. }
  819. $applyMonthRange = !$hasActiveSearch;
  820. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  821. $opArr = (array)json_decode($this->request->get('op', ''), true);
  822. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  823. $wffTab = $this->resolveProcuremenListStage();
  824. try {
  825. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  826. if ($wffTab === 'audit') {
  827. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  828. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  829. );
  830. } elseif ($wffTab === 'confirm') {
  831. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  832. $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange)
  833. );
  834. } else {
  835. $pool = $this->procuremenEnsureRedisPool();
  836. if (!is_array($pool)) {
  837. $pool = [];
  838. }
  839. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  840. $hideSet = $this->loadPickHiddenScydgySet();
  841. if ($pool !== [] && $hideSet !== []) {
  842. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  843. if (!is_array($r)) {
  844. return false;
  845. }
  846. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  847. return $id <= 0 || !isset($hideSet[$id]);
  848. }));
  849. }
  850. $manualPool = $this->loadPickManualOrderRows();
  851. if ($manualPool !== []) {
  852. $pool = array_merge($pool, $manualPool);
  853. }
  854. if ($pool === []) {
  855. return json([
  856. 'total' => 0,
  857. 'rows' => [],
  858. ]);
  859. }
  860. }
  861. $filtered = $this->filterProcuremenIndexPool(
  862. $pool,
  863. $monthStart,
  864. $monthEnd,
  865. $applyMonthRange,
  866. $search,
  867. $filterArr,
  868. $opArr,
  869. $listTimePrimary
  870. );
  871. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  872. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  873. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  874. }
  875. $sortField = 'ID';
  876. if (is_string($sort) && $sort !== '') {
  877. $parts = explode(',', $sort);
  878. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  879. if ($sortField === '') {
  880. $sortField = 'ID';
  881. }
  882. }
  883. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  884. $nFiltered = count($filtered);
  885. if ($nFiltered > 1) {
  886. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  887. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  888. $ta = $this->procuremenRowListSortTime($a, $sortField);
  889. $tb = $this->procuremenRowListSortTime($b, $sortField);
  890. if ($ta === $tb) {
  891. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  892. }
  893. if ($ta === '') {
  894. return 1;
  895. }
  896. if ($tb === '') {
  897. return -1;
  898. }
  899. return strcmp($ta, $tb) * $ord;
  900. });
  901. } elseif ($sortField === 'ID') {
  902. $sortKeys = [];
  903. foreach ($filtered as $i => $row) {
  904. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  905. }
  906. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  907. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  908. } elseif ($sortField === 'CCYDH') {
  909. usort($filtered, function ($a, $b) use ($ord) {
  910. $sa = trim((string)($a['CCYDH'] ?? ''));
  911. $sb = trim((string)($b['CCYDH'] ?? ''));
  912. if ($sa === $sb) {
  913. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  914. }
  915. if ($sa === '') {
  916. return 1;
  917. }
  918. if ($sb === '') {
  919. return -1;
  920. }
  921. return strcmp($sa, $sb) * $ord;
  922. });
  923. } else {
  924. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  925. $va = $a[$sortField] ?? null;
  926. $vb = $b[$sortField] ?? null;
  927. $sa = (string)$va;
  928. $sb = (string)$vb;
  929. if ($sa === $sb) {
  930. return 0;
  931. }
  932. return strcmp($sa, $sb) * $ord;
  933. });
  934. }
  935. }
  936. $offset = max(0, (int)$offset);
  937. $limit = max(1, (int)$limit);
  938. $rows = array_slice($filtered, $offset, $limit);
  939. foreach ($rows as &$rw) {
  940. if (!is_array($rw)) {
  941. continue;
  942. }
  943. $rid = (int)($rw['ID'] ?? 0);
  944. $rw['_iss_out'] = ($wffTab !== 'pick');
  945. }
  946. unset($rw);
  947. if ($wffTab === 'confirm' && count($rows) > 0) {
  948. $idList = [];
  949. foreach ($rows as $rw) {
  950. if (!is_array($rw)) {
  951. continue;
  952. }
  953. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  954. foreach ($rw['_order_merge_rows'] as $mr) {
  955. $mid = (int)($mr['ID'] ?? 0);
  956. if ($this->isValidScydgyRowId($mid)) {
  957. $idList[$mid] = true;
  958. }
  959. }
  960. }
  961. $id = (int)($rw['ID'] ?? 0);
  962. if ($this->isValidScydgyRowId($id)) {
  963. $idList[$id] = true;
  964. }
  965. }
  966. $sumMap = $this->OrderDetailSummary(array_keys($idList));
  967. foreach ($rows as &$rw) {
  968. if (!is_array($rw)) {
  969. continue;
  970. }
  971. $mergeIds = [];
  972. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  973. foreach ($rw['_order_merge_rows'] as $mr) {
  974. $mid = (int)($mr['ID'] ?? 0);
  975. if ($this->isValidScydgyRowId($mid)) {
  976. $mergeIds[$mid] = true;
  977. }
  978. }
  979. }
  980. $rid = (int)($rw['ID'] ?? 0);
  981. if ($this->isValidScydgyRowId($rid)) {
  982. $mergeIds[$rid] = true;
  983. }
  984. $cnt = 0;
  985. $amt = 0;
  986. $deliv = 0;
  987. foreach (array_keys($mergeIds) as $mid) {
  988. $s = isset($sumMap[$mid]) ? $sumMap[$mid] : ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  989. $cnt += (int)($s['cnt'] ?? 0);
  990. $amt += (int)($s['amt'] ?? 0);
  991. $deliv += (int)($s['deliv'] ?? 0);
  992. }
  993. $rw['po_detail_count'] = $cnt;
  994. $rw['po_amount_fill_cnt'] = $amt;
  995. $rw['po_delivery_fill_cnt'] = $deliv;
  996. }
  997. unset($rw);
  998. }
  999. if ($wffTab === 'confirm' && count($rows) > 0) {
  1000. $idList = [];
  1001. foreach ($rows as $rw) {
  1002. if (!is_array($rw)) {
  1003. continue;
  1004. }
  1005. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1006. foreach ($rw['_order_merge_rows'] as $mr) {
  1007. $mid = (int)($mr['ID'] ?? 0);
  1008. if ($this->isValidScydgyRowId($mid)) {
  1009. $idList[$mid] = true;
  1010. }
  1011. }
  1012. }
  1013. $id = (int)($rw['ID'] ?? 0);
  1014. if ($this->isValidScydgyRowId($id)) {
  1015. $idList[$id] = true;
  1016. }
  1017. }
  1018. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1019. foreach ($rows as &$rw) {
  1020. if (!is_array($rw)) {
  1021. continue;
  1022. }
  1023. $mergeIds = [];
  1024. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1025. foreach ($rw['_order_merge_rows'] as $mr) {
  1026. $mid = (int)($mr['ID'] ?? 0);
  1027. if ($this->isValidScydgyRowId($mid)) {
  1028. $mergeIds[$mid] = true;
  1029. }
  1030. }
  1031. }
  1032. $rid = (int)($rw['ID'] ?? 0);
  1033. if ($this->isValidScydgyRowId($rid)) {
  1034. $mergeIds[$rid] = true;
  1035. }
  1036. $buckets = [];
  1037. foreach (array_keys($mergeIds) as $mid) {
  1038. if (isset($quoteBucket[$mid])) {
  1039. $buckets[] = $quoteBucket[$mid];
  1040. }
  1041. }
  1042. $rw['picked_supplier_name'] = $buckets !== []
  1043. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1044. : '';
  1045. }
  1046. unset($rw);
  1047. }
  1048. if ($wffTab === 'audit' && count($rows) > 0) {
  1049. $idList = [];
  1050. foreach ($rows as $rw) {
  1051. if (!is_array($rw)) {
  1052. continue;
  1053. }
  1054. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1055. foreach ($rw['_order_merge_rows'] as $mr) {
  1056. $mid = (int)($mr['ID'] ?? 0);
  1057. if ($this->isValidScydgyRowId($mid)) {
  1058. $idList[$mid] = true;
  1059. }
  1060. }
  1061. }
  1062. $id = (int)($rw['ID'] ?? 0);
  1063. if ($this->isValidScydgyRowId($id)) {
  1064. $idList[$id] = true;
  1065. }
  1066. }
  1067. $notifyMap = $this->loadNotifySupplierNamesByScydgyIds(array_keys($idList));
  1068. foreach ($rows as &$rw) {
  1069. if (!is_array($rw)) {
  1070. continue;
  1071. }
  1072. $mergeIds = [];
  1073. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1074. foreach ($rw['_order_merge_rows'] as $mr) {
  1075. $mid = (int)($mr['ID'] ?? 0);
  1076. if ($this->isValidScydgyRowId($mid)) {
  1077. $mergeIds[$mid] = true;
  1078. }
  1079. }
  1080. }
  1081. $rid = (int)($rw['ID'] ?? 0);
  1082. if ($this->isValidScydgyRowId($rid)) {
  1083. $mergeIds[$rid] = true;
  1084. }
  1085. $names = [];
  1086. foreach (array_keys($mergeIds) as $mid) {
  1087. foreach ($notifyMap[$mid] ?? [] as $cn) {
  1088. if ($cn !== '' && !in_array($cn, $names, true)) {
  1089. $names[] = $cn;
  1090. }
  1091. }
  1092. }
  1093. sort($names, SORT_STRING);
  1094. $rw['notify_supplier_text'] = $this->formatNotifySupplierDisplay($names);
  1095. }
  1096. unset($rw);
  1097. }
  1098. if ($wffTab === 'all' && count($rows) > 0) {
  1099. $this->mergePurchaseOrder($rows);
  1100. }
  1101. if ($wffTab === 'pick' && count($rows) > 0) {
  1102. $this->mergePurchaseOrder($rows);
  1103. }
  1104. foreach ($rows as &$rwClean) {
  1105. if (is_array($rwClean)) {
  1106. unset($rwClean['_order_merge_rows']);
  1107. if (array_key_exists('NGZL', $rwClean)) {
  1108. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1109. }
  1110. }
  1111. }
  1112. unset($rwClean);
  1113. return json([
  1114. 'total' => count($filtered),
  1115. 'rows' => $rows,
  1116. ]);
  1117. } catch (\Throwable $e) {
  1118. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1119. return json([
  1120. 'total' => 0,
  1121. 'rows' => [],
  1122. ]);
  1123. }
  1124. }
  1125. /**
  1126. * 已协助/不可再审核判定(与「未发」列表隐藏规则一致,避免仅保存数量却被当成已下发)
  1127. * - purchase_order.status 为 0 或 1:已审核下发或已完结
  1128. * - 或存在 purchase_order_detail:已向供应商下过明细
  1129. * 仅写入 purchase_order 且 status 为空:视为未发(如只填本次数量、最高限价)
  1130. *
  1131. * @return array<int, true> scydgy_id => true
  1132. */
  1133. protected function loadIssuedScydgySet()
  1134. {
  1135. $issuedSet = [];
  1136. try {
  1137. $poList = Db::table('purchase_order')
  1138. ->whereIn('status', array_merge(
  1139. ProcuremenStatus::poInProgressValues(),
  1140. ProcuremenStatus::poCompletedValues()
  1141. ))
  1142. ->column('scydgy_id');
  1143. if (is_array($poList)) {
  1144. foreach ($poList as $ids) {
  1145. $n = (int)$ids;
  1146. if ($n > 0) {
  1147. $issuedSet[$n] = true;
  1148. }
  1149. }
  1150. }
  1151. } catch (\Throwable $e) {
  1152. }
  1153. try {
  1154. $detList = Db::table('purchase_order_detail');
  1155. $this->applyActivePurchaseOrderDetailWhere($detList);
  1156. $detList = $detList->group('scydgy_id')->column('scydgy_id');
  1157. if (is_array($detList)) {
  1158. foreach ($detList as $ids) {
  1159. $n = (int)$ids;
  1160. if ($n > 0) {
  1161. $issuedSet[$n] = true;
  1162. }
  1163. }
  1164. }
  1165. } catch (\Throwable $e) {
  1166. }
  1167. return $issuedSet;
  1168. }
  1169. /**
  1170. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1171. *
  1172. * @return array<int, true>
  1173. */
  1174. protected function loadPickHiddenScydgySet(): array
  1175. {
  1176. if ($this->pickHiddenScydgySetCache !== null) {
  1177. return $this->pickHiddenScydgySetCache;
  1178. }
  1179. $hideSet = [];
  1180. try {
  1181. $poIds = Db::table('purchase_order')
  1182. ->where(function ($q) {
  1183. $q->whereIn('wflow_status', array_merge(
  1184. ProcuremenStatus::wflowPendingConfirmValues(),
  1185. ProcuremenStatus::wflowPendingApprovalValues()
  1186. ))
  1187. ->whereOr(function ($q1) {
  1188. $q1->whereIn('status', ProcuremenStatus::poCompletedValues());
  1189. })
  1190. ->whereOr(function ($q2) {
  1191. $q2->whereNotNull('pick_time')
  1192. ->where('pick_time', '<>', '')
  1193. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1194. })
  1195. ->whereOr(function ($q3) {
  1196. $q3->whereNotNull('mod_rq')
  1197. ->where('mod_rq', '<>', '')
  1198. ->where('mod_rq', 'not like', '0000-00-00%');
  1199. });
  1200. })
  1201. ->column('scydgy_id');
  1202. if (is_array($poIds)) {
  1203. foreach ($poIds as $pid) {
  1204. $k = (int)$pid;
  1205. if ($k !== 0) {
  1206. $hideSet[$k] = true;
  1207. }
  1208. }
  1209. }
  1210. } catch (\Throwable $e) {
  1211. }
  1212. try {
  1213. $detIdsQuery = Db::table('purchase_order_detail');
  1214. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1215. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1216. if (is_array($detIds)) {
  1217. foreach ($detIds as $pid) {
  1218. $k = (int)$pid;
  1219. if ($this->isValidScydgyRowId($k)) {
  1220. $hideSet[$k] = true;
  1221. }
  1222. }
  1223. }
  1224. } catch (\Throwable $e) {
  1225. }
  1226. $this->pickHiddenScydgySetCache = $hideSet;
  1227. return $hideSet;
  1228. }
  1229. /**
  1230. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1231. *
  1232. * @return array<int, array<string, mixed>>
  1233. */
  1234. protected function loadPickManualOrderRows(): array
  1235. {
  1236. try {
  1237. $dbRows = Db::table('purchase_order')
  1238. ->where('scydgy_id', '<', 0)
  1239. ->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%\')')
  1240. ->order('scydgy_id', 'asc')
  1241. ->select();
  1242. } catch (\Throwable $e) {
  1243. try {
  1244. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1245. } catch (\Throwable $e2) {
  1246. return [];
  1247. }
  1248. }
  1249. if (!is_array($dbRows) || $dbRows === []) {
  1250. return [];
  1251. }
  1252. $detailSidSet = [];
  1253. try {
  1254. $negIds = [];
  1255. foreach ($dbRows as $dbRow) {
  1256. if (!is_array($dbRow)) {
  1257. continue;
  1258. }
  1259. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1260. if ($sid < 0) {
  1261. $negIds[$sid] = true;
  1262. }
  1263. }
  1264. if ($negIds !== []) {
  1265. $detQuery = Db::table('purchase_order_detail')
  1266. ->where('scydgy_id', 'in', array_keys($negIds));
  1267. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1268. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1269. if (is_array($detRows)) {
  1270. foreach ($detRows as $did) {
  1271. $detailSidSet[(int)$did] = true;
  1272. }
  1273. }
  1274. }
  1275. } catch (\Throwable $e) {
  1276. }
  1277. $pool = [];
  1278. foreach ($dbRows as $dbRow) {
  1279. if (!is_array($dbRow)) {
  1280. continue;
  1281. }
  1282. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1283. if ($sid >= 0) {
  1284. continue;
  1285. }
  1286. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1287. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1288. continue;
  1289. }
  1290. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1291. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1292. continue;
  1293. }
  1294. if (isset($detailSidSet[$sid])) {
  1295. continue;
  1296. }
  1297. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1298. $r['_is_manual'] = 1;
  1299. $pool[] = $r;
  1300. }
  1301. return $pool;
  1302. }
  1303. /**
  1304. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1305. */
  1306. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1307. {
  1308. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1309. foreach ($keys as $k) {
  1310. $t = trim((string)($row[$k] ?? ''));
  1311. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1312. return $t;
  1313. }
  1314. }
  1315. return '';
  1316. }
  1317. /**
  1318. * 分配手工新增工序行 ID(负数递减)
  1319. */
  1320. protected function allocateManualScydgyId(): int
  1321. {
  1322. try {
  1323. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1324. $min = (int)$min;
  1325. return $min < 0 ? $min - 1 : -1;
  1326. } catch (\Throwable $e) {
  1327. return -1;
  1328. }
  1329. }
  1330. /**
  1331. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1332. */
  1333. protected function allocateManualOrderCcydh(): string
  1334. {
  1335. $prefix = 'YW' . date('Ymd');
  1336. $maxSeq = 0;
  1337. try {
  1338. $rows = Db::table('purchase_order')
  1339. ->where('CCYDH', 'like', $prefix . '%')
  1340. ->column('CCYDH');
  1341. if (is_array($rows)) {
  1342. foreach ($rows as $ccydh) {
  1343. $ccydh = trim((string)$ccydh);
  1344. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1345. $maxSeq = max($maxSeq, (int)$m[1]);
  1346. }
  1347. }
  1348. }
  1349. } catch (\Throwable $e) {
  1350. }
  1351. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1352. }
  1353. /**
  1354. * purchase_order.mod_rq 是否有有效软删除时间
  1355. */
  1356. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1357. {
  1358. $t = trim((string)$modRq);
  1359. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1360. }
  1361. /**
  1362. * 列表行 → purchase_order 写入字段
  1363. *
  1364. * @return array<string, mixed>
  1365. */
  1366. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1367. {
  1368. return [
  1369. 'scydgy_id' => $scydgyId,
  1370. 'CCYDH' => $row['CCYDH'] ?? null,
  1371. 'CYJMC' => $row['CYJMC'] ?? null,
  1372. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1373. 'CDXMC' => $row['CDXMC'] ?? null,
  1374. 'CGYBH' => $row['CGYBH'] ?? null,
  1375. 'CGYMC' => $row['CGYMC'] ?? null,
  1376. 'CDW' => $row['CDW'] ?? null,
  1377. 'NGZL' => $row['NGZL'] ?? null,
  1378. 'CDF' => $row['CDF'] ?? null,
  1379. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1380. 'MBZ' => $row['MBZ'] ?? null,
  1381. 'bwjg' => $row['bwjg'] ?? null,
  1382. 'iStatus' => $row['iStatus'] ?? null,
  1383. 'dStamp' => $row['dStamp'] ?? null,
  1384. 'dputrecord' => $row['dputrecord'] ?? null,
  1385. 'cywyxm' => $row['cywyxm'] ?? null,
  1386. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1387. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1388. ];
  1389. }
  1390. /**
  1391. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1392. */
  1393. protected function softDeleteProcuremenPickRow(array $row): void
  1394. {
  1395. $sid = $this->extractScydgyRowId($row);
  1396. if (!$this->isValidScydgyRowId($sid)) {
  1397. throw new \InvalidArgumentException('无效的行主键');
  1398. }
  1399. $hideSet = $this->loadPickHiddenScydgySet();
  1400. if ($sid > 0 && isset($hideSet[$sid])) {
  1401. throw new \InvalidArgumentException('订单号「' . trim((string)($row['CCYDH'] ?? '')) . '」已下发或已进入后续流程,无法删除');
  1402. }
  1403. if ($sid < 0) {
  1404. try {
  1405. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1406. if (is_array($po)) {
  1407. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1408. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1409. }
  1410. if ($this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1411. return;
  1412. }
  1413. }
  1414. } catch (\InvalidArgumentException $e) {
  1415. throw $e;
  1416. } catch (\Throwable $e) {
  1417. }
  1418. }
  1419. $now = date('Y-m-d H:i:s');
  1420. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1421. if (is_array($exists)) {
  1422. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1423. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1424. } else {
  1425. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1426. $data['mod_rq'] = $now;
  1427. $data['createtime'] = $now;
  1428. Db::table('purchase_order')->insert($data);
  1429. $poIdLog = (int)Db::getLastInsID();
  1430. }
  1431. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1432. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1433. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1434. if ($gymcLog !== '') {
  1435. $logTail .= ' / ' . $gymcLog;
  1436. }
  1437. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1438. }
  1439. /**
  1440. * 手工新增协助工序(写入 purchase_order)
  1441. *
  1442. * @param array<string, mixed> $params
  1443. * @return int scydgy_id
  1444. */
  1445. protected function saveManualPickOrder(array $params): int
  1446. {
  1447. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1448. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1449. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1450. if ($ccydh === '') {
  1451. $ccydh = $this->allocateManualOrderCcydh();
  1452. }
  1453. $now = date('Y-m-d H:i:s');
  1454. $sid = $this->allocateManualScydgyId();
  1455. $data = [
  1456. 'scydgy_id' => $sid,
  1457. 'CCYDH' => $ccydh,
  1458. 'CYJMC' => $cyjmc,
  1459. 'CGYMC' => $cgymc,
  1460. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1461. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1462. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1463. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1464. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1465. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1466. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1467. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1468. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1469. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1470. 'createtime' => $now,
  1471. 'dStamp' => $now,
  1472. 'dputrecord' => $now,
  1473. ];
  1474. Db::table('purchase_order')->insert($data);
  1475. $poId = (int)Db::getLastInsID();
  1476. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1477. return $sid;
  1478. }
  1479. protected function formatProcuremenRowLabel(array $row): string
  1480. {
  1481. $dh = trim((string)($row['CCYDH'] ?? ''));
  1482. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1483. if ($dh !== '' && $gymc !== '') {
  1484. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1485. }
  1486. if ($dh !== '') {
  1487. return '订单「' . $dh . '」';
  1488. }
  1489. if ($gymc !== '') {
  1490. return '工序「' . $gymc . '」';
  1491. }
  1492. $id = $this->extractScydgyRowId($row);
  1493. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1494. }
  1495. /**
  1496. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1497. */
  1498. protected function extractScydgyRowId(array $row): int
  1499. {
  1500. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1501. }
  1502. protected function isValidScydgyRowId(int $id): bool
  1503. {
  1504. return $id !== 0;
  1505. }
  1506. protected function isManualScydgyRowId(int $id): bool
  1507. {
  1508. return $id < 0;
  1509. }
  1510. /**
  1511. * 采购确认已选定供应商:明细 purchase_order_detail.status = 1 的工序行 scydgy_id 集合
  1512. *
  1513. * @return array<int, true>
  1514. */
  1515. protected function loadScydgyIdsWithPickedSupplierDetail(): array
  1516. {
  1517. $set = [];
  1518. try {
  1519. $rows = Db::table('purchase_order_detail')->whereIn('status', ProcuremenStatus::podPickedValues())->field('scydgy_id')->select();
  1520. } catch (\Throwable $e) {
  1521. $rows = [];
  1522. }
  1523. if (!is_array($rows)) {
  1524. return $set;
  1525. }
  1526. foreach ($rows as $r) {
  1527. if (!is_array($r)) {
  1528. continue;
  1529. }
  1530. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1531. if ($sid > 0) {
  1532. $set[$sid] = true;
  1533. }
  1534. }
  1535. return $set;
  1536. }
  1537. /**
  1538. * 每个工序行对应已选中供应商名称(取 status=1 的首条明细 company_name)
  1539. *
  1540. * @param int[] $scydgyIds
  1541. * @return array<int, string> scydgy_id => company_name
  1542. */
  1543. protected function loadPickedSupplierCompanyByScydgyIds(array $scydgyIds): array
  1544. {
  1545. $out = [];
  1546. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1547. if ($scydgyIds === []) {
  1548. return $out;
  1549. }
  1550. try {
  1551. $rows = Db::table('purchase_order_detail')
  1552. ->where('scydgy_id', 'in', $scydgyIds)
  1553. ->whereIn('status', ProcuremenStatus::podPickedValues())
  1554. ->field('scydgy_id,company_name')
  1555. ->order('id', 'asc')
  1556. ->select();
  1557. } catch (\Throwable $e) {
  1558. try {
  1559. $rows = Db::table('purchase_order_detail')
  1560. ->where('scydgy_id', 'in', $scydgyIds)
  1561. ->whereIn('status', ProcuremenStatus::podPickedValues())
  1562. ->field('scydgy_id,company_name')
  1563. ->order('ID', 'asc')
  1564. ->select();
  1565. } catch (\Throwable $e2) {
  1566. $rows = [];
  1567. }
  1568. }
  1569. if (!is_array($rows)) {
  1570. return $out;
  1571. }
  1572. foreach ($rows as $r) {
  1573. if (!is_array($r)) {
  1574. continue;
  1575. }
  1576. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1577. if (!$this->isValidScydgyRowId($sid) || isset($out[$sid])) {
  1578. continue;
  1579. }
  1580. $name = trim((string)($r['company_name'] ?? ''));
  1581. $out[$sid] = $name;
  1582. }
  1583. return $out;
  1584. }
  1585. /**
  1586. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1587. *
  1588. * @param int[] $scydgyIds
  1589. * @return array<int, string[]>
  1590. */
  1591. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1592. {
  1593. $out = [];
  1594. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1595. if ($scydgyIds === []) {
  1596. return $out;
  1597. }
  1598. try {
  1599. $rows = Db::table('purchase_order_detail')
  1600. ->where('scydgy_id', 'in', $scydgyIds)
  1601. ->field('scydgy_id,company_name')
  1602. ->order('company_name', 'asc')
  1603. ->select();
  1604. } catch (\Throwable $e) {
  1605. $rows = [];
  1606. }
  1607. if (!is_array($rows)) {
  1608. return $out;
  1609. }
  1610. foreach ($rows as $r) {
  1611. if (!is_array($r)) {
  1612. continue;
  1613. }
  1614. $sid = (int)($r['scydgy_id'] ?? 0);
  1615. $cn = trim((string)($r['company_name'] ?? ''));
  1616. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1617. continue;
  1618. }
  1619. if (!isset($out[$sid])) {
  1620. $out[$sid] = [];
  1621. }
  1622. if (!in_array($cn, $out[$sid], true)) {
  1623. $out[$sid][] = $cn;
  1624. }
  1625. }
  1626. return $out;
  1627. }
  1628. /**
  1629. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1630. *
  1631. * @param string[] $names
  1632. */
  1633. protected function formatNotifySupplierDisplay(array $names): string
  1634. {
  1635. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1636. return trim((string)$n);
  1637. }, $names))));
  1638. if ($names === []) {
  1639. return '';
  1640. }
  1641. sort($names, SORT_STRING);
  1642. return implode('、', $names);
  1643. }
  1644. /**
  1645. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1646. *
  1647. * @param int[] $scydgyIds
  1648. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1649. */
  1650. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1651. {
  1652. $out = [];
  1653. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1654. if ($scydgyIds === []) {
  1655. return $out;
  1656. }
  1657. try {
  1658. $rows = Db::table('purchase_order_detail')
  1659. ->where('scydgy_id', 'in', $scydgyIds)
  1660. ->field('scydgy_id,company_name,amount')
  1661. ->select();
  1662. } catch (\Throwable $e) {
  1663. $rows = [];
  1664. }
  1665. if (!is_array($rows)) {
  1666. return $out;
  1667. }
  1668. foreach ($rows as $r) {
  1669. if (!is_array($r)) {
  1670. continue;
  1671. }
  1672. $sid = (int)($r['scydgy_id'] ?? 0);
  1673. $cn = trim((string)($r['company_name'] ?? ''));
  1674. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1675. continue;
  1676. }
  1677. if (!isset($out[$sid])) {
  1678. $out[$sid] = ['all' => [], 'quoted' => []];
  1679. }
  1680. $out[$sid]['all'][$cn] = true;
  1681. $am = trim((string)($r['amount'] ?? ''));
  1682. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1683. $out[$sid]['quoted'][$cn] = true;
  1684. }
  1685. }
  1686. return $out;
  1687. }
  1688. /**
  1689. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1690. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1691. */
  1692. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1693. {
  1694. $merged = ['all' => [], 'quoted' => []];
  1695. foreach ($buckets as $b) {
  1696. if (!is_array($b)) {
  1697. continue;
  1698. }
  1699. foreach ($b['all'] ?? [] as $cn => $_) {
  1700. $merged['all'][$cn] = true;
  1701. }
  1702. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1703. $merged['quoted'][$cn] = true;
  1704. }
  1705. }
  1706. return $merged;
  1707. }
  1708. /**
  1709. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1710. */
  1711. protected function formatQuotedSupplierLines(array $bucket): string
  1712. {
  1713. $all = array_keys($bucket['all'] ?? []);
  1714. if ($all === []) {
  1715. return '';
  1716. }
  1717. sort($all, SORT_STRING);
  1718. $lines = [];
  1719. foreach ($all as $cn) {
  1720. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1721. $lines[] = $cn . '(' . $status . ')';
  1722. }
  1723. return implode("\n", $lines);
  1724. }
  1725. /**
  1726. * @param int[] $scydgyIds
  1727. * @return array<int, string>
  1728. */
  1729. protected function loadQuotedSupplierSummaryByScydgyIds(array $scydgyIds): array
  1730. {
  1731. $out = [];
  1732. foreach ($this->loadQuotedSupplierBucketByScydgyIds($scydgyIds) as $sid => $bucket) {
  1733. $text = $this->formatQuotedSupplierLines($bucket);
  1734. if ($text !== '') {
  1735. $out[$sid] = $text;
  1736. }
  1737. }
  1738. return $out;
  1739. }
  1740. /**
  1741. * 审核弹窗:按供应商汇总报价明细
  1742. *
  1743. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1744. * @return array<int, array<string, mixed>>
  1745. */
  1746. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  1747. {
  1748. $sids = [];
  1749. foreach ($bundle['pos'] ?? [] as $po) {
  1750. if (!is_array($po)) {
  1751. continue;
  1752. }
  1753. $sid = (int)($po['scydgy_id'] ?? 0);
  1754. if ($this->isValidScydgyRowId($sid)) {
  1755. $sids[$sid] = true;
  1756. }
  1757. }
  1758. if ($sids === []) {
  1759. return [];
  1760. }
  1761. $gymcMap = [];
  1762. $qtyBySid = [];
  1763. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1764. if (!is_array($mr)) {
  1765. continue;
  1766. }
  1767. $gid = $this->extractScydgyRowId($mr);
  1768. if ($this->isValidScydgyRowId($gid)) {
  1769. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1770. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1771. if ($qty === '') {
  1772. $qty = trim((string)($mr['NGZL'] ?? ''));
  1773. }
  1774. $qtyBySid[$gid] = $qty;
  1775. }
  1776. }
  1777. foreach ($bundle['pos'] ?? [] as $po) {
  1778. if (!is_array($po)) {
  1779. continue;
  1780. }
  1781. $gid = (int)($po['scydgy_id'] ?? 0);
  1782. if ($this->isValidScydgyRowId($gid)) {
  1783. $nm = trim((string)($po['CGYMC'] ?? ''));
  1784. if ($nm !== '') {
  1785. $gymcMap[$gid] = $nm;
  1786. }
  1787. }
  1788. }
  1789. try {
  1790. $detailsQuery = Db::table('purchase_order_detail')
  1791. ->where('scydgy_id', 'in', array_keys($sids));
  1792. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1793. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  1794. } catch (\Throwable $e) {
  1795. try {
  1796. $detailsQuery = Db::table('purchase_order_detail')
  1797. ->where('scydgy_id', 'in', array_keys($sids));
  1798. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1799. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  1800. } catch (\Throwable $e2) {
  1801. $details = [];
  1802. }
  1803. }
  1804. if (!is_array($details)) {
  1805. $details = [];
  1806. }
  1807. $byCompany = [];
  1808. foreach ($details as $d) {
  1809. if (!is_array($d)) {
  1810. continue;
  1811. }
  1812. $cn = trim((string)($d['company_name'] ?? ''));
  1813. if ($cn === '') {
  1814. continue;
  1815. }
  1816. if (!isset($byCompany[$cn])) {
  1817. $ph = trim((string)($d['phone'] ?? ''));
  1818. $username = trim((string)($d['username'] ?? ''));
  1819. if ($username === '') {
  1820. $username = $this->resolveCustomerContactName($ph, $cn);
  1821. }
  1822. $byCompany[$cn] = [
  1823. 'name' => $cn,
  1824. 'email' => trim((string)($d['email'] ?? '')),
  1825. 'phone' => $ph,
  1826. 'username' => $username,
  1827. 'has_quote' => false,
  1828. 'lines' => [],
  1829. ];
  1830. }
  1831. $sid = (int)($d['scydgy_id'] ?? 0);
  1832. $am = trim((string)($d['amount'] ?? ''));
  1833. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1834. if ($gymc === '') {
  1835. $gymc = '工序';
  1836. }
  1837. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1838. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1839. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1840. $deliveryShow = $deliveryRaw;
  1841. }
  1842. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1843. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1844. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1845. $subtotal = null;
  1846. if ($amountNum !== null) {
  1847. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1848. }
  1849. $unitPriceText = $amountFilled
  1850. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1851. : '未填写';
  1852. $byCompany[$cn]['lines'][] = [
  1853. 'cgymc' => $gymc,
  1854. 'amount' => $am,
  1855. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  1856. 'amount_filled' => $amountFilled,
  1857. 'unit_price_text' => $unitPriceText,
  1858. 'delivery' => $deliveryRaw,
  1859. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  1860. 'delivery_filled' => $deliveryFilled,
  1861. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  1862. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1863. 'subtotal_num' => $subtotal,
  1864. 'status_name' => trim((string)($d['status_name'] ?? '')),
  1865. 'is_quoted' => $amountFilled,
  1866. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  1867. ];
  1868. }
  1869. foreach ($byCompany as $cn => $g) {
  1870. $total = count($g['lines']);
  1871. $quoted = 0;
  1872. $groupTotal = 0.0;
  1873. $groupHasTotal = false;
  1874. foreach ($g['lines'] as $ln) {
  1875. $am = trim((string)($ln['amount'] ?? ''));
  1876. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1877. $quoted++;
  1878. }
  1879. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1880. $groupTotal += (float)$ln['subtotal_num'];
  1881. $groupHasTotal = true;
  1882. }
  1883. }
  1884. $byCompany[$cn]['has_quote'] = $total > 0 && $quoted === $total;
  1885. $byCompany[$cn]['line_count'] = $total;
  1886. $byCompany[$cn]['has_total'] = $total > 0;
  1887. $byCompany[$cn]['total_text'] = $groupHasTotal ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1888. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  1889. }
  1890. return array_values($byCompany);
  1891. }
  1892. /**
  1893. * 确认供应商弹窗:通知对象(不含报价,仅工序与联系方式)
  1894. *
  1895. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1896. * @return array<int, array<string, mixed>>
  1897. */
  1898. protected function loadAuditSupplierNotifyGroups(array $bundle): array
  1899. {
  1900. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  1901. $out = [];
  1902. foreach ($groups as $g) {
  1903. if (!is_array($g)) {
  1904. continue;
  1905. }
  1906. $processNames = [];
  1907. foreach ($g['lines'] ?? [] as $ln) {
  1908. if (!is_array($ln)) {
  1909. continue;
  1910. }
  1911. $n = trim((string)($ln['cgymc'] ?? ''));
  1912. if ($n !== '' && !in_array($n, $processNames, true)) {
  1913. $processNames[] = $n;
  1914. }
  1915. }
  1916. $out[] = [
  1917. 'name' => trim((string)($g['name'] ?? '')),
  1918. 'email' => trim((string)($g['email'] ?? '')),
  1919. 'phone' => trim((string)($g['phone'] ?? '')),
  1920. 'username' => trim((string)($g['username'] ?? '')),
  1921. 'process_names' => $processNames,
  1922. 'process_text' => implode('、', $processNames),
  1923. ];
  1924. }
  1925. return $out;
  1926. }
  1927. /**
  1928. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  1929. *
  1930. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1931. * @return array<int, array<string, mixed>>
  1932. */
  1933. protected function loadConfirmSupplierPickGroups(array $bundle): array
  1934. {
  1935. $sids = [];
  1936. $poIdMap = [];
  1937. foreach ($bundle['pos'] ?? [] as $po) {
  1938. if (!is_array($po)) {
  1939. continue;
  1940. }
  1941. $sid = (int)($po['scydgy_id'] ?? 0);
  1942. if ($this->isValidScydgyRowId($sid)) {
  1943. $sids[$sid] = true;
  1944. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  1945. }
  1946. }
  1947. if ($sids === []) {
  1948. return [];
  1949. }
  1950. $gymcMap = [];
  1951. $qtyBySid = [];
  1952. $orderedSids = [];
  1953. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1954. if (!is_array($mr)) {
  1955. continue;
  1956. }
  1957. $gid = $this->extractScydgyRowId($mr);
  1958. if ($this->isValidScydgyRowId($gid)) {
  1959. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1960. $orderedSids[] = $gid;
  1961. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1962. if ($qty === '') {
  1963. $qty = trim((string)($mr['NGZL'] ?? ''));
  1964. }
  1965. $qtyBySid[$gid] = $qty;
  1966. }
  1967. }
  1968. foreach ($bundle['pos'] ?? [] as $po) {
  1969. if (!is_array($po)) {
  1970. continue;
  1971. }
  1972. $gid = (int)($po['scydgy_id'] ?? 0);
  1973. if ($this->isValidScydgyRowId($gid)) {
  1974. $nm = trim((string)($po['CGYMC'] ?? ''));
  1975. if ($nm !== '') {
  1976. $gymcMap[$gid] = $nm;
  1977. }
  1978. }
  1979. }
  1980. try {
  1981. $details = Db::table('purchase_order_detail')
  1982. ->where('scydgy_id', 'in', array_keys($sids))
  1983. ->order('company_name', 'asc')
  1984. ->order('id', 'asc')
  1985. ->select();
  1986. } catch (\Throwable $e) {
  1987. try {
  1988. $details = Db::table('purchase_order_detail')
  1989. ->where('scydgy_id', 'in', array_keys($sids))
  1990. ->order('company_name', 'asc')
  1991. ->order('ID', 'asc')
  1992. ->select();
  1993. } catch (\Throwable $e2) {
  1994. $details = [];
  1995. }
  1996. }
  1997. if (!is_array($details)) {
  1998. $details = [];
  1999. }
  2000. $byCompany = [];
  2001. foreach ($details as $d) {
  2002. if (!is_array($d)) {
  2003. continue;
  2004. }
  2005. $cn = trim((string)($d['company_name'] ?? ''));
  2006. if ($cn === '') {
  2007. continue;
  2008. }
  2009. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2010. $sid = (int)($d['scydgy_id'] ?? 0);
  2011. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2012. continue;
  2013. }
  2014. if (!isset($byCompany[$cn])) {
  2015. $ph = trim((string)($d['phone'] ?? ''));
  2016. $username = trim((string)($d['username'] ?? ''));
  2017. if ($username === '') {
  2018. $username = $this->resolveCustomerContactName($ph, $cn);
  2019. }
  2020. $byCompany[$cn] = [
  2021. 'name' => $cn,
  2022. 'email' => trim((string)($d['email'] ?? '')),
  2023. 'phone' => $ph,
  2024. 'username' => $username,
  2025. 'pick_lines' => [],
  2026. 'detail_picks' => [],
  2027. ];
  2028. }
  2029. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2030. if ($gymc === '') {
  2031. $gymc = '工序';
  2032. }
  2033. $am = trim((string)($d['amount'] ?? ''));
  2034. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2035. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2036. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2037. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2038. $deliveryShow = $deliveryRaw;
  2039. }
  2040. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2041. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2042. $subtotal = null;
  2043. if ($amountNum !== null) {
  2044. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2045. }
  2046. $unitPriceText = $amountFilled
  2047. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2048. : '未填写';
  2049. $byCompany[$cn]['pick_lines'][$sid] = [
  2050. 'cgymc' => $gymc,
  2051. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2052. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2053. 'amount_filled' => $amountFilled,
  2054. 'delivery_filled' => $deliveryFilled,
  2055. 'unit_price_text' => $unitPriceText,
  2056. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2057. 'subtotal_num' => $subtotal,
  2058. 'is_quoted' => $amountFilled,
  2059. ];
  2060. $byCompany[$cn]['detail_picks'][$sid] = [
  2061. 'scydgy_id' => $sid,
  2062. 'detail_id' => $detailId,
  2063. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2064. 'cgymc' => $gymc,
  2065. ];
  2066. }
  2067. $out = [];
  2068. foreach ($byCompany as $g) {
  2069. $pickLinesMap = $g['pick_lines'] ?? [];
  2070. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2071. continue;
  2072. }
  2073. $pickLines = [];
  2074. $usedLineSids = [];
  2075. foreach ($orderedSids as $sid) {
  2076. if (!isset($pickLinesMap[$sid])) {
  2077. continue;
  2078. }
  2079. $pickLines[] = $pickLinesMap[$sid];
  2080. $usedLineSids[$sid] = true;
  2081. }
  2082. foreach ($pickLinesMap as $sid => $ln) {
  2083. if (isset($usedLineSids[$sid])) {
  2084. continue;
  2085. }
  2086. $pickLines[] = $ln;
  2087. }
  2088. $groupTotal = 0.0;
  2089. $groupHasTotal = false;
  2090. foreach ($pickLines as $ln) {
  2091. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2092. $groupTotal += (float)$ln['subtotal_num'];
  2093. $groupHasTotal = true;
  2094. }
  2095. }
  2096. $lineCount = count($pickLines);
  2097. $g['pick_lines'] = $pickLines;
  2098. $g['line_count'] = $lineCount;
  2099. $g['has_total'] = $lineCount > 0;
  2100. $g['total_text'] = $groupHasTotal ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2101. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  2102. $detailPicks = $g['detail_picks'] ?? [];
  2103. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  2104. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2105. unset($g['detail_picks']);
  2106. $out[] = $g;
  2107. }
  2108. return $out;
  2109. }
  2110. /**
  2111. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2112. * @return array<int, int[]> scydgy_id => detail_id[]
  2113. */
  2114. protected function mapDetailIdsByScydgyId(array $details): array
  2115. {
  2116. $out = [];
  2117. foreach ($details as $d) {
  2118. if (!is_array($d)) {
  2119. continue;
  2120. }
  2121. $sid = (int)($d['scydgy_id'] ?? 0);
  2122. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2123. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2124. continue;
  2125. }
  2126. if (!isset($out[$sid])) {
  2127. $out[$sid] = [];
  2128. }
  2129. $out[$sid][] = $pk;
  2130. }
  2131. foreach ($out as $sid => $ids) {
  2132. $out[$sid] = array_values(array_unique($ids));
  2133. }
  2134. return $out;
  2135. }
  2136. /**
  2137. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2138. *
  2139. * @param array<string, mixed> $dbRow
  2140. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2141. */
  2142. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2143. {
  2144. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2145. $r = [
  2146. 'ID' => $sid,
  2147. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2148. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2149. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2150. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2151. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2152. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2153. 'CDW' => $dbRow['CDW'] ?? '',
  2154. 'NGZL' => $dbRow['NGZL'] ?? '',
  2155. 'CDF' => $dbRow['CDF'] ?? '',
  2156. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2157. 'MBZ' => $dbRow['MBZ'] ?? '',
  2158. 'bwjg' => $dbRow['bwjg'] ?? '',
  2159. 'iStatus' => $dbRow['iStatus'] ?? '',
  2160. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2161. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2162. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2163. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2164. 'dStamp' => $dbRow['dStamp'] ?? '',
  2165. 'pick_time' => $dbRow['pick_time'] ?? '',
  2166. ];
  2167. if ($sid > 0 && isset($dStampMap[$sid])) {
  2168. $t = trim((string)$dStampMap[$sid]);
  2169. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2170. $r['dStamp'] = $dStampMap[$sid];
  2171. }
  2172. }
  2173. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2174. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2175. $ct = $dbRow['createtime'];
  2176. if (is_numeric($ct) && (int)$ct > 946684800) {
  2177. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2178. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2179. $r['dStamp'] = trim($ct);
  2180. }
  2181. }
  2182. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2183. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2184. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2185. $fallback = trim((string)($r['dStamp'] ?? ''));
  2186. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2187. $r['dputrecord'] = $fallback;
  2188. }
  2189. }
  2190. if (array_key_exists('id', $dbRow)) {
  2191. $r['purchase_order_id'] = (int)$dbRow['id'];
  2192. }
  2193. if ($sid < 0) {
  2194. $r['_is_manual'] = 1;
  2195. }
  2196. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2197. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2198. if ($pickNm !== '') {
  2199. $r['pick_company_name'] = $pickNm;
  2200. $r['picked_supplier_name'] = $pickNm;
  2201. }
  2202. return $r;
  2203. }
  2204. /**
  2205. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2206. *
  2207. * @return array<int, array<string, mixed>>
  2208. */
  2209. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2210. {
  2211. $pool = [];
  2212. if (!is_array($dbRows) || $dbRows === []) {
  2213. return $pool;
  2214. }
  2215. $dStampMap = [];
  2216. $sidList = [];
  2217. foreach ($dbRows as $tmpRow) {
  2218. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2219. $sid = (int)$tmpRow['scydgy_id'];
  2220. if ($sid > 0) {
  2221. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2222. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2223. $sidList[$sid] = true;
  2224. }
  2225. }
  2226. }
  2227. }
  2228. if ($sidList !== []) {
  2229. try {
  2230. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2231. } catch (\Throwable $e) {
  2232. $dStampMap = [];
  2233. }
  2234. }
  2235. foreach ($dbRows as $dbRow) {
  2236. if (!is_array($dbRow)) {
  2237. continue;
  2238. }
  2239. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2240. }
  2241. return $pool;
  2242. }
  2243. /**
  2244. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2245. *
  2246. * @param int[] $scydgyIds
  2247. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2248. */
  2249. protected function OrderDetailSummary(array $scydgyIds)
  2250. {
  2251. $out = [];
  2252. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2253. if ($scydgyIds === []) {
  2254. return $out;
  2255. }
  2256. $list = [];
  2257. try {
  2258. $list = Db::table('purchase_order_detail')
  2259. ->where('scydgy_id', 'in', $scydgyIds)
  2260. ->field('id,scydgy_id,amount,delivery')
  2261. ->select();
  2262. } catch (\Throwable $e) {
  2263. $list = [];
  2264. }
  2265. if (!is_array($list)) {
  2266. return $out;
  2267. }
  2268. foreach ($list as $r) {
  2269. if (!is_array($r)) {
  2270. continue;
  2271. }
  2272. $ids = (int)($r['scydgy_id'] ?? 0);
  2273. if (!$this->isValidScydgyRowId($ids)) {
  2274. continue;
  2275. }
  2276. if (!isset($out[$ids])) {
  2277. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2278. }
  2279. $out[$ids]['cnt']++;
  2280. $am = $r['amount'] ?? null;
  2281. if ($am !== null && $am !== '') {
  2282. if (!(is_string($am) && trim($am) === '')) {
  2283. $out[$ids]['amt']++;
  2284. }
  2285. }
  2286. $dv = $r['delivery'] ?? null;
  2287. if ($dv !== null && trim((string)$dv) !== '') {
  2288. $out[$ids]['deliv']++;
  2289. }
  2290. }
  2291. return $out;
  2292. }
  2293. /**
  2294. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2295. *
  2296. * @return array
  2297. */
  2298. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2299. {
  2300. $strContains = function ($haystack, $needle) {
  2301. if ($needle === '') {
  2302. return false;
  2303. }
  2304. $haystack = (string)$haystack;
  2305. if (function_exists('mb_stripos')) {
  2306. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2307. }
  2308. return stripos($haystack, $needle) !== false;
  2309. };
  2310. $stripAlias = function ($f) {
  2311. return preg_replace('/^[ab]\./i', '', (string)$f);
  2312. };
  2313. $searchColNames = [];
  2314. foreach (explode(',', $this->searchFields) as $colRaw) {
  2315. $c = $stripAlias(trim($colRaw));
  2316. if ($c !== '') {
  2317. $searchColNames[] = $c;
  2318. }
  2319. }
  2320. $filtered = [];
  2321. foreach ($pool as $r) {
  2322. if (!is_array($r)) {
  2323. continue;
  2324. }
  2325. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2326. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2327. if (!$isManual) {
  2328. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2329. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2330. continue;
  2331. }
  2332. if ($applyMonthRange) {
  2333. $mo = (int)$m[2];
  2334. if ($mo < 1 || $mo > 12) {
  2335. continue;
  2336. }
  2337. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2338. $rowMonthStart = $ymRow . '-01 00:00:00';
  2339. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2340. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2341. continue;
  2342. }
  2343. }
  2344. } elseif ($applyMonthRange) {
  2345. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2346. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2347. $ds = $listTime;
  2348. }
  2349. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2350. continue;
  2351. }
  2352. $mo = (int)$m[2];
  2353. if ($mo < 1 || $mo > 12) {
  2354. continue;
  2355. }
  2356. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2357. $rowMonthStart = $ymRow . '-01 00:00:00';
  2358. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2359. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2360. continue;
  2361. }
  2362. }
  2363. if ($search !== '') {
  2364. $hitSearch = false;
  2365. foreach ($searchColNames as $c) {
  2366. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2367. if ($cell !== '' && $strContains($cell, $search)) {
  2368. $hitSearch = true;
  2369. break;
  2370. }
  2371. }
  2372. if (!$hitSearch) {
  2373. continue;
  2374. }
  2375. }
  2376. foreach ($filterArr as $fk => $fv) {
  2377. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2378. continue;
  2379. }
  2380. if (is_array($fv)) {
  2381. continue;
  2382. }
  2383. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2384. continue;
  2385. }
  2386. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2387. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2388. $field = $stripAlias($fk);
  2389. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2390. $cellStr = trim((string)$cell);
  2391. switch ($sym) {
  2392. case '=':
  2393. if ((string)$cell !== (string)$fv) {
  2394. continue 3;
  2395. }
  2396. break;
  2397. case '<>':
  2398. if ((string)$cell === (string)$fv) {
  2399. continue 3;
  2400. }
  2401. break;
  2402. case 'LIKE':
  2403. case 'NOT LIKE':
  2404. $needle = trim((string)$fv);
  2405. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2406. if ($sym === 'LIKE' && !$hit) {
  2407. continue 3;
  2408. }
  2409. if ($sym === 'NOT LIKE' && $hit) {
  2410. continue 3;
  2411. }
  2412. break;
  2413. case '>':
  2414. case '>=':
  2415. case '<':
  2416. case '<=':
  2417. if (!is_numeric($cell) && $cellStr === '') {
  2418. continue 3;
  2419. }
  2420. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2421. $vv = (float)$fv;
  2422. if ($sym === '>' && !($cv > $vv)) {
  2423. continue 3;
  2424. }
  2425. if ($sym === '>=' && !($cv >= $vv)) {
  2426. continue 3;
  2427. }
  2428. if ($sym === '<' && !($cv < $vv)) {
  2429. continue 3;
  2430. }
  2431. if ($sym === '<=' && !($cv <= $vv)) {
  2432. continue 3;
  2433. }
  2434. break;
  2435. case 'RANGE':
  2436. case 'NOT RANGE':
  2437. case 'BETWEEN':
  2438. case 'NOT BETWEEN':
  2439. case 'BETWEEN TIME':
  2440. case 'NOT BETWEEN TIME':
  2441. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2442. $rawR = str_replace(' - ', ',', $rawR);
  2443. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2444. if (count($arr) < 2) {
  2445. break;
  2446. }
  2447. $lo = $arr[0];
  2448. $hi = $arr[1];
  2449. if ($lo === '' && $hi === '') {
  2450. break;
  2451. }
  2452. $isNot = (strpos($sym, 'NOT') !== false);
  2453. if ($lo === '') {
  2454. $in = ($cellStr !== '' && $cellStr <= $hi);
  2455. if ($isNot ? $in : !$in) {
  2456. continue 3;
  2457. }
  2458. break;
  2459. }
  2460. if ($hi === '') {
  2461. $in = ($cellStr !== '' && $cellStr >= $lo);
  2462. if ($isNot ? $in : !$in) {
  2463. continue 3;
  2464. }
  2465. break;
  2466. }
  2467. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2468. if ($isNot ? $in : !$in) {
  2469. continue 3;
  2470. }
  2471. break;
  2472. case 'NULL':
  2473. case 'IS NULL':
  2474. if ($cell !== null && $cell !== '') {
  2475. continue 3;
  2476. }
  2477. break;
  2478. case 'NOT NULL':
  2479. case 'IS NOT NULL':
  2480. if ($cell === null || $cell === '') {
  2481. continue 3;
  2482. }
  2483. break;
  2484. default:
  2485. break;
  2486. }
  2487. }
  2488. $filtered[] = $r;
  2489. }
  2490. return $filtered;
  2491. }
  2492. /**
  2493. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2494. */
  2495. public function snapshotToProcure()
  2496. {
  2497. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2498. $this->error(__('Invalid parameters'));
  2499. }
  2500. $row = json_decode($this->request->post('row_json', ''), true);
  2501. if (!is_array($row)) {
  2502. $this->error(__('Invalid parameters'));
  2503. }
  2504. try {
  2505. $ids = $this->extractScydgyRowId($row);
  2506. if (!$this->isValidScydgyRowId($ids)) {
  2507. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2508. }
  2509. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2510. $data = [
  2511. 'scydgy_id' => $ids,
  2512. 'CCYDH' => $row['CCYDH'] ?? null,
  2513. 'CYJMC' => $row['CYJMC'] ?? null,
  2514. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2515. 'CDXMC' => $row['CDXMC'] ?? null,
  2516. 'CGYBH' => $row['CGYBH'] ?? null,
  2517. 'CGYMC' => $row['CGYMC'] ?? null,
  2518. 'CDW' => $row['CDW'] ?? null,
  2519. 'NGZL' => $row['NGZL'] ?? null,
  2520. 'CDF' => $row['CDF'] ?? null,
  2521. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2522. 'MBZ' => $row['MBZ'] ?? null,
  2523. 'bwjg' => $row['bwjg'] ?? null,
  2524. 'iStatus' => $row['iStatus'] ?? null,
  2525. 'dStamp' => $row['dStamp'] ?? null,
  2526. 'dputrecord' => $row['dputrecord'] ?? null,
  2527. 'cywyxm' => $row['cywyxm'] ?? null,
  2528. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2529. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2530. ];
  2531. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  2532. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  2533. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  2534. $this->success('操作成功');
  2535. return;
  2536. }
  2537. if ($exists) {
  2538. $upd = $data;
  2539. unset($upd['scydgy_id'], $upd['status']);
  2540. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2541. } else {
  2542. // 新增:不写 status(空/走库默认);仅写创建时间
  2543. $data['createtime'] = date('Y-m-d H:i:s');
  2544. Db::table('purchase_order')->insert($data);
  2545. }
  2546. } catch (\Throwable $e) {
  2547. $this->error($e->getMessage());
  2548. }
  2549. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  2550. $this->success('操作成功');
  2551. }
  2552. /**
  2553. * 未发列表
  2554. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  2555. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  2556. */
  2557. public function completeDirectly()
  2558. {
  2559. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2560. $this->error(__('参数错误'));
  2561. }
  2562. if (!$this->procuremenCanComplete()) {
  2563. $this->error(__('You have no permission'));
  2564. }
  2565. $row = json_decode($this->request->post('row_json', ''), true);
  2566. if (!is_array($row)) {
  2567. $this->error(__('Invalid parameters'));
  2568. }
  2569. $finishRaw = $this->request->post('finish', '1');
  2570. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  2571. try {
  2572. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  2573. $ids = $this->extractScydgyRowId($row);
  2574. if (!$this->isValidScydgyRowId($ids)) {
  2575. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2576. }
  2577. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2578. $data = [
  2579. 'scydgy_id' => $ids,
  2580. 'CCYDH' => $row['CCYDH'] ?? null,
  2581. 'CYJMC' => $row['CYJMC'] ?? null,
  2582. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2583. 'CDXMC' => $row['CDXMC'] ?? null,
  2584. 'CGYBH' => $row['CGYBH'] ?? null,
  2585. 'CGYMC' => $row['CGYMC'] ?? null,
  2586. 'CDW' => $row['CDW'] ?? null,
  2587. 'NGZL' => $row['NGZL'] ?? null,
  2588. 'CDF' => $row['CDF'] ?? null,
  2589. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2590. 'MBZ' => $row['MBZ'] ?? null,
  2591. 'bwjg' => $row['bwjg'] ?? null,
  2592. 'iStatus' => $row['iStatus'] ?? null,
  2593. 'dStamp' => $row['dStamp'] ?? null,
  2594. 'dputrecord' => $row['dputrecord'] ?? null,
  2595. 'cywyxm' => $row['cywyxm'] ?? null,
  2596. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2597. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2598. ];
  2599. if ($asComplete) {
  2600. // 主表 status 为 varchar 时统一写 '1',档案 procuremenarchive 按 status=1 查询
  2601. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  2602. }
  2603. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  2604. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  2605. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  2606. $this->success('操作成功');
  2607. return;
  2608. }
  2609. if ($exists) {
  2610. $upd = $data;
  2611. unset($upd['scydgy_id']);
  2612. if (!$asComplete) {
  2613. unset($upd['status']);
  2614. }
  2615. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2616. } else {
  2617. // 新增:不写 status;完结时 $data 已含 status=1
  2618. $data['createtime'] = date('Y-m-d H:i:s');
  2619. Db::table('purchase_order')->insert($data);
  2620. }
  2621. } catch (\Throwable $e) {
  2622. $this->error($e->getMessage());
  2623. }
  2624. $poIdLog = null;
  2625. try {
  2626. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2627. if (is_array($rpo)) {
  2628. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2629. $poIdLog = $tid > 0 ? $tid : null;
  2630. }
  2631. } catch (\Throwable $e) {
  2632. $poIdLog = null;
  2633. }
  2634. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  2635. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  2636. if ($asComplete) {
  2637. $this->addOrderLog(
  2638. $ids,
  2639. 'mark_complete',
  2640. '点击「完结」,已标记为已完结',
  2641. $poIdLog
  2642. );
  2643. try {
  2644. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  2645. if ($pdfPublicPath === '') {
  2646. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  2647. }
  2648. } catch (\Throwable $e) {
  2649. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  2650. }
  2651. } else {
  2652. $this->addOrderLog(
  2653. $ids,
  2654. 'save_qty_price',
  2655. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  2656. $poIdLog
  2657. );
  2658. }
  2659. $this->success("操作成功");
  2660. }
  2661. /**
  2662. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  2663. *
  2664. * @param array<int, array> $rows 引用传递当前页行
  2665. */
  2666. protected function mergePurchaseOrder(array &$rows)
  2667. {
  2668. if ($rows === []) {
  2669. return;
  2670. }
  2671. $ids = [];
  2672. foreach ($rows as $rw) {
  2673. if (!is_array($rw)) {
  2674. continue;
  2675. }
  2676. $id = (int)($rw['ID'] ?? 0);
  2677. if ($id > 0) {
  2678. $ids[$id] = true;
  2679. }
  2680. }
  2681. $idList = array_keys($ids);
  2682. if ($idList === []) {
  2683. return;
  2684. }
  2685. try {
  2686. $list = Db::table('purchase_order')
  2687. ->where('scydgy_id', 'in', $idList)
  2688. ->field('scydgy_id,This_quantity,ceilingPrice')
  2689. ->select();
  2690. } catch (\Throwable $e) {
  2691. return;
  2692. }
  2693. if (!is_array($list)) {
  2694. return;
  2695. }
  2696. $byId = [];
  2697. foreach ($list as $dbRow) {
  2698. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  2699. continue;
  2700. }
  2701. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  2702. }
  2703. foreach ($rows as &$rw) {
  2704. if (!is_array($rw)) {
  2705. continue;
  2706. }
  2707. $sid = (int)($rw['ID'] ?? 0);
  2708. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  2709. continue;
  2710. }
  2711. $db = $byId[$sid];
  2712. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  2713. $rw['This_quantity'] = $db['This_quantity'];
  2714. }
  2715. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  2716. $rw['ceilingPrice'] = $db['ceilingPrice'];
  2717. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  2718. $rw['ceilingPrice'] = $db['ceiling_price'];
  2719. }
  2720. }
  2721. unset($rw);
  2722. }
  2723. /**
  2724. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  2725. */
  2726. public function purchaseConfirmPick()
  2727. {
  2728. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2729. $this->error(__('Invalid parameters'));
  2730. }
  2731. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  2732. if ($batchRaw !== '') {
  2733. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  2734. return;
  2735. }
  2736. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  2737. $sid = (int)$scydgyId;
  2738. if (!$this->isValidScydgyRowId($sid)) {
  2739. $this->error('参数无效');
  2740. }
  2741. $parseIdList = function ($raw) {
  2742. if (is_array($raw)) {
  2743. $arr = $raw;
  2744. } else {
  2745. $decoded = json_decode((string)$raw, true);
  2746. $arr = is_array($decoded) ? $decoded : [];
  2747. }
  2748. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  2749. };
  2750. $selectedRaw = $this->request->post('selected_ids', null);
  2751. if ($selectedRaw === null || $selectedRaw === '') {
  2752. $legacy = (int)$this->request->post('selected_id', 0);
  2753. $selectedIds = $legacy > 0 ? [$legacy] : [];
  2754. } else {
  2755. $selectedIds = $parseIdList($selectedRaw);
  2756. }
  2757. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  2758. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  2759. try {
  2760. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  2761. } catch (\InvalidArgumentException $e) {
  2762. $this->error($e->getMessage());
  2763. } catch (\Throwable $e) {
  2764. $this->error($e->getMessage());
  2765. }
  2766. $this->success('操作成功', '', $result);
  2767. }
  2768. /**
  2769. * 整单采购确认(多道工序一次提交)
  2770. */
  2771. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  2772. {
  2773. $decoded = json_decode($batchRaw, true);
  2774. if (!is_array($decoded) || $decoded === []) {
  2775. $this->error('提交数据无效');
  2776. }
  2777. $picks = [];
  2778. foreach ($decoded as $item) {
  2779. if (!is_array($item)) {
  2780. continue;
  2781. }
  2782. $sid = (int)($item['scydgy_id'] ?? 0);
  2783. if (!$this->isValidScydgyRowId($sid)) {
  2784. continue;
  2785. }
  2786. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  2787. if (!is_array($sel)) {
  2788. $sel = [(int)$sel];
  2789. }
  2790. $unsel = $item['unselected_ids'] ?? [];
  2791. if (!is_array($unsel)) {
  2792. $unsel = json_decode((string)$unsel, true);
  2793. $unsel = is_array($unsel) ? $unsel : [];
  2794. }
  2795. $picks[] = [
  2796. 'scydgy_id' => $sid,
  2797. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  2798. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  2799. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  2800. ];
  2801. }
  2802. if ($picks === []) {
  2803. $this->error('提交数据无效');
  2804. }
  2805. Db::startTrans();
  2806. $results = [];
  2807. try {
  2808. foreach ($picks as $pick) {
  2809. $results[] = $this->runPurchaseConfirmPick(
  2810. (int)$pick['scydgy_id'],
  2811. $pick['selected_ids'],
  2812. $pick['unselected_ids'],
  2813. (int)$pick['purchase_order_id'],
  2814. false
  2815. );
  2816. }
  2817. Db::commit();
  2818. } catch (\Throwable $e) {
  2819. Db::rollback();
  2820. $msg = $e->getMessage();
  2821. $this->error($msg !== '' ? $msg : '提交失败');
  2822. }
  2823. $this->success('操作成功', '', ['batch' => $results]);
  2824. }
  2825. /**
  2826. * @return array<string, mixed>
  2827. */
  2828. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true): array
  2829. {
  2830. $scydgyId = (string)$sid;
  2831. if ($selectedIds === []) {
  2832. throw new \InvalidArgumentException('请至少勾选一条明细');
  2833. }
  2834. $inter = array_intersect($selectedIds, $unselectedIds);
  2835. if ($inter !== []) {
  2836. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  2837. }
  2838. $allIds = $this->purchaseOrderDetail($sid);
  2839. if ($allIds === []) {
  2840. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  2841. }
  2842. foreach ($selectedIds as $id) {
  2843. if (!in_array($id, $allIds, true)) {
  2844. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  2845. }
  2846. }
  2847. foreach ($unselectedIds as $id) {
  2848. if (!in_array($id, $allIds, true)) {
  2849. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  2850. }
  2851. }
  2852. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  2853. sort($union, SORT_NUMERIC);
  2854. $expect = $allIds;
  2855. sort($expect, SORT_NUMERIC);
  2856. if ($union !== $expect) {
  2857. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  2858. }
  2859. if ($manageTransaction) {
  2860. Db::startTrans();
  2861. }
  2862. try {
  2863. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  2864. $aff = 0;
  2865. try {
  2866. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  2867. } catch (\Throwable $e) {
  2868. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  2869. }
  2870. if ($aff < 1) {
  2871. throw new \Exception('更新选中状态失败');
  2872. }
  2873. if ($purchaseOrderId > 0) {
  2874. $poAff = (int)Db::table('purchase_order')
  2875. ->where('id', $purchaseOrderId)
  2876. ->where('scydgy_id', $sid)
  2877. ->update(['status' => ProcuremenStatus::POD_PICKED]);
  2878. if ($poAff < 1) {
  2879. throw new \Exception('主表订单不存在或与工序行不匹配');
  2880. }
  2881. } else {
  2882. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::PO_COMPLETED]);
  2883. if ($poAff < 1) {
  2884. throw new \Exception('未找到');
  2885. }
  2886. }
  2887. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  2888. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  2889. if ($manageTransaction) {
  2890. Db::commit();
  2891. }
  2892. } catch (\Throwable $e) {
  2893. if ($manageTransaction) {
  2894. Db::rollback();
  2895. }
  2896. throw $e;
  2897. }
  2898. $poIdFinal = $purchaseOrderId;
  2899. if ($poIdFinal <= 0) {
  2900. try {
  2901. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2902. if (is_array($rpo)) {
  2903. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2904. }
  2905. } catch (\Throwable $e) {
  2906. $poIdFinal = 0;
  2907. }
  2908. }
  2909. $pickNames = [];
  2910. foreach ($selectedIds as $pid) {
  2911. $dr = $this->purchaseOrderDetai($sid, $pid);
  2912. $nm = trim((string)($dr['company_name'] ?? ''));
  2913. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  2914. }
  2915. $this->addOrderLog(
  2916. $sid,
  2917. 'purchase_confirm',
  2918. '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
  2919. $poIdFinal > 0 ? $poIdFinal : null
  2920. );
  2921. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
  2922. $sendSmsSafe = function ($phone, $content) {
  2923. $phone = trim((string)$phone);
  2924. if ($phone === '') {
  2925. return;
  2926. }
  2927. try {
  2928. $this->smsbao($phone, $content);
  2929. } catch (\Throwable $e) {
  2930. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  2931. }
  2932. };
  2933. foreach ($selectedIds as $pid) {
  2934. $dr = $this->purchaseOrderDetai($sid, $pid);
  2935. if (!is_array($dr)) {
  2936. continue;
  2937. }
  2938. $cname = trim((string)($dr['company_name'] ?? ''));
  2939. $ph = trim((string)($dr['phone'] ?? ''));
  2940. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  2941. 'company_name' => $cname,
  2942. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2943. 'phone' => $ph,
  2944. ]));
  2945. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2946. }
  2947. foreach ($unselectedIds as $pid) {
  2948. $dr = $this->purchaseOrderDetai($sid, $pid);
  2949. if (!is_array($dr)) {
  2950. continue;
  2951. }
  2952. $cname = trim((string)($dr['company_name'] ?? ''));
  2953. $ph = trim((string)($dr['phone'] ?? ''));
  2954. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  2955. 'company_name' => $cname,
  2956. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2957. 'phone' => $ph,
  2958. ]));
  2959. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2960. }
  2961. Log::write(sprintf(
  2962. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  2963. $scydgyId,
  2964. $purchaseOrderId,
  2965. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  2966. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  2967. ), 'notice');
  2968. $pdfPublicPath = '';
  2969. try {
  2970. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  2971. } catch (\Throwable $e) {
  2972. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  2973. }
  2974. return [
  2975. 'scydgy_id' => $scydgyId,
  2976. 'purchase_order_id' => $purchaseOrderId,
  2977. 'selected_ids' => $selectedIds,
  2978. 'unselected_ids' => $unselectedIds,
  2979. 'purchase_confirm_pdf' => $pdfPublicPath,
  2980. ];
  2981. }
  2982. /**
  2983. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  2984. *
  2985. * @param int[] $detailIds
  2986. */
  2987. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  2988. {
  2989. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2990. if ($detailIds === []) {
  2991. return;
  2992. }
  2993. $payload = ['status_name' => $statusName];
  2994. try {
  2995. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  2996. } catch (\Throwable $e) {
  2997. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  2998. }
  2999. }
  3000. /**
  3001. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3002. */
  3003. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3004. {
  3005. try {
  3006. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3007. } catch (\Throwable $e) {
  3008. return;
  3009. }
  3010. if (!is_array($rows)) {
  3011. return;
  3012. }
  3013. foreach ($rows as $dr) {
  3014. if (!is_array($dr)) {
  3015. continue;
  3016. }
  3017. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3018. if ($id <= 0) {
  3019. continue;
  3020. }
  3021. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3022. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3023. try {
  3024. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3025. } catch (\Throwable $e) {
  3026. }
  3027. }
  3028. }
  3029. /**
  3030. * @param array<string, mixed> $detailRow
  3031. */
  3032. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3033. {
  3034. $am = $detailRow['amount'] ?? null;
  3035. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3036. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3037. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3038. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3039. }
  3040. /**
  3041. * @return int[]
  3042. */
  3043. protected function purchaseOrderDetail(int $scydgyId): array
  3044. {
  3045. if (!$this->isValidScydgyRowId($scydgyId)) {
  3046. return [];
  3047. }
  3048. try {
  3049. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3050. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3051. $list = $listQuery->select();
  3052. } catch (\Throwable $e) {
  3053. return [];
  3054. }
  3055. if (!is_array($list)) {
  3056. return [];
  3057. }
  3058. $ids = [];
  3059. foreach ($list as $r) {
  3060. if (!is_array($r)) {
  3061. continue;
  3062. }
  3063. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3064. if ($pk > 0) {
  3065. $ids[] = $pk;
  3066. }
  3067. }
  3068. return array_values(array_unique($ids));
  3069. }
  3070. /**
  3071. * 获取当前登录用户信息 [id, 展示名]
  3072. */
  3073. protected function GetUseName(): array
  3074. {
  3075. $id = 0;
  3076. $name = '';
  3077. try {
  3078. if ($this->auth && $this->auth->isLogin()) {
  3079. $u = $this->auth->getUserInfo();
  3080. if (is_array($u)) {
  3081. $id = (int)($u['id'] ?? 0);
  3082. $name = trim((string)($u['nickname'] ?? ''));
  3083. if ($name === '') {
  3084. $name = trim((string)($u['username'] ?? ''));
  3085. }
  3086. }
  3087. }
  3088. } catch (\Throwable $e) {
  3089. }
  3090. if ($name === '') {
  3091. $name = '未知用户';
  3092. }
  3093. return [$id, $name];
  3094. }
  3095. /**
  3096. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3097. */
  3098. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3099. {
  3100. if (!$this->isValidScydgyRowId($scydgyId) || $content === '') {
  3101. return;
  3102. }
  3103. list($adminId, $adminName) = $this->GetUseName();
  3104. $cut = function ($s, $max) {
  3105. if (function_exists('mb_substr')) {
  3106. return mb_substr($s, 0, $max, 'UTF-8');
  3107. }
  3108. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  3109. };
  3110. try {
  3111. Db::table('purchase_order_oper_log')->insert([
  3112. 'scydgy_id' => $scydgyId,
  3113. 'purchase_order_id' => $purchaseOrderId,
  3114. 'admin_id' => $adminId,
  3115. 'admin_name' => $cut($adminName, 64),
  3116. 'action' => $cut((string)$action, 64),
  3117. 'content' => $cut($content, 1000),
  3118. // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
  3119. 'createtime' => time(),
  3120. ]);
  3121. } catch (\Throwable $e) {
  3122. Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
  3123. }
  3124. }
  3125. /**
  3126. * 按主键取一条
  3127. */
  3128. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3129. {
  3130. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3131. return [];
  3132. }
  3133. try {
  3134. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3135. if (is_array($one)) {
  3136. return $one;
  3137. }
  3138. } catch (\Throwable $e) {
  3139. }
  3140. try {
  3141. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3142. if (is_array($one)) {
  3143. return $one;
  3144. }
  3145. } catch (\Throwable $e) {
  3146. }
  3147. return [];
  3148. }
  3149. /**
  3150. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3151. */
  3152. protected function formatProcuremenDetailTime($v): string
  3153. {
  3154. if ($v === null || $v === '') {
  3155. return '';
  3156. }
  3157. if (is_numeric($v) && (int)$v > 946684800) {
  3158. return date('Y-m-d H:i:s', (int)$v);
  3159. }
  3160. $s = trim((string)$v);
  3161. if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
  3162. return $s;
  3163. }
  3164. return '';
  3165. }
  3166. /**
  3167. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3168. */
  3169. protected function formatDeliveryYmd($v): string
  3170. {
  3171. if ($v === null || $v === '') {
  3172. return '';
  3173. }
  3174. $s = trim((string)$v);
  3175. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3176. return '';
  3177. }
  3178. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3179. return $m[1];
  3180. }
  3181. $ts = strtotime($s);
  3182. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3183. }
  3184. /**
  3185. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3186. */
  3187. protected function detailRowSupplierOperated(array $r): bool
  3188. {
  3189. $am = $r['amount'] ?? null;
  3190. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3191. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3192. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3193. return $okAmt || $okDel;
  3194. }
  3195. /**
  3196. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3197. */
  3198. protected function resolveDetailSupplierOperTime(array $r): string
  3199. {
  3200. if (!$this->detailRowSupplierOperated($r)) {
  3201. return '';
  3202. }
  3203. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3204. if ($t !== '') {
  3205. return $t;
  3206. }
  3207. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3208. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3209. continue;
  3210. }
  3211. $t = $this->formatProcuremenDetailTime($r[$col]);
  3212. if ($t !== '') {
  3213. return $t;
  3214. }
  3215. }
  3216. return '';
  3217. }
  3218. /**
  3219. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3220. */
  3221. protected function detailRowSupplierAccepted(array $r): bool
  3222. {
  3223. $am = $r['amount'] ?? null;
  3224. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3225. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3226. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3227. return $okAmt && $okDel;
  3228. }
  3229. /**
  3230. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3231. */
  3232. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3233. {
  3234. if ($detailCount > 0) {
  3235. return true;
  3236. }
  3237. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3238. return true;
  3239. }
  3240. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3241. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3242. return true;
  3243. }
  3244. return false;
  3245. }
  3246. /**
  3247. * 下发时间:优先 pick_time,其次首条下发明细时间
  3248. */
  3249. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3250. {
  3251. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3252. if ($issueTime !== '') {
  3253. return $issueTime;
  3254. }
  3255. foreach ($details as $dr) {
  3256. if (!is_array($dr)) {
  3257. continue;
  3258. }
  3259. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3260. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3261. $issueTime = $t;
  3262. }
  3263. }
  3264. if ($issueTime !== '') {
  3265. return $issueTime;
  3266. }
  3267. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3268. }
  3269. /**
  3270. * 直接点「完结」时间:优先操作记录 mark_complete
  3271. */
  3272. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3273. {
  3274. if (!$this->isValidScydgyRowId($scydgyId)) {
  3275. return '';
  3276. }
  3277. try {
  3278. $log = Db::table('purchase_order_oper_log')
  3279. ->where('scydgy_id', $scydgyId)
  3280. ->where('action', 'mark_complete')
  3281. ->order('id', 'desc')
  3282. ->find();
  3283. if (is_array($log)) {
  3284. $ct = (int)($log['createtime'] ?? 0);
  3285. if ($ct > 946684800) {
  3286. return date('Y-m-d H:i:s', $ct);
  3287. }
  3288. }
  3289. } catch (\Throwable $e) {
  3290. }
  3291. return '';
  3292. }
  3293. /**
  3294. * 操作记录时间(取指定 action 最近一条)
  3295. *
  3296. * @param string|array<int, string> $actions
  3297. */
  3298. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3299. {
  3300. if (!$this->isValidScydgyRowId($scydgyId)) {
  3301. return '';
  3302. }
  3303. $acts = is_array($actions) ? $actions : [$actions];
  3304. $acts = array_values(array_filter(array_map('strval', $acts)));
  3305. if ($acts === []) {
  3306. return '';
  3307. }
  3308. try {
  3309. $log = Db::table('purchase_order_oper_log')
  3310. ->where('scydgy_id', $scydgyId)
  3311. ->where('action', 'in', $acts)
  3312. ->order('id', 'desc')
  3313. ->find();
  3314. if (is_array($log)) {
  3315. $ct = (int)($log['createtime'] ?? 0);
  3316. if ($ct > 946684800) {
  3317. return date('Y-m-d H:i:s', $ct);
  3318. }
  3319. }
  3320. } catch (\Throwable $e) {
  3321. }
  3322. return '';
  3323. }
  3324. /**
  3325. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3326. *
  3327. * @param array $main purchase_order 一行
  3328. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3329. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3330. */
  3331. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3332. {
  3333. $issueCnt = count($details);
  3334. $acceptCnt = 0;
  3335. $pickedName = '';
  3336. $pickedTime = '';
  3337. foreach ($details as $dr) {
  3338. if (!is_array($dr)) {
  3339. continue;
  3340. }
  3341. if ($this->detailRowSupplierAccepted($dr)) {
  3342. $acceptCnt++;
  3343. }
  3344. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3345. if ($pickedName === '') {
  3346. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3347. }
  3348. if ($pickedTime === '') {
  3349. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3350. if ($pickedTime === '') {
  3351. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3352. }
  3353. }
  3354. }
  3355. }
  3356. $hasMain = $main !== [];
  3357. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3358. if ($poTime === '') {
  3359. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3360. }
  3361. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3362. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3363. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3364. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3365. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3366. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3367. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3368. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3369. $supplierTime = '';
  3370. if ($acceptCnt > 0) {
  3371. foreach ($details as $dr) {
  3372. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3373. continue;
  3374. }
  3375. $t = $this->resolveDetailSupplierOperTime($dr);
  3376. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3377. $supplierTime = $t;
  3378. }
  3379. }
  3380. }
  3381. $directComplete = ($mainCompleted && !$issued);
  3382. $doneTime = '';
  3383. if ($mainCompleted) {
  3384. if ($directComplete) {
  3385. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3386. }
  3387. if ($doneTime === '') {
  3388. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3389. }
  3390. if ($doneTime === '') {
  3391. foreach ($details as $dr) {
  3392. if (!is_array($dr)) {
  3393. continue;
  3394. }
  3395. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3396. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3397. $doneTime = $t;
  3398. }
  3399. }
  3400. }
  3401. if ($doneTime === '') {
  3402. $doneTime = $poTime;
  3403. }
  3404. if ($confirmApproveTime !== '') {
  3405. $doneTime = $confirmApproveTime;
  3406. }
  3407. }
  3408. if ($directComplete) {
  3409. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3410. $step1Done = $hasMain;
  3411. $step2Done = false;
  3412. $step3Done = false;
  3413. $step4Done = false;
  3414. $step5Done = false;
  3415. $step6Done = true;
  3416. } else {
  3417. $step1Done = $issued;
  3418. $step2Done = $issued;
  3419. $step3Done = $acceptCnt > 0;
  3420. $step4Done = $wflowPendingApproval;
  3421. if (!$step4Done) {
  3422. foreach ($details as $dr) {
  3423. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3424. $step4Done = true;
  3425. break;
  3426. }
  3427. }
  3428. }
  3429. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3430. $step6Done = $mainCompleted;
  3431. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3432. if ($mainCompleted && $issued) {
  3433. $step3Done = true;
  3434. $step4Done = true;
  3435. $step5Done = true;
  3436. if ($supplierTime === '') {
  3437. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3438. if ($fillT !== '') {
  3439. $supplierTime = $fillT;
  3440. }
  3441. }
  3442. if ($pickedTime === '') {
  3443. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3444. if ($fillT !== '') {
  3445. $pickedTime = $fillT;
  3446. }
  3447. }
  3448. if ($auditSelectTime === '') {
  3449. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3450. if ($fillT !== '') {
  3451. $auditSelectTime = $fillT;
  3452. }
  3453. }
  3454. if ($confirmApproveTime === '') {
  3455. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3456. if ($fillT !== '') {
  3457. $confirmApproveTime = $fillT;
  3458. }
  3459. }
  3460. }
  3461. }
  3462. $steps = [
  3463. [
  3464. 'title' => '未发',
  3465. 'subtitle' => '',
  3466. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3467. 'done' => $step1Done,
  3468. ],
  3469. [
  3470. 'title' => '下发',
  3471. 'subtitle' => '',
  3472. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3473. 'done' => $step2Done,
  3474. ],
  3475. [
  3476. 'title' => '供应商接单',
  3477. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3478. 'time' => $step3Done ? $supplierTime : '',
  3479. 'done' => $step3Done,
  3480. ],
  3481. [
  3482. 'title' => '待确认',
  3483. 'subtitle' => $step4Done
  3484. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  3485. : ($issued ? '待选供应商' : ''),
  3486. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  3487. 'done' => $step4Done,
  3488. ],
  3489. [
  3490. 'title' => '待审批',
  3491. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  3492. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  3493. 'done' => $step5Done,
  3494. ],
  3495. [
  3496. 'title' => '已完结',
  3497. 'subtitle' => '',
  3498. 'time' => $step6Done ? $doneTime : '',
  3499. 'done' => $step6Done,
  3500. ],
  3501. ];
  3502. $currentIdx = count($steps) - 1;
  3503. if (!$directComplete) {
  3504. foreach ($steps as $i => $s) {
  3505. if (!$s['done']) {
  3506. $currentIdx = $i;
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. $nSteps = count($steps);
  3512. foreach ($steps as $idx => &$s) {
  3513. $s['current'] = ($idx === $currentIdx);
  3514. if ($idx === 0) {
  3515. $s['pdf_left_bg'] = '';
  3516. } else {
  3517. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3518. }
  3519. if ($idx >= $nSteps - 1) {
  3520. $s['pdf_right_bg'] = '';
  3521. } else {
  3522. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3523. }
  3524. }
  3525. unset($s);
  3526. $labelMap = [
  3527. 'CCYDH' => '订单号',
  3528. 'CYJMC' => '印件名称',
  3529. 'CCLBMMC' => '承揽部门',
  3530. 'CGYMC' => '工序名称',
  3531. 'CDW' => '单位',
  3532. 'NGZL' => '工作量',
  3533. 'CDF' => '单价',
  3534. 'cGzzxMc' => '工作中心',
  3535. 'MBZ' => '备注',
  3536. 'This_quantity' => '本次数量',
  3537. 'ceilingPrice' => '最高限价',
  3538. ];
  3539. $orderSummary = [];
  3540. foreach ($labelMap as $key => $lab) {
  3541. if (!array_key_exists($key, $main)) {
  3542. continue;
  3543. }
  3544. $val = $main[$key];
  3545. if ($val === null) {
  3546. $val = '';
  3547. } elseif (!is_scalar($val)) {
  3548. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3549. } else {
  3550. $val = (string)$val;
  3551. }
  3552. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3553. }
  3554. $orderSummaryGrid = [];
  3555. $n = count($orderSummary);
  3556. for ($i = 0; $i < $n; $i += 2) {
  3557. $left = $orderSummary[$i];
  3558. $hasRight = ($i + 1) < $n;
  3559. $orderSummaryGrid[] = [
  3560. 'l1' => $left['label'],
  3561. 'v1' => $left['value'],
  3562. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3563. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3564. ];
  3565. }
  3566. return [
  3567. 'steps' => $steps,
  3568. 'orderSummary' => $orderSummary,
  3569. 'orderSummaryGrid' => $orderSummaryGrid,
  3570. 'detailRows' => $details,
  3571. ];
  3572. }
  3573. /**
  3574. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3575. *
  3576. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3577. */
  3578. protected function prepareProcuremenDetailsView(string $ids): array
  3579. {
  3580. $main = [];
  3581. try {
  3582. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3583. $main = is_array($one) ? $one : [];
  3584. } catch (\Throwable $e) {
  3585. $main = [];
  3586. }
  3587. $details = [];
  3588. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3589. if ($mergeRows === []) {
  3590. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3591. if ($mergeRows === [] && $main !== []) {
  3592. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3593. }
  3594. }
  3595. $detailSidList = [];
  3596. $anchorSid = (int)$ids;
  3597. if ($anchorSid !== 0) {
  3598. $detailSidList[$anchorSid] = true;
  3599. }
  3600. foreach ($mergeRows as $mr) {
  3601. if (!is_array($mr)) {
  3602. continue;
  3603. }
  3604. $sid = $this->extractScydgyRowId($mr);
  3605. if ($sid !== 0) {
  3606. $detailSidList[$sid] = true;
  3607. }
  3608. }
  3609. try {
  3610. if ($detailSidList !== []) {
  3611. $details = Db::table('purchase_order_detail')
  3612. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3613. ->order('id', 'asc')
  3614. ->select();
  3615. }
  3616. } catch (\Throwable $e) {
  3617. $details = [];
  3618. }
  3619. if (!is_array($details)) {
  3620. $details = [];
  3621. }
  3622. foreach ($details as &$r) {
  3623. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3624. $r['id'] = $r['ID'];
  3625. }
  3626. if (isset($r['createtime'])) {
  3627. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3628. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3629. } else {
  3630. $r['createtime_text'] = (string)$r['createtime'];
  3631. }
  3632. } else {
  3633. $r['createtime_text'] = '';
  3634. }
  3635. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3636. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3637. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  3638. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  3639. }
  3640. unset($r);
  3641. $activeDetails = [];
  3642. foreach ($details as $r) {
  3643. if (is_array($r) && empty($r['is_void'])) {
  3644. $activeDetails[] = $r;
  3645. }
  3646. }
  3647. $operLogs = [];
  3648. try {
  3649. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3650. } catch (\Throwable $e) {
  3651. $operLogs = [];
  3652. }
  3653. if (!is_array($operLogs)) {
  3654. $operLogs = [];
  3655. }
  3656. foreach ($operLogs as &$lg) {
  3657. if (!is_array($lg)) {
  3658. continue;
  3659. }
  3660. $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
  3661. $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
  3662. }
  3663. unset($lg);
  3664. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3665. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3666. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3667. if ($ccydh === '') {
  3668. foreach ($details as $r) {
  3669. if (!is_array($r)) {
  3670. continue;
  3671. }
  3672. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3673. if ($ccydh !== '') {
  3674. break;
  3675. }
  3676. }
  3677. }
  3678. $this->view->assign('ccydh', $ccydh);
  3679. $this->view->assign('steps', $bundle['steps']);
  3680. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3681. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3682. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3683. $this->view->assign('processCount', count($mergeRows));
  3684. $this->view->assign('detailRows', $details);
  3685. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3686. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3687. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3688. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3689. $this->view->assign('operLogs', $operLogs);
  3690. return [
  3691. 'ok' => $main !== [] || $details !== [],
  3692. 'ccydh' => $ccydh,
  3693. ];
  3694. }
  3695. /**
  3696. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3697. */
  3698. public function details()
  3699. {
  3700. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3701. if (is_array($ids)) {
  3702. $ids = isset($ids[0]) ? $ids[0] : '';
  3703. }
  3704. $ids = trim((string)$ids);
  3705. if ($ids === '') {
  3706. $this->error(__('Invalid parameters'));
  3707. }
  3708. $this->assertManualOrderDetailsViewable((int)$ids);
  3709. $this->prepareProcuremenDetailsView($ids);
  3710. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3711. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3712. $this->view->engine->layout(false);
  3713. try {
  3714. return $this->view->fetch('procuremen/details_dialog_shell');
  3715. } finally {
  3716. if ($restoreLayout) {
  3717. $this->view->engine->layout($restoreLayout);
  3718. }
  3719. }
  3720. }
  3721. /**
  3722. * 解析合并审核工序行(订单号须一致,且均未协助)
  3723. *
  3724. * @return array<int, array<string, mixed>>
  3725. */
  3726. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3727. {
  3728. $primary = json_decode($rowJson, true);
  3729. if (!is_array($primary)) {
  3730. $this->error(__('Invalid parameters'));
  3731. }
  3732. $merge = json_decode($mergeRowsJson, true);
  3733. if (!is_array($merge) || $merge === []) {
  3734. $merge = [$primary];
  3735. }
  3736. $seen = [];
  3737. $out = [];
  3738. foreach ($merge as $r) {
  3739. if (!is_array($r)) {
  3740. continue;
  3741. }
  3742. $id = $this->extractScydgyRowId($r);
  3743. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3744. continue;
  3745. }
  3746. $seen[$id] = true;
  3747. $out[] = $r;
  3748. }
  3749. if ($out === []) {
  3750. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3751. }
  3752. $ccydh = null;
  3753. foreach ($out as $r) {
  3754. $dh = trim((string)($r['CCYDH'] ?? ''));
  3755. if ($ccydh === null) {
  3756. $ccydh = $dh;
  3757. } elseif ($dh !== $ccydh) {
  3758. $this->error('合并审核要求所选行的订单号一致');
  3759. }
  3760. }
  3761. $ids = [];
  3762. foreach ($out as $r) {
  3763. $id = $this->extractScydgyRowId($r);
  3764. if ($this->isValidScydgyRowId($id)) {
  3765. $ids[$id] = true;
  3766. }
  3767. }
  3768. $poBySid = [];
  3769. $detCntBySid = [];
  3770. if ($ids !== []) {
  3771. $idList = array_keys($ids);
  3772. try {
  3773. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3774. if (is_array($poList)) {
  3775. foreach ($poList as $po) {
  3776. if (!is_array($po)) {
  3777. continue;
  3778. }
  3779. $sid = (int)($po['scydgy_id'] ?? 0);
  3780. if ($this->isValidScydgyRowId($sid)) {
  3781. $poBySid[$sid] = $po;
  3782. }
  3783. }
  3784. }
  3785. } catch (\Throwable $e) {
  3786. }
  3787. try {
  3788. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  3789. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  3790. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  3791. if (is_array($detRows)) {
  3792. foreach ($detRows as $dr) {
  3793. if (!is_array($dr)) {
  3794. continue;
  3795. }
  3796. $sid = (int)($dr['scydgy_id'] ?? 0);
  3797. if ($this->isValidScydgyRowId($sid)) {
  3798. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3799. }
  3800. }
  3801. }
  3802. } catch (\Throwable $e) {
  3803. }
  3804. }
  3805. foreach ($out as $r) {
  3806. $id = $this->extractScydgyRowId($r);
  3807. if (!$this->isValidScydgyRowId($id)) {
  3808. continue;
  3809. }
  3810. $po = $poBySid[$id] ?? null;
  3811. if (!is_array($po)) {
  3812. continue;
  3813. }
  3814. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  3815. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3816. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3817. }
  3818. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3819. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  3820. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3821. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  3822. }
  3823. }
  3824. return $out;
  3825. }
  3826. /**
  3827. * 规范化下发/确认时勾选的供应商
  3828. *
  3829. * @param array<int, mixed> $companies
  3830. * @return array<int, array<string, string>>
  3831. */
  3832. protected function normalizePickCompanies(array $companies): array
  3833. {
  3834. $out = [];
  3835. foreach ($companies as $c) {
  3836. if (!is_array($c)) {
  3837. continue;
  3838. }
  3839. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  3840. if ($name === '') {
  3841. continue;
  3842. }
  3843. $out[] = [
  3844. 'name' => $name,
  3845. 'company_name' => $name,
  3846. 'username' => trim((string)($c['username'] ?? '')),
  3847. 'email' => trim((string)($c['email'] ?? '')),
  3848. 'phone' => trim((string)($c['phone'] ?? '')),
  3849. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  3850. ];
  3851. }
  3852. return $out;
  3853. }
  3854. /**
  3855. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  3856. *
  3857. * @param array<int, array<string, mixed>> $pool
  3858. * @return array<int, array<string, mixed>>
  3859. */
  3860. protected function collapseProcuremenPoolByOrder(array $pool): array
  3861. {
  3862. if ($pool === []) {
  3863. return [];
  3864. }
  3865. $groups = [];
  3866. foreach ($pool as $row) {
  3867. if (!is_array($row)) {
  3868. continue;
  3869. }
  3870. $dh = trim((string)($row['CCYDH'] ?? ''));
  3871. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  3872. if (!isset($groups[$key])) {
  3873. $groups[$key] = [];
  3874. }
  3875. $groups[$key][] = $row;
  3876. }
  3877. $out = [];
  3878. foreach ($groups as $ccydh => $rows) {
  3879. if ($rows === []) {
  3880. continue;
  3881. }
  3882. usort($rows, function ($a, $b) {
  3883. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  3884. });
  3885. $head = $rows[0];
  3886. $gymcList = [];
  3887. foreach ($rows as $r) {
  3888. $g = trim((string)($r['CGYMC'] ?? ''));
  3889. if ($g !== '' && !in_array($g, $gymcList, true)) {
  3890. $gymcList[] = $g;
  3891. }
  3892. }
  3893. $merged = $head;
  3894. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  3895. $merged['process_count'] = count($rows);
  3896. $merged['_order_merge_rows'] = $rows;
  3897. if (count($rows) > 1) {
  3898. $merged['CGYMC'] = implode('、', $gymcList);
  3899. }
  3900. $mergedPickTime = '';
  3901. foreach ($rows as $r) {
  3902. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  3903. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  3904. $mergedPickTime = $t;
  3905. }
  3906. }
  3907. if ($mergedPickTime !== '') {
  3908. $merged['pick_time'] = $mergedPickTime;
  3909. }
  3910. $out[] = $merged;
  3911. }
  3912. usort($out, function ($a, $b) {
  3913. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  3914. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  3915. if ($ta === $tb) {
  3916. $ida = (int)($a['purchase_order_id'] ?? 0);
  3917. $idb = (int)($b['purchase_order_id'] ?? 0);
  3918. if ($ida !== $idb) {
  3919. return $idb <=> $ida;
  3920. }
  3921. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  3922. }
  3923. if ($ta === '') {
  3924. return 1;
  3925. }
  3926. if ($tb === '') {
  3927. return -1;
  3928. }
  3929. return strcmp($tb, $ta);
  3930. });
  3931. return $out;
  3932. }
  3933. /**
  3934. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  3935. *
  3936. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3937. */
  3938. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  3939. {
  3940. $scydgyId = trim($scydgyId);
  3941. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3942. if ($scydgyId === '') {
  3943. return $empty;
  3944. }
  3945. try {
  3946. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3947. } catch (\Throwable $e) {
  3948. $anchor = null;
  3949. }
  3950. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  3951. return $empty;
  3952. }
  3953. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3954. if ($ccydh === '') {
  3955. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  3956. }
  3957. try {
  3958. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  3959. } catch (\Throwable $e) {
  3960. $pos = [$anchor];
  3961. }
  3962. if (!is_array($pos) || $pos === []) {
  3963. $pos = [$anchor];
  3964. }
  3965. return [
  3966. 'ccydh' => $ccydh,
  3967. 'pos' => $pos,
  3968. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3969. ];
  3970. }
  3971. /**
  3972. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  3973. */
  3974. protected function purchaseOrderRowInConfirmStage(array $po): bool
  3975. {
  3976. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  3977. return false;
  3978. }
  3979. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  3980. return true;
  3981. }
  3982. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  3983. $sid = (int)($po['scydgy_id'] ?? 0);
  3984. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  3985. }
  3986. return false;
  3987. }
  3988. /**
  3989. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  3990. *
  3991. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3992. */
  3993. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  3994. {
  3995. $scydgyId = trim($scydgyId);
  3996. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3997. if ($scydgyId === '') {
  3998. return $empty;
  3999. }
  4000. try {
  4001. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4002. } catch (\Throwable $e) {
  4003. $anchor = null;
  4004. }
  4005. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4006. return $empty;
  4007. }
  4008. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4009. if ($ccydh === '') {
  4010. return [
  4011. 'ccydh' => '',
  4012. 'pos' => [$anchor],
  4013. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4014. ];
  4015. }
  4016. try {
  4017. $pos = Db::table('purchase_order')
  4018. ->where('CCYDH', $ccydh)
  4019. ->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))
  4020. ->where(function ($q) {
  4021. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  4022. ->whereOr(function ($q2) {
  4023. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  4024. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  4025. });
  4026. })
  4027. ->order('scydgy_id', 'asc')
  4028. ->select();
  4029. } catch (\Throwable $e) {
  4030. $pos = [$anchor];
  4031. }
  4032. if (!is_array($pos) || $pos === []) {
  4033. $pos = [$anchor];
  4034. }
  4035. $pos = array_values(array_filter($pos, function ($po) {
  4036. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4037. }));
  4038. if ($pos === []) {
  4039. $pos = [$anchor];
  4040. }
  4041. return [
  4042. 'ccydh' => $ccydh,
  4043. 'pos' => $pos,
  4044. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4045. ];
  4046. }
  4047. /**
  4048. * @param array<int, array<string, mixed>> $purchaseOrders
  4049. * @return array<int, array<string, mixed>>
  4050. */
  4051. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4052. {
  4053. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4054. $byId = [];
  4055. foreach ($pool as $r) {
  4056. if (!is_array($r)) {
  4057. continue;
  4058. }
  4059. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4060. if ($this->isValidScydgyRowId($sid)) {
  4061. $byId[$sid] = $r;
  4062. }
  4063. }
  4064. $out = [];
  4065. foreach ($purchaseOrders as $po) {
  4066. if (!is_array($po)) {
  4067. continue;
  4068. }
  4069. $sid = (int)($po['scydgy_id'] ?? 0);
  4070. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4071. $out[] = $byId[$sid];
  4072. }
  4073. }
  4074. return $out;
  4075. }
  4076. /**
  4077. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4078. *
  4079. * @return array<int, array<string, mixed>>
  4080. */
  4081. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4082. {
  4083. $scydgyId = trim($scydgyId);
  4084. if ($scydgyId === '') {
  4085. return [];
  4086. }
  4087. try {
  4088. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4089. } catch (\Throwable $e) {
  4090. $anchor = null;
  4091. }
  4092. if (!is_array($anchor)) {
  4093. return [];
  4094. }
  4095. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4096. return [];
  4097. }
  4098. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4099. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4100. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4101. try {
  4102. $q = Db::table('purchase_order');
  4103. if ($ccydh !== '') {
  4104. $q->where('CCYDH', $ccydh);
  4105. } else {
  4106. $q->where('scydgy_id', $scydgyId);
  4107. }
  4108. if ($isValidPick) {
  4109. $q->where('pick_time', $pickTime);
  4110. }
  4111. $pos = $q->order('scydgy_id', 'asc')->select();
  4112. } catch (\Throwable $e) {
  4113. $pos = [$anchor];
  4114. }
  4115. if (!is_array($pos) || $pos === []) {
  4116. $pos = [$anchor];
  4117. }
  4118. $pos = array_values(array_filter($pos, function ($po) {
  4119. if (!is_array($po)) {
  4120. return false;
  4121. }
  4122. $mr = $po['mod_rq'] ?? null;
  4123. if ($mr === null || $mr === '') {
  4124. return true;
  4125. }
  4126. $mrs = trim((string)$mr);
  4127. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4128. }));
  4129. if ($pos === []) {
  4130. $pos = [$anchor];
  4131. }
  4132. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4133. if ($rows === []) {
  4134. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4135. }
  4136. return $rows;
  4137. }
  4138. /**
  4139. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4140. *
  4141. * @param array<int, array<string, mixed>> $mergeRows
  4142. * @return array<int, array<string, mixed>>
  4143. */
  4144. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4145. {
  4146. $list = array_values($mergeRows);
  4147. $n = count($list);
  4148. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4149. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4150. $mergeSame = $n > 1 && $orderKey0 !== '';
  4151. if ($mergeSame) {
  4152. foreach ($list as $rr) {
  4153. if (!is_array($rr)) {
  4154. $mergeSame = false;
  4155. break;
  4156. }
  4157. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4158. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4159. $mergeSame = false;
  4160. break;
  4161. }
  4162. }
  4163. }
  4164. $out = [];
  4165. foreach ($list as $idx => $r) {
  4166. if (!is_array($r)) {
  4167. continue;
  4168. }
  4169. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4170. if (is_scalar($qty)) {
  4171. $qty = trim((string)$qty);
  4172. } else {
  4173. $qty = '';
  4174. }
  4175. if ($qty === '') {
  4176. $gzl = $r['NGZL'] ?? '';
  4177. if (is_scalar($gzl)) {
  4178. $qty = trim((string)$gzl);
  4179. }
  4180. }
  4181. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4182. $sid = $this->extractScydgyRowId($r);
  4183. $out[] = [
  4184. 'seq' => $idx + 1,
  4185. 'scydgy_id' => $sid,
  4186. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4187. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4188. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4189. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4190. 'NGZL' => $r['NGZL'] ?? '',
  4191. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4192. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4193. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4194. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4195. 'show_order_cells' => !$mergeSame || $idx === 0,
  4196. 'order_rowspan' => $mergeSame ? $n : 1,
  4197. ];
  4198. }
  4199. return $out;
  4200. }
  4201. /**
  4202. * 解析金额/数量(去千分位等非数字字符)
  4203. */
  4204. protected function parseProcuremenMoneyNumber($value): ?float
  4205. {
  4206. if ($value === null || $value === '') {
  4207. return null;
  4208. }
  4209. if (is_numeric($value)) {
  4210. return (float)$value;
  4211. }
  4212. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4213. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4214. }
  4215. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4216. {
  4217. if ($amount === null) {
  4218. return '';
  4219. }
  4220. return (string)(int)round($amount);
  4221. }
  4222. /**
  4223. * 列表/详情展示:工作量为 0 时显示空
  4224. */
  4225. protected function formatProcuremenWorkloadDisplay($value): string
  4226. {
  4227. if ($value === null || $value === '') {
  4228. return '';
  4229. }
  4230. $s = trim((string)$value);
  4231. if ($s === '') {
  4232. return '';
  4233. }
  4234. if (is_numeric($s) && (float)$s == 0) {
  4235. return '';
  4236. }
  4237. return $s;
  4238. }
  4239. /**
  4240. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4241. */
  4242. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4243. {
  4244. foreach ($details as $d) {
  4245. if (!is_array($d)) {
  4246. continue;
  4247. }
  4248. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4249. $cn = trim((string)($d['company_name'] ?? ''));
  4250. if ($cn !== '') {
  4251. return $cn;
  4252. }
  4253. }
  4254. }
  4255. return trim((string)($main['pick_company_name'] ?? ''));
  4256. }
  4257. /**
  4258. * 详情报价小计:单价 × 本工序本次数量
  4259. */
  4260. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4261. {
  4262. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4263. if ($unit === null) {
  4264. return null;
  4265. }
  4266. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4267. if ($qty === null || $qty <= 0) {
  4268. return null;
  4269. }
  4270. return $unit * $qty;
  4271. }
  4272. /**
  4273. * 详情页:工序小计 + 供应商分组报价与总计
  4274. *
  4275. * @param array<int, array<string, mixed>> $mergeRows
  4276. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4277. * @return array{
  4278. * process_rows: array,
  4279. * supplier_groups: array,
  4280. * order_total_text: string,
  4281. * order_total_has: bool,
  4282. * selected_company: string
  4283. * }
  4284. */
  4285. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4286. {
  4287. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4288. $qtyBySid = [];
  4289. $gymcBySid = [];
  4290. $orderedSids = [];
  4291. foreach ($mergeRows as $mr) {
  4292. if (!is_array($mr)) {
  4293. continue;
  4294. }
  4295. $sid = $this->extractScydgyRowId($mr);
  4296. if ($sid > 0) {
  4297. $orderedSids[] = $sid;
  4298. }
  4299. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4300. if ($qty === '') {
  4301. $qty = trim((string)($mr['NGZL'] ?? ''));
  4302. }
  4303. $qtyBySid[$sid] = $qty;
  4304. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4305. }
  4306. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4307. $detailByCompanySid = [];
  4308. foreach ($details as $d) {
  4309. if (!is_array($d)) {
  4310. continue;
  4311. }
  4312. $cn = trim((string)($d['company_name'] ?? ''));
  4313. $sid = (int)($d['scydgy_id'] ?? 0);
  4314. if ($cn === '' || $sid === 0) {
  4315. continue;
  4316. }
  4317. if (!isset($detailByCompanySid[$cn])) {
  4318. $detailByCompanySid[$cn] = [];
  4319. }
  4320. $detailByCompanySid[$cn][$sid] = $d;
  4321. }
  4322. $supplierGroups = [];
  4323. foreach ($detailByCompanySid as $cn => $bySid) {
  4324. $lines = [];
  4325. $groupTotal = 0.0;
  4326. $groupHas = false;
  4327. $groupVoid = true;
  4328. $usedSids = [];
  4329. $appendLine = function (int $sid, array $d) use (
  4330. &$lines,
  4331. &$groupTotal,
  4332. &$groupHas,
  4333. &$groupVoid,
  4334. $qtyBySid,
  4335. $gymcBySid
  4336. ) {
  4337. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  4338. if (!$isVoid) {
  4339. $groupVoid = false;
  4340. }
  4341. $qtyStr = $qtyBySid[$sid] ?? '';
  4342. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4343. $sub = null;
  4344. if (!$isVoid && $amountNum !== null) {
  4345. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  4346. if ($sub !== null) {
  4347. $groupTotal += $sub;
  4348. $groupHas = true;
  4349. }
  4350. }
  4351. $ct = $this->resolveDetailSupplierOperTime($d);
  4352. $lines[] = [
  4353. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  4354. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : trim((string)($d['amount'] ?? '')),
  4355. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  4356. 'delivery_ymd' => $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null),
  4357. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  4358. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  4359. 'is_void' => $isVoid,
  4360. 'oper_time_text' => $ct,
  4361. ];
  4362. };
  4363. foreach ($orderedSids as $sid) {
  4364. if (!isset($bySid[$sid])) {
  4365. continue;
  4366. }
  4367. $usedSids[$sid] = true;
  4368. $appendLine($sid, $bySid[$sid]);
  4369. }
  4370. foreach ($bySid as $sid => $d) {
  4371. if (isset($usedSids[$sid])) {
  4372. continue;
  4373. }
  4374. $appendLine((int)$sid, $d);
  4375. }
  4376. $firstDetail = null;
  4377. foreach ($bySid as $d) {
  4378. if (is_array($d)) {
  4379. $firstDetail = $d;
  4380. break;
  4381. }
  4382. }
  4383. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  4384. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  4385. if ($username === '' && $ph !== '') {
  4386. $username = $this->resolveCustomerContactName($ph, $cn);
  4387. }
  4388. $lineCount = count($lines);
  4389. $supplierGroups[] = [
  4390. 'company_name' => $cn,
  4391. 'username' => $username,
  4392. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  4393. 'phone' => $ph,
  4394. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  4395. 'is_void' => $groupVoid,
  4396. 'lines' => $lines,
  4397. 'line_count' => $lineCount,
  4398. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  4399. 'total_text' => $groupHas ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  4400. 'has_total' => $lineCount > 0,
  4401. ];
  4402. }
  4403. usort($supplierGroups, function ($a, $b) {
  4404. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  4405. return ($a['is_void'] ?? false) ? 1 : -1;
  4406. }
  4407. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  4408. return ($a['is_selected'] ?? false) ? -1 : 1;
  4409. }
  4410. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  4411. });
  4412. return [
  4413. 'process_rows' => $processRows,
  4414. 'supplier_groups' => $supplierGroups,
  4415. 'order_total_text' => '',
  4416. 'order_total_has' => false,
  4417. 'selected_company' => $selectedCompany,
  4418. ];
  4419. }
  4420. /**
  4421. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  4422. */
  4423. protected function buildProcessLinesPlain(array $mergeRows): string
  4424. {
  4425. $lines = [];
  4426. $i = 1;
  4427. foreach ($mergeRows as $r) {
  4428. if (!is_array($r)) {
  4429. continue;
  4430. }
  4431. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4432. $dw = trim((string)($r['CDW'] ?? ''));
  4433. $gzl = trim((string)($r['NGZL'] ?? ''));
  4434. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4435. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  4436. if ($dw !== '') {
  4437. $parts[] = '单位:' . $dw;
  4438. }
  4439. if ($gzl !== '') {
  4440. $parts[] = '工作量:' . $gzl;
  4441. }
  4442. if ($qty !== '') {
  4443. $parts[] = '本次数量:' . $qty;
  4444. }
  4445. $lines[] = implode(' ', $parts);
  4446. $i++;
  4447. }
  4448. return implode("\n", $lines);
  4449. }
  4450. /**
  4451. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  4452. *
  4453. * @return array<string, string>
  4454. */
  4455. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
  4456. {
  4457. $po = null;
  4458. try {
  4459. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4460. } catch (\Throwable $e) {
  4461. $po = null;
  4462. }
  4463. $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
  4464. $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
  4465. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
  4466. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4467. if (is_array($any)) {
  4468. if ($ccydh === '') {
  4469. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4470. }
  4471. if ($cyjmc === '') {
  4472. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4473. }
  4474. }
  4475. }
  4476. $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
  4477. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4478. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4479. return [
  4480. 'ccydh' => $ccydh,
  4481. 'cyjmc' => $cyjmc,
  4482. 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
  4483. 'process_lines' => $processLines,
  4484. 'process_lines_html' => '',
  4485. ];
  4486. }
  4487. /**
  4488. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4489. */
  4490. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4491. {
  4492. $lines = [];
  4493. if ($ccydh !== '') {
  4494. $lines[] = '订单号:' . $ccydh;
  4495. }
  4496. if ($cyjmc !== '') {
  4497. $lines[] = '印件名称:' . $cyjmc;
  4498. }
  4499. if ($processPlain !== '') {
  4500. $lines[] = $processPlain;
  4501. }
  4502. return implode("\n", $lines);
  4503. }
  4504. /**
  4505. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4506. *
  4507. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4508. */
  4509. protected function buildPlatformLinksPlain(array $detailLinks): string
  4510. {
  4511. $lines = [];
  4512. $i = 1;
  4513. foreach ($detailLinks as $lk) {
  4514. if (!is_array($lk)) {
  4515. continue;
  4516. }
  4517. $url = trim((string)($lk['url'] ?? ''));
  4518. if ($url === '') {
  4519. continue;
  4520. }
  4521. $label = trim((string)($lk['cgymc'] ?? ''));
  4522. if ($label === '') {
  4523. $label = '工序' . $i;
  4524. }
  4525. $lines[] = $label . ':' . $url;
  4526. $i++;
  4527. }
  4528. return implode("\n", $lines);
  4529. }
  4530. /**
  4531. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4532. *
  4533. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4534. */
  4535. protected function buildPlatformLinksHtml(array $detailLinks): string
  4536. {
  4537. $parts = [];
  4538. $i = 1;
  4539. foreach ($detailLinks as $lk) {
  4540. if (!is_array($lk)) {
  4541. continue;
  4542. }
  4543. $url = trim((string)($lk['url'] ?? ''));
  4544. if ($url === '') {
  4545. continue;
  4546. }
  4547. $label = trim((string)($lk['cgymc'] ?? ''));
  4548. if ($label === '') {
  4549. $label = '工序' . $i;
  4550. }
  4551. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4552. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4553. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4554. $i++;
  4555. }
  4556. return implode("<br>\n", $parts);
  4557. }
  4558. /**
  4559. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4560. *
  4561. * @return array<string, mixed>
  4562. */
  4563. protected function loadMailerConfig(): array
  4564. {
  4565. try {
  4566. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4567. } catch (\Throwable $e) {
  4568. $cfg = [];
  4569. }
  4570. return is_array($cfg) ? $cfg : [];
  4571. }
  4572. protected function loadNotifyTemplateRow(string $scene): ?array
  4573. {
  4574. try {
  4575. $row = Db::table('purchase_sms_template')
  4576. ->where('scene', $scene)
  4577. ->where(function ($q) {
  4578. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4579. })
  4580. ->order('id', 'asc')
  4581. ->find();
  4582. } catch (\Throwable $e) {
  4583. return null;
  4584. }
  4585. if (!is_array($row) || $row === []) {
  4586. return null;
  4587. }
  4588. return [
  4589. 'title' => trim((string)($row['title'] ?? '')),
  4590. 'content' => trim((string)($row['content'] ?? '')),
  4591. ];
  4592. }
  4593. /**
  4594. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4595. */
  4596. protected function buildProcessLinesHtml(array $mergeRows): string
  4597. {
  4598. if (count($mergeRows) <= 1) {
  4599. $r = $mergeRows[0] ?? [];
  4600. if (!is_array($r)) {
  4601. return '';
  4602. }
  4603. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4604. $dw = trim((string)($r['CDW'] ?? ''));
  4605. $gzl = trim((string)($r['NGZL'] ?? ''));
  4606. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4607. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4608. if ($dw !== '') {
  4609. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4610. }
  4611. if ($gzl !== '') {
  4612. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4613. }
  4614. if ($qty !== '') {
  4615. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4616. }
  4617. return $html;
  4618. }
  4619. $rows = '';
  4620. $i = 1;
  4621. foreach ($mergeRows as $r) {
  4622. if (!is_array($r)) {
  4623. continue;
  4624. }
  4625. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4626. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4627. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4628. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4629. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4630. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4631. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4632. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4633. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4634. $i++;
  4635. }
  4636. if ($rows === '') {
  4637. return '';
  4638. }
  4639. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4640. . '<thead><tr style="background:#f5f5f5;">'
  4641. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4642. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4643. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4644. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4645. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4646. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4647. }
  4648. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4649. {
  4650. $sysRq = trim($sysRq);
  4651. if ($sysRq === '') {
  4652. if ($required) {
  4653. $this->error('请选择截止时间');
  4654. }
  4655. return '';
  4656. }
  4657. $ts = strtotime($sysRq);
  4658. if ($ts === false || $ts <= 0) {
  4659. $this->error('截止时间格式无效');
  4660. }
  4661. return date('Y-m-d H:i:s', $ts);
  4662. }
  4663. protected function formatProcuremenSysRqForInput($sysRq): string
  4664. {
  4665. $sr = trim((string)$sysRq);
  4666. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4667. return '';
  4668. }
  4669. $ts = strtotime($sr);
  4670. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4671. }
  4672. /**
  4673. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4674. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4675. */
  4676. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4677. {
  4678. $sysRqPost = trim($sysRqPost);
  4679. if ($sysRqPost === '') {
  4680. return $bundle;
  4681. }
  4682. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4683. $pos = $bundle['pos'] ?? [];
  4684. foreach ($pos as $poRow) {
  4685. if (!is_array($poRow)) {
  4686. continue;
  4687. }
  4688. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4689. if (!$this->isValidScydgyRowId($sid)) {
  4690. continue;
  4691. }
  4692. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4693. }
  4694. foreach ($pos as $i => $poRow) {
  4695. if (is_array($pos[$i])) {
  4696. $pos[$i]['sys_rq'] = $sysRqDb;
  4697. }
  4698. }
  4699. $bundle['pos'] = $pos;
  4700. return $bundle;
  4701. }
  4702. /**
  4703. * 写入/更新 purchase_order(单道工序行)
  4704. */
  4705. protected function upsertPurchaseOrderFromRow(
  4706. array $row,
  4707. string $sysRqDb,
  4708. ?int $wflowStatus = null,
  4709. ?string $pickTime = null,
  4710. ?array $exists = null
  4711. ): void {
  4712. $ids = $this->extractScydgyRowId($row);
  4713. if (!$this->isValidScydgyRowId($ids)) {
  4714. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4715. }
  4716. if ($exists === null) {
  4717. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4718. }
  4719. $data = [
  4720. 'scydgy_id' => $ids,
  4721. 'CCYDH' => $row['CCYDH'] ?? null,
  4722. 'CYJMC' => $row['CYJMC'] ?? null,
  4723. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4724. 'CDXMC' => $row['CDXMC'] ?? null,
  4725. 'CGYBH' => $row['CGYBH'] ?? null,
  4726. 'CGYMC' => $row['CGYMC'] ?? null,
  4727. 'CDW' => $row['CDW'] ?? null,
  4728. 'NGZL' => $row['NGZL'] ?? null,
  4729. 'CDF' => $row['CDF'] ?? null,
  4730. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4731. 'MBZ' => $row['MBZ'] ?? null,
  4732. 'bwjg' => $row['bwjg'] ?? null,
  4733. 'iStatus' => $row['iStatus'] ?? null,
  4734. 'dStamp' => $row['dStamp'] ?? null,
  4735. 'dputrecord' => $row['dputrecord'] ?? null,
  4736. 'cywyxm' => $row['cywyxm'] ?? null,
  4737. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4738. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4739. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4740. 'sys_rq' => $sysRqDb,
  4741. ];
  4742. if ($wflowStatus !== null) {
  4743. $data['wflow_status'] = $wflowStatus;
  4744. }
  4745. if ($pickTime !== null && $pickTime !== '') {
  4746. $data['pick_time'] = $pickTime;
  4747. $data['pick_company_name'] = '';
  4748. }
  4749. if ($exists) {
  4750. $upd = $data;
  4751. unset($upd['scydgy_id']);
  4752. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4753. } else {
  4754. $data['createtime'] = date('Y-m-d H:i:s');
  4755. Db::table('purchase_order')->insert($data);
  4756. }
  4757. }
  4758. /**
  4759. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4760. *
  4761. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4762. */
  4763. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4764. {
  4765. $toDb = function ($value) {
  4766. if ($value === null) {
  4767. return null;
  4768. }
  4769. if (is_scalar($value)) {
  4770. return $value;
  4771. }
  4772. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4773. };
  4774. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4775. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4776. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4777. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4778. if ($username === '') {
  4779. $username = $this->resolveCustomerContactName($phone, $companyName);
  4780. }
  4781. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4782. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  4783. }
  4784. if ($phone === '') {
  4785. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  4786. }
  4787. $detailLinks = [];
  4788. foreach ($mergeRows as $row) {
  4789. if (!is_array($row)) {
  4790. continue;
  4791. }
  4792. $sid = $this->extractScydgyRowId($row);
  4793. $detailId = 0;
  4794. if ($skipExisting) {
  4795. try {
  4796. $existsQuery = Db::table('purchase_order_detail')
  4797. ->where('scydgy_id', $sid)
  4798. ->where('company_name', $companyName);
  4799. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  4800. $exists = $existsQuery->find();
  4801. } catch (\Throwable $e) {
  4802. $exists = null;
  4803. }
  4804. if (is_array($exists)) {
  4805. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  4806. }
  4807. }
  4808. if ($detailId <= 0) {
  4809. $one = [
  4810. 'scydgy_id' => $toDb($sid),
  4811. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  4812. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  4813. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  4814. 'username' => $username !== '' ? $username : null,
  4815. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  4816. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  4817. 'createtime' => date('Y-m-d H:i:s'),
  4818. 'status' => ProcuremenStatus::POD_UNPICKED,
  4819. 'status_name' => '未提交',
  4820. ];
  4821. Db::table('purchase_order_detail')->insert($one);
  4822. $detailId = (int)Db::getLastInsID();
  4823. }
  4824. $mprocUrl = '';
  4825. if ($buildMobileLinks && $detailId > 0) {
  4826. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  4827. }
  4828. $detailLinks[] = [
  4829. 'detail_id' => $detailId,
  4830. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  4831. 'url' => $mprocUrl,
  4832. ];
  4833. }
  4834. return $detailLinks;
  4835. }
  4836. /**
  4837. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  4838. * @return array<string, mixed>
  4839. */
  4840. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  4841. {
  4842. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4843. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4844. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4845. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  4846. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  4847. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  4848. $isMerge = !empty($ctx['is_merge']);
  4849. $contactName = trim((string)($c['username'] ?? ''));
  4850. if ($contactName === '') {
  4851. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  4852. }
  4853. $notifyVars = [
  4854. 'company_name' => $companyName,
  4855. 'contact_name' => $contactName,
  4856. 'phone' => $phone,
  4857. 'email' => $toEmail,
  4858. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  4859. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  4860. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  4861. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  4862. 'deadline' => (string)($ctx['deadline'] ?? ''),
  4863. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  4864. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  4865. 'platform_url' => $platformUrl,
  4866. 'platform_links' => $platformLinksPlain,
  4867. 'platform_links_html' => $platformLinksHtml,
  4868. ];
  4869. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  4870. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  4871. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4872. return [
  4873. 'company_name' => $companyName,
  4874. 'phone' => $phone,
  4875. 'email' => $toEmail,
  4876. 'sms_content' => $smsContent,
  4877. 'mail_plain' => $mailPlain,
  4878. 'mail_body' => $mailBody,
  4879. 'notify_vars' => $notifyVars,
  4880. 'detail_links' => $detailLinks,
  4881. ];
  4882. }
  4883. /**
  4884. * 确认供应商 — 向选定一家发送短信/邮件(第二步)
  4885. *
  4886. * @param array<string, mixed> $chosen
  4887. * @param array<int, array<string, mixed>> $mergeRows
  4888. * @param array{ccydh:string, pos:array} $bundle
  4889. */
  4890. protected function sendAuditSupplierConfirmNotify(array $chosen, array $mergeRows, array $bundle): void
  4891. {
  4892. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, true, true);
  4893. }
  4894. /**
  4895. * @param array<string, mixed> $chosen
  4896. * @param array<int, array<string, mixed>> $mergeRows
  4897. * @param array{ccydh:string, pos:array} $bundle
  4898. */
  4899. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  4900. {
  4901. if (!$sendSms && !$sendEmail) {
  4902. return;
  4903. }
  4904. $companyName = trim((string)($chosen['name'] ?? ''));
  4905. $phone = trim((string)($chosen['phone'] ?? ''));
  4906. $toEmail = trim((string)($chosen['email'] ?? ''));
  4907. if ($companyName === '') {
  4908. throw new \Exception('供应商名称无效');
  4909. }
  4910. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  4911. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  4912. }
  4913. if ($sendSms && $phone === '') {
  4914. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  4915. }
  4916. $sids = [];
  4917. foreach ($mergeRows as $mr) {
  4918. if (!is_array($mr)) {
  4919. continue;
  4920. }
  4921. $sid = $this->extractScydgyRowId($mr);
  4922. if ($this->isValidScydgyRowId($sid)) {
  4923. $sids[$sid] = true;
  4924. }
  4925. }
  4926. if ($sids === []) {
  4927. throw new \Exception('未找到工序行,无法发送通知');
  4928. }
  4929. $sysRqNotify = '';
  4930. $pos = $bundle['pos'] ?? [];
  4931. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  4932. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  4933. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  4934. $ts = strtotime($sr);
  4935. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  4936. }
  4937. }
  4938. try {
  4939. $detailsQuery = Db::table('purchase_order_detail')
  4940. ->where('scydgy_id', 'in', array_keys($sids))
  4941. ->where('company_name', $companyName);
  4942. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4943. $details = $detailsQuery->order('id', 'asc')->select();
  4944. } catch (\Throwable $e) {
  4945. $details = [];
  4946. }
  4947. if (!is_array($details) || $details === []) {
  4948. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  4949. try {
  4950. $detailsQuery = Db::table('purchase_order_detail')
  4951. ->where('scydgy_id', 'in', array_keys($sids))
  4952. ->where('company_name', $companyName);
  4953. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4954. $details = $detailsQuery->order('id', 'asc')->select();
  4955. } catch (\Throwable $e) {
  4956. $details = [];
  4957. }
  4958. }
  4959. if (!is_array($details) || $details === []) {
  4960. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  4961. }
  4962. $detailLinks = [];
  4963. foreach ($details as $d) {
  4964. if (!is_array($d)) {
  4965. continue;
  4966. }
  4967. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4968. if ($detailId <= 0) {
  4969. continue;
  4970. }
  4971. $sid = (int)($d['scydgy_id'] ?? 0);
  4972. $gymc = '';
  4973. foreach ($mergeRows as $mr) {
  4974. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  4975. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  4976. break;
  4977. }
  4978. }
  4979. $detailLinks[] = [
  4980. 'detail_id' => $detailId,
  4981. 'cgymc' => $gymc,
  4982. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  4983. ];
  4984. }
  4985. if ($detailLinks === []) {
  4986. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  4987. }
  4988. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  4989. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  4990. if ($sendEmail) {
  4991. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  4992. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  4993. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  4994. }
  4995. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  4996. $mailConfig = $this->loadMailerConfig();
  4997. if (!$this->isProcuremenNotifyDryRun()) {
  4998. if (empty($mailConfig['host'])) {
  4999. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5000. }
  5001. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5002. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5003. }
  5004. }
  5005. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5006. }
  5007. if ($sendSms) {
  5008. $this->issueSendSupplierSms($notifyBundle);
  5009. }
  5010. }
  5011. /**
  5012. * @param array<int, array<string, mixed>> $quoteGroups
  5013. * @return array<int, array<string, mixed>>
  5014. */
  5015. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5016. {
  5017. $names = [];
  5018. if (is_string($companiesJson) && $companiesJson !== '') {
  5019. $decoded = json_decode($companiesJson, true);
  5020. if (is_array($decoded)) {
  5021. foreach ($decoded as $nm) {
  5022. $nm = trim((string)$nm);
  5023. if ($nm !== '') {
  5024. $names[] = $nm;
  5025. }
  5026. }
  5027. }
  5028. }
  5029. $names = array_values(array_unique($names));
  5030. if ($names === [] && $selectedCompany !== '') {
  5031. $names = [$selectedCompany];
  5032. }
  5033. if ($names === []) {
  5034. return $quoteGroups;
  5035. }
  5036. $targets = [];
  5037. foreach ($quoteGroups as $g) {
  5038. if (!is_array($g)) {
  5039. continue;
  5040. }
  5041. $cn = trim((string)($g['name'] ?? ''));
  5042. if ($cn !== '' && in_array($cn, $names, true)) {
  5043. $targets[] = $g;
  5044. }
  5045. }
  5046. return $targets;
  5047. }
  5048. /**
  5049. * @return array{pos:array, merge_rows:array, bundle:array}
  5050. */
  5051. protected function loadAuditResendBundle(string $scydgyId): array
  5052. {
  5053. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5054. $pos = $bundle['pos'];
  5055. $mergeRows = $bundle['merge_rows'];
  5056. if ($pos === [] || $mergeRows === []) {
  5057. $this->error('该订单不在待确认供应商状态');
  5058. }
  5059. $sysRqDb = '';
  5060. if (isset($pos[0]) && is_array($pos[0])) {
  5061. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5062. }
  5063. foreach ($pos as $i => $poRow) {
  5064. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5065. $pos[$i]['sys_rq'] = $sysRqDb;
  5066. }
  5067. }
  5068. $bundle['pos'] = $pos;
  5069. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5070. }
  5071. /**
  5072. * @param array<int, array<string, mixed>> $targets
  5073. */
  5074. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5075. {
  5076. if ($targets === []) {
  5077. $this->error('未找到可通知的供应商');
  5078. }
  5079. $notifyErrors = [];
  5080. try {
  5081. $this->notifyDryRunPreview = [];
  5082. foreach ($targets as $g) {
  5083. if (!is_array($g)) {
  5084. continue;
  5085. }
  5086. $cname = trim((string)($g['name'] ?? ''));
  5087. if ($cname === '') {
  5088. continue;
  5089. }
  5090. $chosen = [
  5091. 'name' => $cname,
  5092. 'company_name' => $cname,
  5093. 'email' => trim((string)($g['email'] ?? '')),
  5094. 'phone' => trim((string)($g['phone'] ?? '')),
  5095. 'username' => trim((string)($g['username'] ?? '')),
  5096. ];
  5097. try {
  5098. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  5099. } catch (\Throwable $e) {
  5100. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5101. }
  5102. }
  5103. } catch (\Throwable $e) {
  5104. $this->error('通知发送失败:' . $e->getMessage());
  5105. }
  5106. if ($notifyErrors !== []) {
  5107. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5108. }
  5109. if ($this->isProcuremenNotifyDryRun()) {
  5110. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5111. 'notify_dry_run' => true,
  5112. 'notify_preview' => $this->notifyDryRunPreview,
  5113. ]);
  5114. }
  5115. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5116. }
  5117. /**
  5118. * 协助下发 — 写入下发明细并拼好短信/邮件内容(供第二步发送)
  5119. *
  5120. * @return array<string, mixed>
  5121. */
  5122. protected function issueBuildSupplierNotifyBundle(array $c, array $mergeRows, array $ctx): array
  5123. {
  5124. $detailLinks = $this->issuePersistSupplierDetails($c, $mergeRows);
  5125. return $this->composeSupplierNotifyBundle($c, $ctx, $detailLinks);
  5126. }
  5127. /**
  5128. * 协助下发 — 发送短信(一家供应商)
  5129. *
  5130. * @param array<string, mixed> $bundle issueBuildSupplierNotifyBundle 返回值
  5131. */
  5132. protected function issueSendSupplierSms(array $bundle): void
  5133. {
  5134. $companyName = (string)($bundle['company_name'] ?? '');
  5135. $phone = (string)($bundle['phone'] ?? '');
  5136. $smsContent = (string)($bundle['sms_content'] ?? '');
  5137. $this->logIssueNotifyDebug('短信', [
  5138. 'company' => $companyName,
  5139. 'phone' => $phone,
  5140. 'sms_content' => $smsContent,
  5141. ]);
  5142. if ($this->isProcuremenNotifyDryRun()) {
  5143. $this->recordNotifyDryRunPreview([
  5144. 'scene' => 'issue_sms',
  5145. 'company_name' => $companyName,
  5146. 'phone' => $phone,
  5147. 'sms_content' => $smsContent,
  5148. ]);
  5149. return;
  5150. }
  5151. $this->smsbao($phone, $smsContent);
  5152. }
  5153. /**
  5154. * 协助下发 — 发送邮件(一家供应商)
  5155. *
  5156. * @param array<string, mixed> $bundle
  5157. * @param array<string, mixed> $mailConfig
  5158. */
  5159. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5160. {
  5161. $companyName = (string)($bundle['company_name'] ?? '');
  5162. $toEmail = (string)($bundle['email'] ?? '');
  5163. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5164. $mailBody = (string)($bundle['mail_body'] ?? '');
  5165. $this->logIssueNotifyDebug('邮件', [
  5166. 'company' => $companyName,
  5167. 'email' => $toEmail,
  5168. 'mail_subject' => $mailSubject,
  5169. 'mail_body' => $mailPlain,
  5170. ]);
  5171. if ($this->isProcuremenNotifyDryRun()) {
  5172. $this->recordNotifyDryRunPreview([
  5173. 'scene' => 'issue_email',
  5174. 'company_name' => $companyName,
  5175. 'email' => $toEmail,
  5176. 'mail_subject' => $mailSubject,
  5177. 'mail_body' => $mailPlain,
  5178. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5179. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5180. 'detail_links' => $bundle['detail_links'] ?? [],
  5181. ]);
  5182. return;
  5183. }
  5184. $mail = new PHPMailer(true);
  5185. $mail->isSMTP();
  5186. $mail->Host = $mailConfig['host'];
  5187. $mail->SMTPAuth = true;
  5188. $mail->Username = $mailConfig['addr'];
  5189. $mail->Password = $mailConfig['pass'];
  5190. $mail->SMTPSecure = $mailConfig['security'];
  5191. $mail->Port = $mailConfig['port'];
  5192. $mail->CharSet = $mailConfig['charset'];
  5193. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5194. $mail->addAddress($toEmail, $companyName);
  5195. $mail->isHTML(true);
  5196. $mail->Subject = $mailSubject;
  5197. $mail->Body = $mailBody;
  5198. $mail->send();
  5199. }
  5200. /**
  5201. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5202. *
  5203. * @param array<int, array<string, mixed>> $mergeRows
  5204. * @return array<string, mixed>
  5205. */
  5206. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5207. {
  5208. $head = $mergeRows[0] ?? [];
  5209. $isMerge = count($mergeRows) > 1;
  5210. return [
  5211. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5212. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5213. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5214. 'is_merge' => $isMerge,
  5215. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5216. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5217. 'deadline' => $sysRqNotify,
  5218. ];
  5219. }
  5220. /**
  5221. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5222. *
  5223. * @param array<string, mixed> $data
  5224. */
  5225. protected function logIssueNotifyDebug(string $type, array $data): void
  5226. {
  5227. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5228. return;
  5229. }
  5230. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5231. }
  5232. /**
  5233. * 协助下发弹窗(选多家供应商并通知)
  5234. */
  5235. public function pickReview()
  5236. {
  5237. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  5238. $this->error(__('You have no permission'));
  5239. }
  5240. if ($this->request->isPost()) {
  5241. $this->error('请使用弹窗内「确认下发」提交');
  5242. }
  5243. $this->view->assign('pickMode', 1);
  5244. return $this->view->fetch('procuremen/review');
  5245. }
  5246. /**
  5247. * 协助新增(独立页面)
  5248. */
  5249. public function add()
  5250. {
  5251. if ($this->request->isPost()) {
  5252. $params = $this->request->post('row/a');
  5253. if (!is_array($params)) {
  5254. $this->error(__('Parameter %s can not be empty', ''));
  5255. }
  5256. [, $adminName] = $this->GetUseName();
  5257. $params['cywyxm'] = $adminName;
  5258. try {
  5259. $sid = $this->saveManualPickOrder($params);
  5260. } catch (\InvalidArgumentException $e) {
  5261. $this->error($e->getMessage());
  5262. } catch (\Throwable $e) {
  5263. $this->error($e->getMessage());
  5264. }
  5265. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5266. }
  5267. [, $adminName] = $this->GetUseName();
  5268. $this->view->assign('adminNickname', $adminName);
  5269. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  5270. return $this->view->fetch();
  5271. }
  5272. /**
  5273. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  5274. */
  5275. public function rfqlist()
  5276. {
  5277. $this->relationSearch = false;
  5278. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  5279. $this->request->filter(['strip_tags', 'trim']);
  5280. if ($this->request->isAjax()) {
  5281. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  5282. $limit = max(10, min(500, (int)$limit));
  5283. $applyFilters = function ($query) use ($where) {
  5284. $query->where('scydgy_id', '<', 0);
  5285. $query->whereRaw(
  5286. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5287. );
  5288. if (!$this->auth->isSuperAdmin()) {
  5289. [, $adminName] = $this->GetUseName();
  5290. $query->where('cywyxm', $adminName);
  5291. }
  5292. if (!empty($where)) {
  5293. $query->where($where);
  5294. }
  5295. };
  5296. $countQuery = Db::table('purchase_order');
  5297. $applyFilters($countQuery);
  5298. $total = (int)$countQuery->count();
  5299. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  5300. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  5301. $listQuery = Db::table('purchase_order');
  5302. $applyFilters($listQuery);
  5303. $rows = $listQuery
  5304. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  5305. ->order($sortField, $orderDir)
  5306. ->limit($offset, $limit)
  5307. ->select();
  5308. if (!is_array($rows)) {
  5309. $rows = [];
  5310. }
  5311. $out = [];
  5312. foreach ($rows as $r) {
  5313. if (!is_array($r)) {
  5314. continue;
  5315. }
  5316. $sid = (int)($r['scydgy_id'] ?? 0);
  5317. if ($sid >= 0) {
  5318. continue;
  5319. }
  5320. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  5321. if ($createdText === '') {
  5322. $createdText = trim((string)($r['dStamp'] ?? ''));
  5323. }
  5324. $out[] = [
  5325. 'id' => (int)($r['id'] ?? 0),
  5326. 'scydgy_id' => $sid,
  5327. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5328. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5329. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5330. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5331. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5332. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  5333. 'createtime' => $r['createtime'] ?? null,
  5334. 'createtime_text' => $createdText,
  5335. ];
  5336. }
  5337. return json(['total' => $total, 'rows' => $out]);
  5338. }
  5339. [, $adminName] = $this->GetUseName();
  5340. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  5341. $this->view->assign('adminNickname', $adminName);
  5342. return $this->view->fetch('procuremen/rfqlist');
  5343. }
  5344. /**
  5345. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  5346. */
  5347. public function rfqlistDetails()
  5348. {
  5349. return $this->details();
  5350. }
  5351. /**
  5352. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  5353. */
  5354. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  5355. {
  5356. if ($scydgyId >= 0) {
  5357. return;
  5358. }
  5359. try {
  5360. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5361. } catch (\Throwable $e) {
  5362. $po = null;
  5363. }
  5364. if (!is_array($po)) {
  5365. $this->error('订单不存在');
  5366. }
  5367. $modRq = trim((string)($po['mod_rq'] ?? ''));
  5368. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  5369. $this->error('订单不存在');
  5370. }
  5371. if ($this->auth->isSuperAdmin()) {
  5372. return;
  5373. }
  5374. [, $adminName] = $this->GetUseName();
  5375. $cywy = trim((string)($po['cywyxm'] ?? ''));
  5376. if ($cywy !== '' && $cywy === $adminName) {
  5377. return;
  5378. }
  5379. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  5380. try {
  5381. if ($this->auth->check($rule)) {
  5382. return;
  5383. }
  5384. } catch (\Throwable $e) {
  5385. }
  5386. }
  5387. $this->error('无权查看该订单');
  5388. }
  5389. /**
  5390. * @deprecated 使用 {@see assertManualOrderDetailsViewable}
  5391. */
  5392. protected function assertRfqRowViewable(int $scydgyId): void
  5393. {
  5394. $this->assertManualOrderDetailsViewable($scydgyId);
  5395. }
  5396. /**
  5397. * 手工新增协助工序进度文案
  5398. */
  5399. protected function formatProcuremenRfqProgressText(array $row): string
  5400. {
  5401. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  5402. return ProcuremenStatus::PO_COMPLETED;
  5403. }
  5404. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  5405. return '待采购确认';
  5406. }
  5407. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  5408. return '待确认供应商';
  5409. }
  5410. $sid = (int)($row['scydgy_id'] ?? 0);
  5411. if ($sid < 0) {
  5412. try {
  5413. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  5414. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  5415. $detCnt = (int)$detCntQuery->count();
  5416. if ($detCnt > 0) {
  5417. return '已下发待确认';
  5418. }
  5419. } catch (\Throwable $e) {
  5420. }
  5421. }
  5422. return '待协助下发';
  5423. }
  5424. /**
  5425. * 协助初选列表 — 批量软删除
  5426. */
  5427. public function pickDelete()
  5428. {
  5429. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5430. $this->error(__('Invalid parameters'));
  5431. }
  5432. if (!$this->procuremenCanPickDelete()) {
  5433. $this->error(__('You have no permission'));
  5434. }
  5435. $rowsRaw = $this->request->post('rows_json', '[]');
  5436. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  5437. if (!is_array($rows) || $rows === []) {
  5438. $this->error('请至少勾选一条工序');
  5439. }
  5440. $done = 0;
  5441. Db::startTrans();
  5442. try {
  5443. foreach ($rows as $row) {
  5444. if (!is_array($row)) {
  5445. continue;
  5446. }
  5447. $this->softDeleteProcuremenPickRow($row);
  5448. $done++;
  5449. }
  5450. if ($done < 1) {
  5451. throw new \Exception('没有可删除的工序');
  5452. }
  5453. Db::commit();
  5454. } catch (\InvalidArgumentException $e) {
  5455. Db::rollback();
  5456. $this->error($e->getMessage());
  5457. } catch (\Throwable $e) {
  5458. Db::rollback();
  5459. $this->error($e->getMessage());
  5460. }
  5461. $this->success('已删除 ' . $done . ' 条工序');
  5462. }
  5463. /**
  5464. * 协助下发 — 手工新增工序(弹窗)
  5465. */
  5466. public function pickAdd()
  5467. {
  5468. if ($this->request->isPost()) {
  5469. $params = $this->request->post('row/a');
  5470. if (!is_array($params)) {
  5471. $this->error(__('Parameter %s can not be empty', ''));
  5472. }
  5473. try {
  5474. $sid = $this->saveManualPickOrder($params);
  5475. } catch (\InvalidArgumentException $e) {
  5476. $this->error($e->getMessage());
  5477. } catch (\Throwable $e) {
  5478. $this->error($e->getMessage());
  5479. }
  5480. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5481. }
  5482. return $this->view->fetch('procuremen/pick_add');
  5483. }
  5484. /**
  5485. * 协助下发提交 — 弹窗「确认下发」→ POST procuremen/picksubmit
  5486. */
  5487. public function pickSubmit()
  5488. {
  5489. if (!$this->request->isPost()) {
  5490. $this->error(__('Invalid parameters'));
  5491. }
  5492. // ---------- 接口订单数据 ----------
  5493. $rowJson = $this->request->post('row_json', '');
  5494. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5495. $companiesJson = $this->request->post('companies_json', '[]');
  5496. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5497. $companies = json_decode($companiesJson, true);
  5498. if (!is_array($companies)) {
  5499. $this->error('供应商数据无效');
  5500. }
  5501. $issueCompanies = $this->normalizePickCompanies($companies);
  5502. if ($issueCompanies === []) {
  5503. $this->error('请至少选择一家合作供应商');
  5504. }
  5505. $issueNameLabels = [];
  5506. foreach ($issueCompanies as $pc) {
  5507. $issueNameLabels[] = $pc['name'];
  5508. }
  5509. $issueNamesSummary = implode('、', $issueNameLabels);
  5510. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5511. if ($sysRq === '') {
  5512. $this->error('请选择截止时间');
  5513. }
  5514. $sysRqTs = strtotime($sysRq);
  5515. if ($sysRqTs === false || $sysRqTs <= 0) {
  5516. $this->error('截止时间格式无效');
  5517. }
  5518. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5519. $isMerge = count($mergeRows) > 1;
  5520. $logMsg = ($isMerge ? '合并协助初选(' . count($mergeRows) . ' 道工序)' : '协助初选')
  5521. . ',通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5522. $issueTime = date('Y-m-d H:i:s');
  5523. $logSidList = [];
  5524. foreach ($mergeRows as $row) {
  5525. if (!is_array($row)) {
  5526. continue;
  5527. }
  5528. $sid = $this->extractScydgyRowId($row);
  5529. if ($this->isValidScydgyRowId($sid)) {
  5530. $logSidList[$sid] = true;
  5531. }
  5532. }
  5533. $existingBySid = [];
  5534. if ($logSidList !== []) {
  5535. try {
  5536. $existingRows = Db::table('purchase_order')
  5537. ->where('scydgy_id', 'in', array_keys($logSidList))
  5538. ->select();
  5539. if (is_array($existingRows)) {
  5540. foreach ($existingRows as $poRow) {
  5541. if (!is_array($poRow)) {
  5542. continue;
  5543. }
  5544. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5545. if ($this->isValidScydgyRowId($sid)) {
  5546. $existingBySid[$sid] = $poRow;
  5547. }
  5548. }
  5549. }
  5550. } catch (\Throwable $e) {
  5551. $existingBySid = [];
  5552. }
  5553. }
  5554. Db::startTrans();
  5555. try {
  5556. // ---------- 主表 wflow_status=1;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5557. foreach ($mergeRows as $row) {
  5558. if (!is_array($row)) {
  5559. continue;
  5560. }
  5561. $sid = $this->extractScydgyRowId($row);
  5562. $this->upsertPurchaseOrderFromRow(
  5563. $row,
  5564. $sysRqDb,
  5565. 1,
  5566. $issueTime,
  5567. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5568. );
  5569. }
  5570. foreach ($issueCompanies as $c) {
  5571. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5572. }
  5573. Db::commit();
  5574. } catch (\Throwable $e) {
  5575. Db::rollback();
  5576. $this->error($e->getMessage());
  5577. }
  5578. $poIdBySid = [];
  5579. if ($logSidList !== []) {
  5580. try {
  5581. $poIdBySid = Db::table('purchase_order')
  5582. ->where('scydgy_id', 'in', array_keys($logSidList))
  5583. ->column('id', 'scydgy_id');
  5584. } catch (\Throwable $e) {
  5585. $poIdBySid = [];
  5586. }
  5587. }
  5588. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5589. if ($logSidList !== []) {
  5590. list($adminId, $adminName) = $this->GetUseName();
  5591. $cut = function ($s, $max) {
  5592. if (function_exists('mb_substr')) {
  5593. return mb_substr($s, 0, $max, 'UTF-8');
  5594. }
  5595. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5596. };
  5597. $logRows = [];
  5598. $seenLogSid = [];
  5599. foreach ($mergeRows as $row) {
  5600. if (!is_array($row)) {
  5601. continue;
  5602. }
  5603. $ids = $this->extractScydgyRowId($row);
  5604. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5605. continue;
  5606. }
  5607. $seenLogSid[$ids] = true;
  5608. $poIdLog = null;
  5609. if (isset($poIdBySid[$ids])) {
  5610. $tid = (int)$poIdBySid[$ids];
  5611. $poIdLog = $tid > 0 ? $tid : null;
  5612. }
  5613. $logRows[] = [
  5614. 'scydgy_id' => $ids,
  5615. 'purchase_order_id' => $poIdLog,
  5616. 'admin_id' => $adminId,
  5617. 'admin_name' => $cut($adminName, 64),
  5618. 'action' => $cut('issue_submit', 64),
  5619. 'content' => $cut($logMsg, 1000),
  5620. 'createtime' => time(),
  5621. ];
  5622. }
  5623. if ($logRows !== []) {
  5624. try {
  5625. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5626. } catch (\Throwable $e) {
  5627. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5628. }
  5629. }
  5630. }
  5631. $notifyErrors = [];
  5632. $posNotify = [];
  5633. if ($logSidList !== []) {
  5634. try {
  5635. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5636. } catch (\Throwable $e) {
  5637. $posNotify = [];
  5638. }
  5639. }
  5640. if (!is_array($posNotify)) {
  5641. $posNotify = [];
  5642. }
  5643. foreach ($posNotify as $i => $prow) {
  5644. if (is_array($posNotify[$i])) {
  5645. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5646. }
  5647. }
  5648. $ccydhPick = '';
  5649. foreach ($mergeRows as $row) {
  5650. if (!is_array($row)) {
  5651. continue;
  5652. }
  5653. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5654. if ($ccydhPick !== '') {
  5655. break;
  5656. }
  5657. }
  5658. $notifyBundleBase = [
  5659. 'ccydh' => $ccydhPick,
  5660. 'pos' => $posNotify,
  5661. 'merge_rows' => $mergeRows,
  5662. ];
  5663. try {
  5664. $this->notifyDryRunPreview = [];
  5665. foreach ($issueCompanies as $c) {
  5666. if (!is_array($c)) {
  5667. continue;
  5668. }
  5669. $cname = trim((string)($c['name'] ?? ''));
  5670. if ($cname === '') {
  5671. continue;
  5672. }
  5673. try {
  5674. $this->sendAuditSupplierConfirmNotify($c, $mergeRows, $notifyBundleBase);
  5675. } catch (\Throwable $e) {
  5676. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5677. }
  5678. }
  5679. } catch (\Throwable $e) {
  5680. $this->error('通知发送失败:' . $e->getMessage());
  5681. }
  5682. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5683. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5684. }
  5685. if ($this->isProcuremenNotifyDryRun()) {
  5686. $this->success('【演练模式】已保存并生成通知预览', '', [
  5687. 'notify_dry_run' => true,
  5688. 'notify_preview' => $this->notifyDryRunPreview,
  5689. ]);
  5690. }
  5691. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  5692. }
  5693. /**
  5694. * 确认供应商弹窗
  5695. */
  5696. public function auditIssue()
  5697. {
  5698. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5699. if (is_array($ids)) {
  5700. $ids = isset($ids[0]) ? $ids[0] : '';
  5701. }
  5702. $ids = trim((string)$ids);
  5703. if ($ids === '') {
  5704. $this->error(__('Invalid parameters'));
  5705. }
  5706. if ($this->request->isPost()) {
  5707. $this->error('请使用弹窗内「确认」提交');
  5708. }
  5709. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5710. $pos = $bundle['pos'];
  5711. if ($pos === []) {
  5712. $this->error('该订单不在待确认供应商状态');
  5713. }
  5714. $po = $pos[0];
  5715. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5716. if ($quoteGroups === []) {
  5717. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  5718. }
  5719. $pickedName = '';
  5720. foreach ($pos as $poRow) {
  5721. if (!is_array($poRow)) {
  5722. continue;
  5723. }
  5724. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5725. if ($pn !== '') {
  5726. $pickedName = $pn;
  5727. break;
  5728. }
  5729. }
  5730. $this->view->assign('po', $po);
  5731. $this->view->assign('scydgyId', $ids);
  5732. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5733. $mergeRows = $bundle['merge_rows'];
  5734. $this->view->assign('processRows', $mergeRows);
  5735. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5736. $this->view->assign('processCount', count($mergeRows));
  5737. $this->view->assign('quoteGroups', $quoteGroups);
  5738. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5739. $this->view->assign('pickedCompanyName', $pickedName);
  5740. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5741. return $this->view->fetch('procuremen/audit_issue');
  5742. }
  5743. /**
  5744. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5745. */
  5746. public function auditSubmit()
  5747. {
  5748. if (!$this->request->isPost()) {
  5749. $this->error(__('Invalid parameters'));
  5750. }
  5751. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5752. if ($scydgyId === '') {
  5753. $this->error('参数无效');
  5754. }
  5755. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5756. $pos = $bundle['pos'];
  5757. $mergeRows = $bundle['merge_rows'];
  5758. if ($pos === [] || $mergeRows === []) {
  5759. $this->error('该订单不在待确认供应商状态');
  5760. }
  5761. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5762. if ($quoteGroups === []) {
  5763. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  5764. }
  5765. $companyName = trim((string)$this->request->post('selected_company', ''));
  5766. if ($companyName === '') {
  5767. $this->error('请选择一家供应商');
  5768. }
  5769. $matched = null;
  5770. foreach ($quoteGroups as $g) {
  5771. if (!is_array($g)) {
  5772. continue;
  5773. }
  5774. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5775. $matched = $g;
  5776. break;
  5777. }
  5778. }
  5779. if ($matched === null) {
  5780. $this->error('所选供应商不在本单报价列表中');
  5781. }
  5782. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5783. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5784. $procCnt = count($mergeRows);
  5785. $logMsg = '确认供应商(订单' . ($ccydhLog !== '' ? $ccydhLog : '')
  5786. . ($procCnt > 1 ? ',' . $procCnt . ' 道工序' : '')
  5787. . '),选定:' . $companyName;
  5788. Db::startTrans();
  5789. try {
  5790. foreach ($pos as $poRow) {
  5791. if (!is_array($poRow)) {
  5792. continue;
  5793. }
  5794. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5795. if (!$this->isValidScydgyRowId($sid)) {
  5796. continue;
  5797. }
  5798. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5799. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  5800. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5801. 'pick_company_name' => $companyName,
  5802. 'sys_rq' => $sysRqDb,
  5803. ]);
  5804. }
  5805. Db::commit();
  5806. } catch (\Throwable $e) {
  5807. Db::rollback();
  5808. $this->error($e->getMessage());
  5809. }
  5810. foreach ($pos as $poRow) {
  5811. if (!is_array($poRow)) {
  5812. continue;
  5813. }
  5814. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5815. if (!$this->isValidScydgyRowId($sid)) {
  5816. continue;
  5817. }
  5818. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  5819. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  5820. }
  5821. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  5822. }
  5823. /**
  5824. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  5825. */
  5826. public function auditResendSms()
  5827. {
  5828. if (!$this->request->isPost()) {
  5829. $this->error(__('Invalid parameters'));
  5830. }
  5831. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5832. if ($scydgyId === '') {
  5833. $this->error('参数无效');
  5834. }
  5835. $loaded = $this->loadAuditResendBundle($scydgyId);
  5836. $mergeRows = $loaded['merge_rows'];
  5837. $bundle = $loaded['bundle'];
  5838. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5839. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5840. if ($quoteGroups === []) {
  5841. $this->error('暂无可通知的供应商');
  5842. }
  5843. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5844. $companiesJson = (string)$this->request->post('companies_json', '');
  5845. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5846. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  5847. }
  5848. /**
  5849. * 确认供应商 — 二次发送邮件(可选单家/批量)
  5850. */
  5851. public function auditResendEmail()
  5852. {
  5853. if (!$this->request->isPost()) {
  5854. $this->error(__('Invalid parameters'));
  5855. }
  5856. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5857. if ($scydgyId === '') {
  5858. $this->error('参数无效');
  5859. }
  5860. $loaded = $this->loadAuditResendBundle($scydgyId);
  5861. $mergeRows = $loaded['merge_rows'];
  5862. $bundle = $loaded['bundle'];
  5863. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5864. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5865. if ($quoteGroups === []) {
  5866. $this->error('暂无可通知的供应商');
  5867. }
  5868. $companiesJson = (string)$this->request->post('companies_json', '');
  5869. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5870. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5871. if ($companiesJson === '' && $selectedCompany === '') {
  5872. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  5873. }
  5874. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  5875. }
  5876. /**
  5877. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  5878. *
  5879. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5880. * @return array<int, true> 已处理的 scydgy_id 集合
  5881. */
  5882. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  5883. {
  5884. $pos = $bundle['pos'] ?? [];
  5885. if (!is_array($pos) || $pos === []) {
  5886. return [];
  5887. }
  5888. $sids = [];
  5889. foreach ($pos as $poRow) {
  5890. if (!is_array($poRow)) {
  5891. continue;
  5892. }
  5893. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5894. if ($this->isValidScydgyRowId($sid)) {
  5895. $sids[$sid] = true;
  5896. }
  5897. }
  5898. if ($sids === []) {
  5899. return [];
  5900. }
  5901. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5902. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '') . $logSuffix;
  5903. Db::table('purchase_order')
  5904. ->where('scydgy_id', 'in', array_keys($sids))
  5905. ->update([
  5906. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  5907. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5908. 'pick_company_name' => '',
  5909. 'pick_time' => null,
  5910. 'sys_rq' => null,
  5911. 'mod_rq' => null,
  5912. ]);
  5913. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  5914. foreach (array_keys($sids) as $sid) {
  5915. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  5916. }
  5917. return $sids;
  5918. }
  5919. /**
  5920. * 废弃单个审批订单 bundle(退回协助初选,明细归档留痕)
  5921. *
  5922. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5923. * @return array<int, true> 已处理的 scydgy_id 集合
  5924. */
  5925. protected function abandonAuditOrderBundle(array $bundle): array
  5926. {
  5927. return $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  5928. }
  5929. /**
  5930. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  5931. *
  5932. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5933. */
  5934. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  5935. {
  5936. $scydgyId = trim($scydgyId);
  5937. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5938. if ($scydgyId === '') {
  5939. return $empty;
  5940. }
  5941. try {
  5942. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5943. } catch (\Throwable $e) {
  5944. $anchor = null;
  5945. }
  5946. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  5947. return $empty;
  5948. }
  5949. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5950. if ($ccydh === '') {
  5951. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5952. }
  5953. try {
  5954. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5955. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  5956. $pos = $query->order('scydgy_id', 'asc')->select();
  5957. } catch (\Throwable $e) {
  5958. $pos = [$anchor];
  5959. }
  5960. if (!is_array($pos) || $pos === []) {
  5961. $pos = [$anchor];
  5962. }
  5963. return [
  5964. 'ccydh' => $ccydh,
  5965. 'pos' => $pos,
  5966. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5967. ];
  5968. }
  5969. protected function purchaseOrderRowIsCompleted(array $po): bool
  5970. {
  5971. $st = $po['status'] ?? null;
  5972. if ($st === 1 || $st === '1') {
  5973. return true;
  5974. }
  5975. if (is_string($st) && trim($st) === '1') {
  5976. return true;
  5977. }
  5978. return is_numeric($st) && (int)$st === 1;
  5979. }
  5980. /**
  5981. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  5982. */
  5983. public function auditAbandon()
  5984. {
  5985. if (!$this->request->isPost()) {
  5986. $this->error(__('Invalid parameters'));
  5987. }
  5988. $anchorIds = [];
  5989. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5990. if ($batchRaw !== '') {
  5991. $decoded = json_decode($batchRaw, true);
  5992. if (is_array($decoded)) {
  5993. foreach ($decoded as $id) {
  5994. $s = trim((string)$id);
  5995. if ($s !== '') {
  5996. $anchorIds[] = $s;
  5997. }
  5998. }
  5999. }
  6000. }
  6001. if ($anchorIds === []) {
  6002. $single = trim((string)$this->request->post('scydgy_id', ''));
  6003. if ($single !== '') {
  6004. $anchorIds[] = $single;
  6005. }
  6006. }
  6007. if ($anchorIds === []) {
  6008. $this->error('请至少选择一条订单');
  6009. }
  6010. $processedCcydh = [];
  6011. $doneOrders = 0;
  6012. $allSids = [];
  6013. Db::startTrans();
  6014. try {
  6015. foreach ($anchorIds as $anchorId) {
  6016. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  6017. if (($bundle['pos'] ?? []) === []) {
  6018. continue;
  6019. }
  6020. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6021. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6022. if (isset($processedCcydh[$dedupeKey])) {
  6023. continue;
  6024. }
  6025. $processedCcydh[$dedupeKey] = true;
  6026. $sids = $this->abandonAuditOrderBundle($bundle);
  6027. if ($sids === []) {
  6028. continue;
  6029. }
  6030. $doneOrders++;
  6031. foreach (array_keys($sids) as $sid) {
  6032. $allSids[(int)$sid] = true;
  6033. }
  6034. }
  6035. if ($doneOrders < 1) {
  6036. throw new \Exception('所选订单均不在待确认供应商状态');
  6037. }
  6038. Db::commit();
  6039. } catch (\Throwable $e) {
  6040. Db::rollback();
  6041. $this->error($e->getMessage());
  6042. }
  6043. $this->pickHiddenScydgySetCache = null;
  6044. $msg = $doneOrders > 1
  6045. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  6046. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  6047. $this->success($msg);
  6048. }
  6049. /**
  6050. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  6051. */
  6052. public function archiveAbandon()
  6053. {
  6054. if (!$this->request->isPost()) {
  6055. $this->error(__('Invalid parameters'));
  6056. }
  6057. $anchorIds = [];
  6058. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6059. if ($batchRaw !== '') {
  6060. $decoded = json_decode($batchRaw, true);
  6061. if (is_array($decoded)) {
  6062. foreach ($decoded as $id) {
  6063. $s = trim((string)$id);
  6064. if ($s !== '') {
  6065. $anchorIds[] = $s;
  6066. }
  6067. }
  6068. }
  6069. }
  6070. if ($anchorIds === []) {
  6071. $single = trim((string)$this->request->post('scydgy_id', ''));
  6072. if ($single !== '') {
  6073. $anchorIds[] = $single;
  6074. }
  6075. }
  6076. if ($anchorIds === []) {
  6077. $this->error('请至少选择一条订单');
  6078. }
  6079. $processedCcydh = [];
  6080. $doneOrders = 0;
  6081. Db::startTrans();
  6082. try {
  6083. foreach ($anchorIds as $anchorId) {
  6084. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  6085. if (($bundle['pos'] ?? []) === []) {
  6086. continue;
  6087. }
  6088. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6089. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6090. if (isset($processedCcydh[$dedupeKey])) {
  6091. continue;
  6092. }
  6093. $processedCcydh[$dedupeKey] = true;
  6094. $sids = $this->abandonOrderBundleToPick(
  6095. $bundle,
  6096. 'archive_abandon',
  6097. ',从历史存证退回协助初选'
  6098. );
  6099. if ($sids === []) {
  6100. continue;
  6101. }
  6102. $doneOrders++;
  6103. }
  6104. if ($doneOrders < 1) {
  6105. throw new \Exception('所选订单均不是已完结状态');
  6106. }
  6107. Db::commit();
  6108. } catch (\Throwable $e) {
  6109. Db::rollback();
  6110. $this->error($e->getMessage());
  6111. }
  6112. $this->pickHiddenScydgySetCache = null;
  6113. $msg = $doneOrders > 1
  6114. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  6115. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  6116. $this->success($msg);
  6117. }
  6118. /**
  6119. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  6120. */
  6121. public function purchaseApprovalReject()
  6122. {
  6123. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6124. $this->error(__('Invalid parameters'));
  6125. }
  6126. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  6127. $decoded = json_decode($batchRaw, true);
  6128. if (!is_array($decoded) || $decoded === []) {
  6129. $this->error('提交数据无效');
  6130. }
  6131. Db::startTrans();
  6132. try {
  6133. foreach ($decoded as $item) {
  6134. if (!is_array($item)) {
  6135. continue;
  6136. }
  6137. $sid = (int)($item['scydgy_id'] ?? 0);
  6138. if (!$this->isValidScydgyRowId($sid)) {
  6139. continue;
  6140. }
  6141. $this->runPurchaseApprovalRejectForSid($sid);
  6142. }
  6143. Db::commit();
  6144. } catch (\Throwable $e) {
  6145. Db::rollback();
  6146. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  6147. }
  6148. $this->success('已驳回并退回「协助审批下发」');
  6149. }
  6150. /**
  6151. * @throws \Exception
  6152. */
  6153. protected function runPurchaseApprovalRejectForSid(int $sid): void
  6154. {
  6155. $allIds = $this->purchaseOrderDetail($sid);
  6156. if ($allIds === []) {
  6157. throw new \Exception('未找到下发明细');
  6158. }
  6159. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6160. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6161. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6162. 'pick_company_name' => '',
  6163. ]);
  6164. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  6165. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  6166. $poId = 0;
  6167. try {
  6168. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6169. if (is_array($po)) {
  6170. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6171. }
  6172. } catch (\Throwable $e) {
  6173. }
  6174. $this->addOrderLog($sid, 'purchase_reject', '采购终审驳回,退回协助审批下发', $poId > 0 ? $poId : null);
  6175. }
  6176. /**
  6177. * 审核弹窗(旧入口,POST 已关闭)
  6178. */
  6179. public function review()
  6180. {
  6181. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  6182. $this->error(__('You have no permission'));
  6183. }
  6184. if ($this->request->isPost()) {
  6185. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  6186. }
  6187. $this->view->assign('pickMode', 0);
  6188. return $this->view->fetch('procuremen/review');
  6189. }
  6190. /**
  6191. * 审核弹窗获取公司列表
  6192. */
  6193. public function reviewCompanies()
  6194. {
  6195. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  6196. $this->error(__('You have no permission'));
  6197. }
  6198. if (!$this->request->isAjax()) {
  6199. $this->error(__('Invalid parameters'));
  6200. }
  6201. $list = [];
  6202. try {
  6203. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  6204. $rows = Db::table('customer')
  6205. ->where(function ($q) {
  6206. $q->where('status', 1)
  6207. ->whereOr('status', '1')
  6208. ->whereOr('status', '')
  6209. ->whereNull('status');
  6210. })
  6211. ->order('id', 'desc')
  6212. ->select();
  6213. } catch (\Throwable $e) {
  6214. $this->success('', '', []);
  6215. return;
  6216. }
  6217. if (!is_array($rows)) {
  6218. $this->success('', '', []);
  6219. return;
  6220. }
  6221. $detailColCandidates = [
  6222. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  6223. 'company_detail', 'company_desc', 'address',
  6224. ];
  6225. foreach ($rows as $row) {
  6226. if (!is_array($row)) {
  6227. continue;
  6228. }
  6229. $norm = [];
  6230. foreach ($row as $k => $v) {
  6231. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6232. }
  6233. $row = $norm;
  6234. $st = $row['status'] ?? '';
  6235. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6236. continue;
  6237. }
  6238. $id = isset($row['id']) ? (string)$row['id'] : '';
  6239. $companyName = '';
  6240. foreach (['company_name', 'name'] as $nk) {
  6241. if (!empty($row[$nk])) {
  6242. $companyName = trim((string)$row[$nk]);
  6243. break;
  6244. }
  6245. }
  6246. $username = '';
  6247. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6248. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6249. $username = trim((string)$row[$uk]);
  6250. break;
  6251. }
  6252. }
  6253. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6254. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6255. if ($phone === '' && isset($row['account'])) {
  6256. $phone = trim((string)$row['account']);
  6257. }
  6258. if ($phone === '' && isset($row['mobile'])) {
  6259. $phone = trim((string)$row['mobile']);
  6260. }
  6261. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  6262. if ($email === '' && $phone === '') {
  6263. continue;
  6264. }
  6265. $category = '';
  6266. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6267. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6268. $category = trim((string)$row[$ck]);
  6269. break;
  6270. }
  6271. }
  6272. $detail = '';
  6273. foreach ($detailColCandidates as $dk) {
  6274. if (!isset($row[$dk])) {
  6275. continue;
  6276. }
  6277. $dv = trim((string)$row[$dk]);
  6278. if ($dv !== '') {
  6279. $detail = $dv;
  6280. break;
  6281. }
  6282. }
  6283. $list[] = [
  6284. 'id' => $id,
  6285. 'name' => $companyName,
  6286. 'company_name' => $companyName,
  6287. 'username' => $username,
  6288. 'email' => $email,
  6289. 'phone' => $phone,
  6290. 'category' => $category,
  6291. 'company_type' => $category,
  6292. 'detail' => $detail,
  6293. ];
  6294. }
  6295. $this->success('', '', $list);
  6296. }
  6297. /**
  6298. * 采购确认-下发明细弹窗:
  6299. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  6300. */
  6301. public function outward_detail()
  6302. {
  6303. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6304. if (is_array($ids)) {
  6305. $ids = isset($ids[0]) ? $ids[0] : '';
  6306. }
  6307. $ids = trim((string)$ids);
  6308. if ($ids === '') {
  6309. $this->error(__('Invalid parameters'));
  6310. }
  6311. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  6312. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  6313. $wffTab = 'all';
  6314. }
  6315. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  6316. $purchaseOrderId = 0;
  6317. $po = null;
  6318. try {
  6319. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6320. if (is_array($po)) {
  6321. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6322. }
  6323. } catch (\Throwable $e) {
  6324. $purchaseOrderId = 0;
  6325. $po = null;
  6326. }
  6327. if (!$isPurchaseConfirm && is_array($po)) {
  6328. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  6329. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  6330. $isPurchaseConfirm = true;
  6331. }
  6332. }
  6333. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  6334. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6335. $confirmProcessCount = 1;
  6336. $confirmPickGroups = [];
  6337. $processDisplayRows = [];
  6338. $allDetailsBySid = [];
  6339. $requiredSidList = [];
  6340. $sidList = [$ids];
  6341. if ($isPurchaseConfirm) {
  6342. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  6343. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  6344. if ($mergeRows !== []) {
  6345. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6346. }
  6347. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  6348. if ($confirmBundle['pos'] !== []) {
  6349. $sidList = [];
  6350. foreach ($confirmBundle['pos'] as $poRow) {
  6351. if (!is_array($poRow)) {
  6352. continue;
  6353. }
  6354. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6355. if (!$this->isValidScydgyRowId($sid)) {
  6356. continue;
  6357. }
  6358. $sidList[] = (string)$sid;
  6359. $requiredSidList[] = $sid;
  6360. }
  6361. }
  6362. if ($sidList === []) {
  6363. $sidList = [$ids];
  6364. $requiredSidList = [(int)$ids];
  6365. }
  6366. $confirmProcessCount = max(1, count($requiredSidList));
  6367. if (is_array($po) && $purchaseOrderId <= 0) {
  6368. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6369. }
  6370. }
  6371. $rows = [];
  6372. try {
  6373. if (count($sidList) === 1) {
  6374. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  6375. } else {
  6376. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  6377. }
  6378. } catch (\Throwable $e) {
  6379. $rows = [];
  6380. }
  6381. if ($isPurchaseConfirm) {
  6382. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  6383. }
  6384. foreach ($rows as &$r) {
  6385. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6386. $r['id'] = $r['ID'];
  6387. }
  6388. if (isset($r['createtime'])) {
  6389. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6390. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6391. } else {
  6392. $r['createtime_text'] = (string)$r['createtime'];
  6393. }
  6394. } else {
  6395. $r['createtime_text'] = '';
  6396. }
  6397. }
  6398. unset($r);
  6399. $pickedCompanyName = '';
  6400. if ($isPurchaseConfirm) {
  6401. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  6402. if (!is_array($poRow)) {
  6403. continue;
  6404. }
  6405. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6406. if ($pn !== '') {
  6407. $pickedCompanyName = $pn;
  6408. break;
  6409. }
  6410. }
  6411. }
  6412. $this->view->assign('rows', $rows ?: []);
  6413. $this->view->assign('rowCount', count($rows ?: []));
  6414. $this->view->assign('scydgyId', $ids);
  6415. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  6416. $this->view->assign('headTitle', $headTitle);
  6417. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  6418. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  6419. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  6420. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  6421. $this->view->assign('processDisplayRows', $processDisplayRows);
  6422. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  6423. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  6424. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  6425. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  6426. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  6427. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  6428. if ($isPurchaseConfirm) {
  6429. return $this->view->fetch();
  6430. }
  6431. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6432. $this->view->engine->layout(false);
  6433. try {
  6434. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  6435. $this->view->assign('dialogBody', $bodyHtml);
  6436. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  6437. } finally {
  6438. if ($restoreLayout) {
  6439. $this->view->engine->layout($restoreLayout);
  6440. }
  6441. }
  6442. }
  6443. /**
  6444. * 月度导出记录表(不存在时自动创建)
  6445. */
  6446. protected function ensurePurchaseMonthExportLogTable(): void
  6447. {
  6448. try {
  6449. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  6450. } catch (\Throwable $e) {
  6451. Db::execute(
  6452. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  6453. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  6454. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  6455. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  6456. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6457. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  6458. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  6459. `createtime` int(10) unsigned DEFAULT NULL,
  6460. PRIMARY KEY (`id`),
  6461. KEY `idx_ym` (`ym`),
  6462. KEY `idx_ct` (`createtime`)
  6463. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  6464. );
  6465. }
  6466. }
  6467. /**
  6468. * 已完结订单归属月份(与历史存证、月度列表一致)
  6469. *
  6470. * @param array<string, mixed> $row purchase_order 行
  6471. */
  6472. protected function resolveCompletedPurchaseOrderYm(array $row, array $completeTsMap = []): string
  6473. {
  6474. $sid = (int)($row['scydgy_id'] ?? 0);
  6475. if ($sid > 0 && isset($completeTsMap[$sid]) && (int)$completeTsMap[$sid] > 946684800) {
  6476. return date('Y-m', (int)$completeTsMap[$sid]);
  6477. }
  6478. if ($sid > 0) {
  6479. $logTs = $this->resolveProcuremenOperLogTime($sid, ['purchase_confirm', 'mark_complete']);
  6480. if ($logTs !== '' && preg_match('/^(\d{4}-\d{2})/', $logTs, $m)) {
  6481. return $m[1];
  6482. }
  6483. }
  6484. foreach (['updatetime', 'createtime', 'dStamp'] as $key) {
  6485. $raw = $row[$key] ?? null;
  6486. if ($raw === null || $raw === '') {
  6487. continue;
  6488. }
  6489. if (is_numeric($raw) && (int)$raw > 946684800) {
  6490. return date('Y-m', (int)$raw);
  6491. }
  6492. $t = trim((string)$raw);
  6493. if ($t !== '' && preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  6494. return $m[1];
  6495. }
  6496. }
  6497. return '';
  6498. }
  6499. /**
  6500. * @param array<int, string> $actions
  6501. * @return array<int, int>
  6502. */
  6503. protected function loadProcuremenOperLogTimestampMap(array $scydgyIds, array $actions): array
  6504. {
  6505. $out = [];
  6506. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  6507. $actions = array_values(array_filter(array_map('strval', $actions)));
  6508. if ($scydgyIds === [] || $actions === []) {
  6509. return $out;
  6510. }
  6511. try {
  6512. $logs = Db::table('purchase_order_oper_log')
  6513. ->where('scydgy_id', 'in', $scydgyIds)
  6514. ->where('action', 'in', $actions)
  6515. ->field('scydgy_id,createtime')
  6516. ->order('id', 'asc')
  6517. ->select();
  6518. } catch (\Throwable $e) {
  6519. $logs = [];
  6520. }
  6521. if (!is_array($logs)) {
  6522. return $out;
  6523. }
  6524. foreach ($logs as $log) {
  6525. if (!is_array($log)) {
  6526. continue;
  6527. }
  6528. $sid = (int)($log['scydgy_id'] ?? 0);
  6529. $ct = (int)($log['createtime'] ?? 0);
  6530. if ($sid > 0 && $ct > 946684800) {
  6531. $out[$sid] = isset($out[$sid]) ? max($out[$sid], $ct) : $ct;
  6532. }
  6533. }
  6534. return $out;
  6535. }
  6536. /**
  6537. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  6538. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6539. */
  6540. public function export_month_outward()
  6541. {
  6542. $this->request->filter(['strip_tags', 'trim']);
  6543. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6544. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6545. $ym = date('Y-m');
  6546. }
  6547. $dbRows = [];
  6548. try {
  6549. $query = Db::table('purchase_order');
  6550. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6551. $dbRows = $query->select();
  6552. } catch (\Throwable $e) {
  6553. $dbRows = [];
  6554. }
  6555. if (!is_array($dbRows)) {
  6556. $dbRows = [];
  6557. }
  6558. $completeTsMap = [];
  6559. $sidList = [];
  6560. foreach ($dbRows as $dbRow) {
  6561. if (!is_array($dbRow)) {
  6562. continue;
  6563. }
  6564. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  6565. if ($sid > 0) {
  6566. $sidList[$sid] = true;
  6567. }
  6568. }
  6569. if ($sidList !== []) {
  6570. $completeTsMap = $this->loadProcuremenOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  6571. }
  6572. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  6573. if (!is_array($dbRow)) {
  6574. return false;
  6575. }
  6576. return $this->resolveCompletedPurchaseOrderYm($dbRow, $completeTsMap) === $ym;
  6577. }));
  6578. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6579. $filtered = $pool;
  6580. $mainBySid = [];
  6581. foreach ($filtered as $rw) {
  6582. if (!is_array($rw)) {
  6583. continue;
  6584. }
  6585. $rid = (int)($rw['ID'] ?? 0);
  6586. if ($rid > 0) {
  6587. $mainBySid[$rid] = $rw;
  6588. }
  6589. }
  6590. if ($mainBySid === []) {
  6591. $detailRows = [];
  6592. } else {
  6593. try {
  6594. $detailRows = Db::table('purchase_order_detail')
  6595. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6596. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6597. ->order('status', 'desc')
  6598. ->order('CCYDH', 'asc')
  6599. ->order('company_name', 'asc')
  6600. ->order('id', 'asc')
  6601. ->select();
  6602. } catch (\Throwable $e) {
  6603. try {
  6604. $detailRows = Db::table('purchase_order_detail')
  6605. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6606. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6607. ->order('status', 'desc')
  6608. ->order('CCYDH', 'asc')
  6609. ->order('company_name', 'asc')
  6610. ->order('ID', 'asc')
  6611. ->select();
  6612. } catch (\Throwable $e2) {
  6613. $detailRows = [];
  6614. }
  6615. }
  6616. }
  6617. if (!is_array($detailRows)) {
  6618. $detailRows = [];
  6619. }
  6620. $exportLines = [];
  6621. $detailSidSeen = [];
  6622. foreach ($detailRows as $dr) {
  6623. if (!is_array($dr)) {
  6624. continue;
  6625. }
  6626. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6627. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6628. continue;
  6629. }
  6630. if (isset($detailSidSeen[$sid])) {
  6631. continue;
  6632. }
  6633. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6634. continue;
  6635. }
  6636. $detailSidSeen[$sid] = true;
  6637. $m = $mainBySid[$sid];
  6638. $exportLines[] = [
  6639. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6640. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6641. 'company_name' => (string)($dr['company_name'] ?? ''),
  6642. 'CDF' => (string)($m['CDF'] ?? ''),
  6643. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6644. 'gx' => $this->procuremenExportGxText($m),
  6645. 'detail' => $dr,
  6646. ];
  6647. }
  6648. foreach ($detailRows as $dr) {
  6649. if (!is_array($dr)) {
  6650. continue;
  6651. }
  6652. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6653. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  6654. continue;
  6655. }
  6656. $detailSidSeen[$sid] = true;
  6657. $m = $mainBySid[$sid];
  6658. $exportLines[] = [
  6659. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6660. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6661. 'company_name' => (string)($dr['company_name'] ?? ''),
  6662. 'CDF' => (string)($m['CDF'] ?? ''),
  6663. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6664. 'gx' => $this->procuremenExportGxText($m),
  6665. 'detail' => $dr,
  6666. ];
  6667. }
  6668. foreach ($mainBySid as $sid => $m) {
  6669. if (isset($detailSidSeen[$sid])) {
  6670. continue;
  6671. }
  6672. $company = trim((string)($m['pick_company_name'] ?? ''));
  6673. $exportLines[] = [
  6674. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  6675. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  6676. 'company_name' => $company,
  6677. 'CDF' => (string)($m['CDF'] ?? ''),
  6678. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6679. 'gx' => $this->procuremenExportGxText($m),
  6680. 'detail' => [],
  6681. ];
  6682. }
  6683. $groups = [];
  6684. foreach ($exportLines as $line) {
  6685. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6686. if (!isset($groups[$k])) {
  6687. $groups[$k] = [];
  6688. }
  6689. $groups[$k][] = $line;
  6690. }
  6691. ksort($groups, SORT_STRING);
  6692. $spreadsheet = new Spreadsheet();
  6693. $sheet = $spreadsheet->getActiveSheet();
  6694. $sheet->setTitle('协助明细');
  6695. $mon = (int)substr($ym, 5, 2);
  6696. $sheet->mergeCells('A1:H1');
  6697. $sheet->setCellValue('A1', $mon . '月协助明细');
  6698. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6699. $sheet->getStyle('A1')->getAlignment()
  6700. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6701. ->setVertical(Alignment::VERTICAL_CENTER);
  6702. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6703. $col = 'A';
  6704. foreach ($headers as $h) {
  6705. $sheet->setCellValue($col . '2', $h);
  6706. $col++;
  6707. }
  6708. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6709. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6710. $rowNum = 3;
  6711. $sumSubtotalCounts = 0;
  6712. $grandAmount = 0.0;
  6713. if ($groups === []) {
  6714. $sheet->mergeCells('A3:H3');
  6715. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  6716. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6717. $rowNum = 4;
  6718. } else {
  6719. foreach ($groups as $items) {
  6720. if ($items === []) {
  6721. continue;
  6722. }
  6723. $groupLineCount = count($items);
  6724. $subAmount = 0.0;
  6725. $i = 0;
  6726. foreach ($items as $line) {
  6727. $i++;
  6728. $dr = $line['detail'];
  6729. $amt = $this->procuremenExportAmount($dr);
  6730. $subAmount += $amt;
  6731. $sheet->setCellValue('A' . $rowNum, $i);
  6732. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6733. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6734. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6735. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6736. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6737. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6738. $sheet->setCellValue('H' . $rowNum, $amt);
  6739. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6740. $rowNum++;
  6741. }
  6742. $sumSubtotalCounts += $groupLineCount;
  6743. $grandAmount += $subAmount;
  6744. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  6745. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6746. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6747. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6748. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  6749. ->setVertical(Alignment::VERTICAL_CENTER);
  6750. $rowNum++;
  6751. }
  6752. }
  6753. $sheet->setCellValue('A' . $rowNum, '总计');
  6754. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6755. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6756. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6757. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6758. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  6759. $lastRow = $rowNum;
  6760. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6761. 'borders' => [
  6762. 'allBorders' => [
  6763. 'borderStyle' => Border::BORDER_THIN,
  6764. 'color' => ['rgb' => '000000'],
  6765. ],
  6766. ],
  6767. ]);
  6768. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6769. if ($lastRow >= 3) {
  6770. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6771. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6772. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6773. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6774. }
  6775. $sheet->getColumnDimension('A')->setWidth(7);
  6776. $sheet->getColumnDimension('B')->setWidth(16);
  6777. $sheet->getColumnDimension('C')->setWidth(52);
  6778. $sheet->getColumnDimension('D')->setWidth(32);
  6779. $sheet->getColumnDimension('E')->setWidth(12);
  6780. $sheet->getColumnDimension('F')->setWidth(44);
  6781. $sheet->getColumnDimension('G')->setWidth(26);
  6782. $sheet->getColumnDimension('H')->setWidth(13);
  6783. $sheet->getRowDimension(1)->setRowHeight(28);
  6784. $fileBase = '协助明细_' . str_replace('-', '', $ym);
  6785. $filename = $fileBase . '.xlsx';
  6786. try {
  6787. $this->ensurePurchaseMonthExportLogTable();
  6788. list($adminId, $adminName) = $this->GetUseName();
  6789. Db::table('purchase_month_export_log')->insert([
  6790. 'ym' => $ym,
  6791. 'admin_id' => (int)$adminId,
  6792. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6793. 'row_count' => count($exportLines),
  6794. 'total_amount' => round($grandAmount, 2),
  6795. 'createtime' => time(),
  6796. ]);
  6797. } catch (\Throwable $e) {
  6798. Log::write('month export log: ' . $e->getMessage(), 'error');
  6799. }
  6800. if (ob_get_length()) {
  6801. ob_end_clean();
  6802. }
  6803. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  6804. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6805. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6806. header('Cache-Control: max-age=0');
  6807. $writer = new Xlsx($spreadsheet);
  6808. $writer->save('php://output');
  6809. $spreadsheet->disconnectWorksheets();
  6810. unset($spreadsheet);
  6811. exit;
  6812. }
  6813. /**
  6814. * 导出用:工序列文案
  6815. */
  6816. protected function procuremenExportGxText(array $r)
  6817. {
  6818. $a = trim((string)($r['CDXMC'] ?? ''));
  6819. $b = trim((string)($r['CGYMC'] ?? ''));
  6820. if ($a !== '' && $b !== '') {
  6821. return $a . ':' . $b;
  6822. }
  6823. return $a !== '' ? $a : $b;
  6824. }
  6825. /**
  6826. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6827. */
  6828. protected function procuremenExportAmount(array $r)
  6829. {
  6830. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6831. if (!array_key_exists($k, $r)) {
  6832. continue;
  6833. }
  6834. $v = $r[$k];
  6835. if ($v === null || $v === '') {
  6836. continue;
  6837. }
  6838. if (is_numeric($v)) {
  6839. return (float)$v;
  6840. }
  6841. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  6842. if ($v !== '' && is_numeric($v)) {
  6843. return (float)$v;
  6844. }
  6845. }
  6846. return 0.0;
  6847. }
  6848. /**
  6849. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  6850. */
  6851. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  6852. {
  6853. $s = trim($ccydh);
  6854. if ($s === '') {
  6855. return 'ORDER';
  6856. }
  6857. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  6858. $s = trim($s, '._-');
  6859. if ($s === '') {
  6860. return 'ORDER';
  6861. }
  6862. if (function_exists('mb_substr')) {
  6863. return mb_substr($s, 0, 80, 'UTF-8');
  6864. }
  6865. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  6866. }
  6867. /**
  6868. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  6869. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  6870. *
  6871. * @return array{objectKey: string, webPath: string}
  6872. */
  6873. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  6874. {
  6875. $sid = (int)$scydgyId;
  6876. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  6877. $y = date('Y');
  6878. $m = date('m');
  6879. $d = date('d');
  6880. $basename = $safeOrder . '_' . $sid . '.pdf';
  6881. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  6882. return [
  6883. 'objectKey' => $objectKey,
  6884. 'webPath' => '/' . $objectKey,
  6885. ];
  6886. }
  6887. /**
  6888. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  6889. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  6890. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  6891. *
  6892. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  6893. */
  6894. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  6895. {
  6896. if (!$this->isValidScydgyRowId($scydgyId)) {
  6897. return '';
  6898. }
  6899. $ids = trim((string)$scydgyId);
  6900. $prep = $this->prepareProcuremenDetailsView($ids);
  6901. if (!$prep['ok']) {
  6902. return '';
  6903. }
  6904. $ccydh = $prep['ccydh'];
  6905. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  6906. $objectKey = $paths['objectKey'];
  6907. $webPath = $paths['webPath'];
  6908. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  6909. $this->view->assign([
  6910. 'pdf_export' => 1,
  6911. 'pdfMetaLine' => $meta,
  6912. ]);
  6913. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  6914. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6915. $this->view->engine->layout(false);
  6916. try {
  6917. $html = $this->view->fetch('procuremen/details_pdf_shell');
  6918. } catch (\Throwable $e) {
  6919. if ($restoreLayout) {
  6920. $this->view->engine->layout($restoreLayout);
  6921. }
  6922. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  6923. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6924. return '';
  6925. }
  6926. if ($restoreLayout) {
  6927. $this->view->engine->layout($restoreLayout);
  6928. }
  6929. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6930. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  6931. if (!is_dir($tempDir)) {
  6932. @mkdir($tempDir, 0755, true);
  6933. }
  6934. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  6935. try {
  6936. $mpdf = new \Mpdf\Mpdf([
  6937. 'mode' => 'utf-8',
  6938. 'format' => 'A4',
  6939. 'margin_left' => 12,
  6940. 'margin_right' => 12,
  6941. 'margin_top' => 14,
  6942. 'margin_bottom' => 14,
  6943. 'tempDir' => $tempDir,
  6944. 'autoScriptToLang' => true,
  6945. 'autoLangToFont' => true,
  6946. ]);
  6947. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  6948. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  6949. $mpdf->SetBasePath('http://127.0.0.1/');
  6950. $mpdf->WriteHTML($html);
  6951. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  6952. } catch (\Throwable $e) {
  6953. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  6954. if (is_file($tempPdf)) {
  6955. @unlink($tempPdf);
  6956. }
  6957. return '';
  6958. }
  6959. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  6960. if ($ossUrl !== '') {
  6961. @unlink($tempPdf);
  6962. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6963. return $ossUrl;
  6964. }
  6965. $pi = pathinfo($objectKey);
  6966. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  6967. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  6968. if ($baseFile === '') {
  6969. @unlink($tempPdf);
  6970. return '';
  6971. }
  6972. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  6973. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  6974. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  6975. @unlink($tempPdf);
  6976. return '';
  6977. }
  6978. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  6979. if (!@copy($tempPdf, $fullPath)) {
  6980. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  6981. @unlink($tempPdf);
  6982. return '';
  6983. }
  6984. @unlink($tempPdf);
  6985. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6986. return $webPath;
  6987. }
  6988. /**
  6989. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  6990. */
  6991. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  6992. {
  6993. if ($scydgyId <= 0 || $webPath === '') {
  6994. return;
  6995. }
  6996. try {
  6997. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  6998. } catch (\Throwable $e) {
  6999. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  7000. }
  7001. }
  7002. /**
  7003. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  7004. *
  7005. * @param array<string, string> $vars
  7006. * @return array<string, string>
  7007. */
  7008. protected function normalizeSmsTemplateVars(array $vars): array
  7009. {
  7010. $out = [];
  7011. foreach ($vars as $k => $v) {
  7012. $out[(string)$k] = trim((string)$v);
  7013. }
  7014. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  7015. $out['contact_name'] = $out['company_name'];
  7016. }
  7017. return $out;
  7018. }
  7019. /**
  7020. * 按手机号或公司名称查 customer 表联系人姓名
  7021. */
  7022. protected function resolveCustomerContactName(string $phone, string $companyName): string
  7023. {
  7024. $phone = trim($phone);
  7025. $companyName = trim($companyName);
  7026. try {
  7027. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  7028. $row = Db::table('customer')
  7029. ->where(function ($q) use ($phone) {
  7030. $q->where('phone', $phone)->whereOr('account', $phone);
  7031. })
  7032. ->order('id', 'asc')
  7033. ->find();
  7034. if (is_array($row)) {
  7035. $nm = trim((string)($row['username'] ?? ''));
  7036. if ($nm !== '') {
  7037. return $nm;
  7038. }
  7039. }
  7040. }
  7041. if ($companyName !== '') {
  7042. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  7043. if (is_array($row)) {
  7044. return trim((string)($row['username'] ?? ''));
  7045. }
  7046. }
  7047. } catch (\Throwable $e) {
  7048. }
  7049. return '';
  7050. }
  7051. /**
  7052. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  7053. */
  7054. protected function plainTextToHtmlEmailBody(string $text): string
  7055. {
  7056. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  7057. $parts = explode("\n", $text);
  7058. $out = [];
  7059. foreach ($parts as $line) {
  7060. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  7061. $out[] = $line;
  7062. } else {
  7063. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  7064. }
  7065. }
  7066. return implode("<br>\n", $out);
  7067. }
  7068. /**
  7069. * 短信场景:去掉链接类变量,避免误填 URL
  7070. *
  7071. * @param array<string, string> $vars
  7072. * @return array<string, string>
  7073. */
  7074. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  7075. {
  7076. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  7077. return $vars;
  7078. }
  7079. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  7080. $vars[$k] = '';
  7081. }
  7082. return $vars;
  7083. }
  7084. /**
  7085. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  7086. *
  7087. * @param array<string, string> $vars
  7088. */
  7089. protected function renderNotifyTemplate(string $scene, array $vars): string
  7090. {
  7091. $vars = $this->normalizeSmsTemplateVars($vars);
  7092. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  7093. $row = $this->loadNotifyTemplateRow($scene);
  7094. if ($row === null) {
  7095. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  7096. }
  7097. $tpl = trim((string)($row['content'] ?? ''));
  7098. if ($tpl === '') {
  7099. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  7100. }
  7101. foreach ($vars as $k => $v) {
  7102. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  7103. }
  7104. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  7105. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  7106. return $tpl;
  7107. }
  7108. protected function resolveProcuremenEmailSubject(string $scene): string
  7109. {
  7110. $map = [
  7111. 'review_email' => '您有新的协助加工订单',
  7112. ];
  7113. $subject = trim((string)($map[$scene] ?? ''));
  7114. if ($subject === '') {
  7115. $this->error('未配置邮件主题:' . $scene);
  7116. }
  7117. return $subject;
  7118. }
  7119. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  7120. {
  7121. $map = [
  7122. 'review_email' => '协助下发-邮箱',
  7123. 'review_sms' => '协助下发-短信',
  7124. 'confirm_ok' => '采购确认-通过',
  7125. 'confirm_fail' => '采购确认-未通过',
  7126. ];
  7127. $label = $map[$scene] ?? $scene;
  7128. if ($titleRequired) {
  7129. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  7130. }
  7131. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  7132. }
  7133. /** @deprecated 使用 renderNotifyTemplate */
  7134. protected function renderSmsTemplate(string $scene, array $vars): string
  7135. {
  7136. return $this->renderNotifyTemplate($scene, $vars);
  7137. }
  7138. /**
  7139. * 是否开启协助通知演练(不发真实短信/邮件)
  7140. */
  7141. protected function isProcuremenNotifyDryRun(): bool
  7142. {
  7143. return (bool)Config::get('procuremen_notify_dry_run');
  7144. }
  7145. /**
  7146. * @param array<string, mixed> $payload
  7147. */
  7148. protected function recordNotifyDryRunPreview(array $payload): void
  7149. {
  7150. $this->notifyDryRunPreview[] = $payload;
  7151. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7152. }
  7153. /**
  7154. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  7155. * @throws \Exception
  7156. */
  7157. protected function smsbao($phone, $content)
  7158. {
  7159. if ($this->isProcuremenNotifyDryRun()) {
  7160. $this->recordNotifyDryRunPreview([
  7161. 'scene' => 'sms_only',
  7162. 'phone' => $phone,
  7163. 'sms_content' => $content,
  7164. ]);
  7165. return;
  7166. }
  7167. $statusStr = [
  7168. '0' => '短信发送成功',
  7169. '-1' => '参数不全',
  7170. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  7171. '30' => '密码错误',
  7172. '40' => '账号不存在',
  7173. '41' => '余额不足',
  7174. '42' => '帐户已过期',
  7175. '43' => 'IP地址限制',
  7176. '50' => '内容含有敏感词',
  7177. ];
  7178. $smsapi = 'http://api.smsbao.com/';
  7179. $user = 'zhuwei123';
  7180. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  7181. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  7182. $result = @file_get_contents($sendurl);
  7183. if ($result === false) {
  7184. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  7185. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  7186. }
  7187. $result = trim((string)$result);
  7188. if ($result !== '0') {
  7189. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  7190. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  7191. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  7192. }
  7193. }
  7194. }