Procuremen.php 285 KB

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