Procuremen.php 266 KB

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