| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113 |
- <?php
- namespace app\admin\controller;
- use app\common\controller\Backend;
- use app\common\library\AliyunOss;
- use PHPMailer\PHPMailer\PHPMailer;
- use think\Config;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\Style\Border;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- use think\Db;
- use think\Log;
- class Procuremen extends Backend
- {
- /**
- * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
- */
- protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
- /**
- * Procuremen模型对象
- * @var \app\admin\model\Procuremen
- */
- protected $model = null;
- /**
- * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
- */
- protected $notifyDryRunPreview = [];
- /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
- protected $procuremenRedisCache = null;
- /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
- protected $pickHiddenScydgySetCache = null;
- /**
- * @var array
- */
- protected $noNeedRight = [
- 'review', 'reviewCompanies', 'outward_detail', 'export_month_outward', 'snapshotToProcure',
- 'pick', 'audit', 'confirm', 'pickreview', 'picksubmit', 'pickadd', 'auditissue', 'auditsubmit',
- 'auditresendsms', 'auditabandon', 'archiveabandon', 'auditresendemail', 'purchaseconfirmpick', 'purchaseapprovalreject', 'add', 'pickdelete', 'completeDirectly', 'rfqlist', 'details',
- ];
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\Procuremen;
- }
- /**
- * 手机端外发明细首页直达链接(登录后打开对应明细,免搜索)
- * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
- *
- * @param int $purchaseOrderDetailId purchase_order_detail 主键
- */
- protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
- {
- static $mprocCfgLoaded = false;
- if (!$mprocCfgLoaded) {
- $mprocCfgLoaded = true;
- if (is_file(APP_PATH . 'extra/mproc.php')) {
- Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
- }
- }
- $eid = (int)$purchaseOrderDetailId;
- $base = $this->resolveMprocMobilePublicBaseUrl();
- if ($base === '') {
- throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
- }
- $path = trim((string)Config::get('mproc.mobile_index_path'));
- if ($path === '') {
- $path = '/index.php/index/index/index';
- } else {
- $path = '/' . ltrim($path, '/');
- }
- // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(& 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
- if ($eid > 0) {
- return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
- }
- return $base . $path . '?main_tab=orders';
- }
- /**
- * 邮件/短信外链:须为带点的公网域名
- */
- protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
- {
- $u = trim((string)$baseUrl);
- if ($u === '' || !preg_match('#^https?://#i', $u)) {
- return false;
- }
- $host = parse_url($u, PHP_URL_HOST);
- if (!is_string($host) || $host === '') {
- return false;
- }
- if (strcasecmp($host, 'localhost') === 0) {
- return false;
- }
- if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
- return false;
- }
- if (strpos($host, '.') === false) {
- return false;
- }
- return true;
- }
- /**
- * 解析用于外发邮件/短信的手机端站点根
- */
- protected function resolveMprocMobilePublicBaseUrl()
- {
- $candidates = [];
- $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
- $candidates[] = trim((string)Config::get('site.indexurl'));
- $cdn = trim((string)Config::get('site.cdnurl'));
- if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
- $candidates[] = rtrim($cdn, '/');
- }
- $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
- $candidates[] = $reqBase;
- foreach ($candidates as $c) {
- if ($c === '') {
- continue;
- }
- $c = rtrim($c, '/');
- if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
- return $c;
- }
- }
- // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
- $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
- if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
- return $reqBase;
- }
- Log::write('外发邮件手机链接:配置地址失效', 'warning');
- return '';
- }
- /**
- * 排除 mcyd.dputrecord 空串、零日期等非法值,避免 MySQL 1525(DATE_FORMAT/BETWEEN 遇 '' 报错)
- */
- protected function whereMcydDputrecordValid($query, $alias = 'a')
- {
- $c = $alias . '.dStamp';
- // 先转成 CHAR 再判断,避免 DATETIME 列里存 '' / 0000-00-00 时参与日期函数报错
- return $query->whereRaw(
- $c . ' IS NOT NULL'
- . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) <> \'\''
- . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) NOT LIKE \'0000-00-00%\''
- . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) REGEXP \'^[12][0-9]{3}-[01][0-9]-[0-3][0-9]\''
- );
- }
- /**
- * 获取 Redis 中 procuremen_redis
- */
- protected function ProcuremenRedis(): array
- {
- if ($this->procuremenRedisCache !== null) {
- return $this->procuremenRedisCache;
- }
- try {
- $redis = redis();
- $raw = $redis->get('procuremen_redis');
- if ($raw === false || $raw === '') {
- $this->procuremenRedisCache = [];
- return $this->procuremenRedisCache;
- }
- $decoded = json_decode($raw, true);
- if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
- $this->procuremenRedisCache = [];
- return $this->procuremenRedisCache;
- }
- $this->procuremenRedisCache = $decoded['data'];
- return $this->procuremenRedisCache;
- } catch (\Throwable $e) {
- $this->procuremenRedisCache = [];
- return $this->procuremenRedisCache;
- }
- }
- /**
- * 左侧菜单
- */
- protected function GetIndexYearMonths()
- {
- $ymSet = [];
- //获取此方法调用缓存数据
- foreach ($this->ProcuremenRedis() as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ds = trim((string)($r['dputrecord'] ?? ''));
- if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
- continue;
- }
- if (!preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
- continue;
- }
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- continue;
- }
- $ymSet[$m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT)] = true;
- }
- $ymList = array_keys($ymSet);
- return $this->buildYearMonthSidebar($ymList);
- }
- /**
- * @param string[] $ymList 形如 2026-06
- * @return array<int, array{year:string, months:array}>
- */
- protected function buildYearMonthSidebar(array $ymList): array
- {
- rsort($ymList, SORT_STRING);
- $byYear = [];
- foreach ($ymList as $ym) {
- $y = substr($ym, 0, 4);
- $mo = (int)substr($ym, 5, 2);
- if (!isset($byYear[$y])) {
- $byYear[$y] = [];
- }
- $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
- }
- krsort($byYear, SORT_NUMERIC);
- foreach ($byYear as $y => $items) {
- usort($byYear[$y], function ($a, $b) {
- return strcmp($b['ym'], $a['ym']);
- });
- }
- $sidebar = [];
- foreach ($byYear as $y => $months) {
- $sidebar[] = ['year' => $y, 'months' => $months];
- }
- return $sidebar;
- }
- /**
- * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
- */
- protected function GetIssuedOrderYearMonths(string $stage): array
- {
- $ymSet = [];
- try {
- $query = Db::table('purchase_order');
- $this->applyPurchaseOrderNotDeletedWhere($query);
- if ($stage === 'audit') {
- $query->whereIn('wflow_status', [1, '1']);
- } elseif ($stage === 'confirm') {
- $query->where('status', 0)->where(function ($q) {
- $q->where('wflow_status', 2)
- ->whereOr(function ($q2) {
- $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
- });
- });
- } else {
- return $this->GetIndexYearMonths();
- }
- $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
- if (is_array($rows)) {
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $t = $this->procuremenRowListSortTime($r, 'pick_time');
- if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
- continue;
- }
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- continue;
- }
- $ymSet[$m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT)] = true;
- }
- }
- } catch (\Throwable $e) {
- $ymSet = [];
- }
- $ymList = array_keys($ymSet);
- if ($ymList === []) {
- $def = $this->resolveProcuremenDefaultYm($stage);
- $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
- }
- return $this->buildYearMonthSidebar($ymList);
- }
- /**
- * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
- */
- protected function resolveProcuremenDefaultYm(string $stage): string
- {
- if ($stage === 'pick') {
- return date('Y-m');
- }
- try {
- $query = Db::table('purchase_order');
- $this->applyPurchaseOrderNotDeletedWhere($query);
- if ($stage === 'audit') {
- $query->whereIn('wflow_status', [1, '1']);
- } elseif ($stage === 'confirm') {
- $query->where('status', 0)->where(function ($q) {
- $q->where('wflow_status', 2)
- ->whereOr(function ($q2) {
- $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
- });
- });
- } else {
- return date('Y-m');
- }
- $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
- if ($latest === null || $latest === '') {
- $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
- }
- $t = $this->formatProcuremenDetailTime($latest);
- if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
- return $m[1] . '-' . $m[2];
- }
- } catch (\Throwable $e) {
- }
- return date('Y-m');
- }
- protected function applyPurchaseOrderNotDeletedWhere($query): void
- {
- $query->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%\')'
- );
- }
- /** purchase_order_detail.status:2=废弃归档(保留留痕,不参与当前流程) */
- protected const PURCHASE_DETAIL_STATUS_VOID = 2;
- protected function isPurchaseOrderDetailVoid(array $row): bool
- {
- if ((int)($row['status'] ?? 0) === self::PURCHASE_DETAIL_STATUS_VOID) {
- return true;
- }
- return trim((string)($row['status_name'] ?? '')) === '已废弃';
- }
- /**
- * 仅当前有效下发明细(排除废弃归档)
- */
- protected function applyActivePurchaseOrderDetailWhere($query): void
- {
- $void = self::PURCHASE_DETAIL_STATUS_VOID;
- $query->whereRaw('(`status` IS NULL OR `status` <> ' . $void . ')')
- ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'已废弃\')');
- }
- /**
- * 列表/流程判定:存在有效下发明细
- */
- protected function purchaseOrderDetailActiveExistsSql(string $detailAlias = 'd'): string
- {
- $void = self::PURCHASE_DETAIL_STATUS_VOID;
- return 'EXISTS (SELECT 1 FROM purchase_order_detail ' . $detailAlias
- . ' WHERE ' . $detailAlias . '.scydgy_id = purchase_order.scydgy_id'
- . ' AND (' . $detailAlias . '.`status` IS NULL OR ' . $detailAlias . '.`status` <> ' . $void . ')'
- . ' AND (' . $detailAlias . '.status_name IS NULL OR TRIM(' . $detailAlias . '.status_name) = \'\' OR ' . $detailAlias . '.status_name <> \'已废弃\')'
- . ' LIMIT 1)';
- }
- /**
- * 废弃退回初选:下发明细标记归档,不物理删除
- *
- * @param array<int, int|string> $scydgyIds
- */
- protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
- {
- $ids = [];
- foreach ($scydgyIds as $sid) {
- $n = (int)$sid;
- if ($this->isValidScydgyRowId($n) || $n < 0) {
- $ids[$n] = true;
- }
- }
- if ($ids === []) {
- return;
- }
- $void = self::PURCHASE_DETAIL_STATUS_VOID;
- Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($ids))
- ->whereRaw('(`status` IS NULL OR `status` <> ' . $void . ')')
- ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'已废弃\')')
- ->update([
- 'status' => $void,
- 'status_name' => '已废弃',
- ]);
- }
- /**
- * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
- */
- protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
- {
- $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
- $norm = function (string $col) use ($p): string {
- return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
- };
- $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
- $parts = [];
- foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
- if ($key === 'createtime') {
- $parts[] = $createtime;
- } else {
- $parts[] = $norm($key);
- }
- }
- return 'COALESCE(' . implode(', ', $parts) . ')';
- }
- protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
- {
- $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
- $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
- }
- /**
- * @return array<int, array<string, mixed>>
- */
- protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
- {
- $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
- . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
- try {
- $query = Db::table('purchase_order')->field($fields);
- $this->applyPurchaseOrderNotDeletedWhere($query);
- if ($stage === 'audit') {
- $query->whereIn('wflow_status', [1, '1'])->order('pick_time', 'desc')->order('id', 'desc');
- } elseif ($stage === 'confirm') {
- $query->where('status', 0)->where(function ($q) {
- $q->where('wflow_status', 2)
- ->whereOr(function ($q2) {
- $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
- });
- })->order('pick_time', 'desc')->order('id', 'desc');
- } else {
- return [];
- }
- if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
- }
- $rows = $query->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- return is_array($rows) ? $rows : [];
- }
- /**
- * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
- */
- protected function resolveProcuremenListStage(): string
- {
- $action = strtolower((string)$this->request->action());
- if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
- return $action;
- }
- $tab = trim((string)$this->request->request('wff_tab', 'pick'));
- return in_array($tab, ['pick', 'audit', 'confirm'], true) ? $tab : 'pick';
- }
- protected function assignProcuremenListPage(string $stage, string $pageTitle): void
- {
- $rootTrue = rtrim((string)$this->request->root(true), '/');
- $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
- if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
- $indexPhpRoot = $rootTrue . '/index.php';
- }
- $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
- $this->view->assign('defaultYm', $this->resolveProcuremenDefaultYm($stage));
- $this->view->assign(
- 'sidebarYearMonths',
- $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage)
- );
- $this->view->assign('procuremenStage', $stage);
- $this->view->assign('procuremenPageTitle', $pageTitle);
- }
- /** 外发下发(选工序+供应商,发短信邮件通知报价) */
- public function pick()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('pick', '外发下发');
- return $this->view->fetch('procuremen/index');
- }
- return $this->index();
- }
- /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
- public function audit()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('audit', '确认供应商');
- return $this->view->fetch('procuremen/index');
- }
- return $this->index();
- }
- /** 采购确认(定标) */
- public function confirm()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('confirm', '采购确认');
- return $this->view->fetch('procuremen/index');
- }
- return $this->index();
- }
- /**
- * 列表页(兼容旧菜单 procuremen/index,等同外发下发)
- */
- public function index()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('pick', '外发下发');
- return $this->view->fetch('procuremen/index');
- }
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- list(, $sort, $order, $offset, $limit) = $this->buildparams();
- $limit = max(10, min(500, (int)$limit));
- $ym = $this->request->request('ym', date('Y-m'));
- $ym = is_string($ym) ? trim($ym) : '';
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $ym = date('Y-m');
- }
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- $search = trim((string)$this->request->get('search', ''));
- $hasActiveSearch = ($search !== '');
- if (!$hasActiveSearch) {
- $filterStr = $this->request->get('filter', '');
- if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
- $arr = json_decode($filterStr, true);
- if (is_array($arr) && count($arr) > 0) {
- foreach ($arr as $v) {
- if (is_array($v)) {
- if (array_filter($v, function ($x) {
- return $x !== '' && $x !== null;
- })) {
- $hasActiveSearch = true;
- break;
- }
- } elseif ($v !== '' && $v !== null) {
- $hasActiveSearch = true;
- break;
- }
- }
- }
- }
- }
- $applyMonthRange = !$hasActiveSearch;
- $filterArr = (array)json_decode($this->request->get('filter', ''), true);
- $opArr = (array)json_decode($this->request->get('op', ''), true);
- /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
- $wffTab = $this->resolveProcuremenListStage();
- try {
- $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
- if ($wffTab === 'audit') {
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
- $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
- );
- } elseif ($wffTab === 'confirm') {
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
- $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange)
- );
- } else {
- $pool = $this->ProcuremenRedis();
- if (!is_array($pool)) {
- $pool = [];
- }
- // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
- $hideSet = $this->loadPickHiddenScydgySet();
- if ($pool !== [] && $hideSet !== []) {
- $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
- if (!is_array($r)) {
- return false;
- }
- $id = (int)($r['ID'] ?? $r['id'] ?? 0);
- return $id <= 0 || !isset($hideSet[$id]);
- }));
- }
- $manualPool = $this->loadPickManualOrderRows();
- if ($manualPool !== []) {
- $pool = array_merge($pool, $manualPool);
- }
- if ($pool === []) {
- return json([
- 'total' => 0,
- 'rows' => [],
- 'msg' => '暂无缓存数据',
- ]);
- }
- }
- $filtered = $this->filterProcuremenIndexPool(
- $pool,
- $monthStart,
- $monthEnd,
- $applyMonthRange,
- $search,
- $filterArr,
- $opArr,
- $listTimePrimary
- );
- /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
- if (in_array($wffTab, ['audit', 'confirm'], true)) {
- $filtered = $this->collapseProcuremenPoolByOrder($filtered);
- }
- $sortField = 'ID';
- if (is_string($sort) && $sort !== '') {
- $parts = explode(',', $sort);
- $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
- if ($sortField === '') {
- $sortField = 'ID';
- }
- }
- $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
- $nFiltered = count($filtered);
- if ($nFiltered > 1) {
- if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
- usort($filtered, function ($a, $b) use ($sortField, $ord) {
- $ta = $this->procuremenRowListSortTime($a, $sortField);
- $tb = $this->procuremenRowListSortTime($b, $sortField);
- if ($ta === $tb) {
- return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
- }
- if ($ta === '') {
- return 1;
- }
- if ($tb === '') {
- return -1;
- }
- return strcmp($ta, $tb) * $ord;
- });
- } elseif ($sortField === 'ID') {
- $sortKeys = [];
- foreach ($filtered as $i => $row) {
- $sortKeys[$i] = (int)($row['ID'] ?? 0);
- }
- $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
- array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
- } else {
- usort($filtered, function ($a, $b) use ($sortField, $ord) {
- $va = $a[$sortField] ?? null;
- $vb = $b[$sortField] ?? null;
- $sa = (string)$va;
- $sb = (string)$vb;
- if ($sa === $sb) {
- return 0;
- }
- return strcmp($sa, $sb) * $ord;
- });
- }
- }
- $offset = max(0, (int)$offset);
- $limit = max(1, (int)$limit);
- $rows = array_slice($filtered, $offset, $limit);
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $rid = (int)($rw['ID'] ?? 0);
- $rw['_iss_out'] = ($wffTab !== 'pick');
- }
- unset($rw);
- if ($wffTab === 'confirm' && count($rows) > 0) {
- $idList = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $idList[$mid] = true;
- }
- }
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($id)) {
- $idList[$id] = true;
- }
- }
- $sumMap = $this->OrderDetailSummary(array_keys($idList));
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $mergeIds = [];
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $mergeIds[$mid] = true;
- }
- }
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($rid)) {
- $mergeIds[$rid] = true;
- }
- $cnt = 0;
- $amt = 0;
- $deliv = 0;
- foreach (array_keys($mergeIds) as $mid) {
- $s = isset($sumMap[$mid]) ? $sumMap[$mid] : ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
- $cnt += (int)($s['cnt'] ?? 0);
- $amt += (int)($s['amt'] ?? 0);
- $deliv += (int)($s['deliv'] ?? 0);
- }
- $rw['po_detail_count'] = $cnt;
- $rw['po_amount_fill_cnt'] = $amt;
- $rw['po_delivery_fill_cnt'] = $deliv;
- }
- unset($rw);
- }
- if ($wffTab === 'confirm' && count($rows) > 0) {
- $idList = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $idList[$mid] = true;
- }
- }
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($id)) {
- $idList[$id] = true;
- }
- }
- $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $mergeIds = [];
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $mergeIds[$mid] = true;
- }
- }
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($rid)) {
- $mergeIds[$rid] = true;
- }
- $buckets = [];
- foreach (array_keys($mergeIds) as $mid) {
- if (isset($quoteBucket[$mid])) {
- $buckets[] = $quoteBucket[$mid];
- }
- }
- $rw['picked_supplier_name'] = $buckets !== []
- ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
- : '';
- }
- unset($rw);
- }
- if ($wffTab === 'audit' && count($rows) > 0) {
- $idList = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $idList[$mid] = true;
- }
- }
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($id)) {
- $idList[$id] = true;
- }
- }
- $notifyMap = $this->loadNotifySupplierNamesByScydgyIds(array_keys($idList));
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $mergeIds = [];
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $mergeIds[$mid] = true;
- }
- }
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($rid)) {
- $mergeIds[$rid] = true;
- }
- $names = [];
- foreach (array_keys($mergeIds) as $mid) {
- foreach ($notifyMap[$mid] ?? [] as $cn) {
- if ($cn !== '' && !in_array($cn, $names, true)) {
- $names[] = $cn;
- }
- }
- }
- sort($names, SORT_STRING);
- $rw['notify_supplier_text'] = $this->formatNotifySupplierDisplay($names);
- }
- unset($rw);
- }
- if ($wffTab === 'all' && count($rows) > 0) {
- $this->mergePurchaseOrder($rows);
- }
- if ($wffTab === 'pick' && count($rows) > 0) {
- $this->mergePurchaseOrder($rows);
- }
- foreach ($rows as &$rwClean) {
- if (is_array($rwClean)) {
- unset($rwClean['_order_merge_rows']);
- if (array_key_exists('NGZL', $rwClean)) {
- $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
- }
- }
- }
- unset($rwClean);
- return json([
- 'total' => count($filtered),
- 'rows' => $rows,
- ]);
- } catch (\Throwable $e) {
- return json([
- 'total' => 0,
- 'rows' => [],
- 'msg' => $e->getMessage(),
- ]);
- }
- }
- /**
- * 已外发/不可再审核判定(与「未发」列表隐藏规则一致,避免仅保存数量却被当成已下发)
- * - purchase_order.status 为 0 或 1:已审核下发或已完结
- * - 或存在 purchase_order_detail:已向供应商下过明细
- * 仅写入 purchase_order 且 status 为空:视为未发(如只填本次数量、最高限价)
- *
- * @return array<int, true> scydgy_id => true
- */
- protected function loadIssuedScydgySet()
- {
- $issuedSet = [];
- try {
- $poList = Db::table('purchase_order')
- ->whereRaw('(`status` = 0 OR `status` = 1)')
- ->column('scydgy_id');
- if (is_array($poList)) {
- foreach ($poList as $ids) {
- $n = (int)$ids;
- if ($n > 0) {
- $issuedSet[$n] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- try {
- $detList = Db::table('purchase_order_detail');
- $this->applyActivePurchaseOrderDetailWhere($detList);
- $detList = $detList->group('scydgy_id')->column('scydgy_id');
- if (is_array($detList)) {
- foreach ($detList as $ids) {
- $n = (int)$ids;
- if ($n > 0) {
- $issuedSet[$n] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- return $issuedSet;
- }
- /**
- * 外发下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
- *
- * @return array<int, true>
- */
- protected function loadPickHiddenScydgySet(): array
- {
- if ($this->pickHiddenScydgySetCache !== null) {
- return $this->pickHiddenScydgySetCache;
- }
- $hideSet = [];
- try {
- $poIds = Db::table('purchase_order')
- ->where(function ($q) {
- $q->where('wflow_status', '>=', 1)
- ->whereOr('status', 1)
- ->whereOr(function ($q2) {
- $q2->whereNotNull('pick_time')
- ->where('pick_time', '<>', '')
- ->where('pick_time', '<>', '0000-00-00 00:00:00');
- })
- ->whereOr(function ($q3) {
- $q3->whereNotNull('mod_rq')
- ->where('mod_rq', '<>', '')
- ->where('mod_rq', 'not like', '0000-00-00%');
- });
- })
- ->column('scydgy_id');
- if (is_array($poIds)) {
- foreach ($poIds as $pid) {
- $k = (int)$pid;
- if ($k !== 0) {
- $hideSet[$k] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- try {
- $detIdsQuery = Db::table('purchase_order_detail');
- $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
- $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
- if (is_array($detIds)) {
- foreach ($detIds as $pid) {
- $k = (int)$pid;
- if ($this->isValidScydgyRowId($k)) {
- $hideSet[$k] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- $this->pickHiddenScydgySetCache = $hideSet;
- return $hideSet;
- }
- /**
- * 外发下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadPickManualOrderRows(): array
- {
- try {
- $dbRows = Db::table('purchase_order')
- ->where('scydgy_id', '<', 0)
- ->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%\')')
- ->order('scydgy_id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e2) {
- return [];
- }
- }
- if (!is_array($dbRows) || $dbRows === []) {
- return [];
- }
- $detailSidSet = [];
- try {
- $negIds = [];
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- if ($sid < 0) {
- $negIds[$sid] = true;
- }
- }
- if ($negIds !== []) {
- $detQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($negIds));
- $this->applyActivePurchaseOrderDetailWhere($detQuery);
- $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
- if (is_array($detRows)) {
- foreach ($detRows as $did) {
- $detailSidSet[(int)$did] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- $pool = [];
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- if ($sid >= 0) {
- continue;
- }
- $wf = (int)($dbRow['wflow_status'] ?? 0);
- if ($wf >= 1) {
- continue;
- }
- $st = trim((string)($dbRow['status'] ?? ''));
- if ($st === '1' || $st === '0') {
- continue;
- }
- if (isset($detailSidSet[$sid])) {
- continue;
- }
- $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
- $r['_is_manual'] = 1;
- $pool[] = $r;
- }
- return $pool;
- }
- /**
- * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
- */
- protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
- {
- $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
- foreach ($keys as $k) {
- $t = trim((string)($row[$k] ?? ''));
- if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
- return $t;
- }
- }
- return '';
- }
- /**
- * 分配手工新增工序行 ID(负数递减)
- */
- protected function allocateManualScydgyId(): int
- {
- try {
- $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
- $min = (int)$min;
- return $min < 0 ? $min - 1 : -1;
- } catch (\Throwable $e) {
- return -1;
- }
- }
- /**
- * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
- */
- protected function allocateManualOrderCcydh(): string
- {
- $prefix = 'YW' . date('Ymd');
- $maxSeq = 0;
- try {
- $rows = Db::table('purchase_order')
- ->where('CCYDH', 'like', $prefix . '%')
- ->column('CCYDH');
- if (is_array($rows)) {
- foreach ($rows as $ccydh) {
- $ccydh = trim((string)$ccydh);
- if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
- $maxSeq = max($maxSeq, (int)$m[1]);
- }
- }
- }
- } catch (\Throwable $e) {
- }
- return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
- }
- /**
- * purchase_order.mod_rq 是否有有效软删除时间
- */
- protected function isPurchaseOrderSoftDeleted($modRq): bool
- {
- $t = trim((string)$modRq);
- return $t !== '' && stripos($t, '0000-00-00') !== 0;
- }
- /**
- * 列表行 → purchase_order 写入字段
- *
- * @return array<string, mixed>
- */
- protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
- {
- return [
- 'scydgy_id' => $scydgyId,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- ];
- }
- /**
- * 外发初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
- */
- protected function softDeleteProcuremenPickRow(array $row): void
- {
- $sid = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($sid)) {
- throw new \InvalidArgumentException('无效的行主键');
- }
- $hideSet = $this->loadPickHiddenScydgySet();
- if ($sid > 0 && isset($hideSet[$sid])) {
- throw new \InvalidArgumentException('订单号「' . trim((string)($row['CCYDH'] ?? '')) . '」已下发或已进入后续流程,无法删除');
- }
- if ($sid < 0) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($po)) {
- if ((int)($po['wflow_status'] ?? 0) >= 1) {
- throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
- }
- if ($this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
- return;
- }
- }
- } catch (\InvalidArgumentException $e) {
- throw $e;
- } catch (\Throwable $e) {
- }
- }
- $now = date('Y-m-d H:i:s');
- $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($exists)) {
- Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
- $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
- } else {
- $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
- $data['mod_rq'] = $now;
- $data['createtime'] = $now;
- Db::table('purchase_order')->insert($data);
- $poIdLog = (int)Db::getLastInsID();
- }
- $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
- $gymcLog = trim((string)($row['CGYMC'] ?? ''));
- $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
- if ($gymcLog !== '') {
- $logTail .= ' / ' . $gymcLog;
- }
- $this->addOrderLog($sid, 'pick_soft_delete', '外发初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
- }
- /**
- * 手工新增外发工序(写入 purchase_order)
- *
- * @param array<string, mixed> $params
- * @return int scydgy_id
- */
- protected function saveManualPickOrder(array $params): int
- {
- $cyjmc = trim((string)($params['CYJMC'] ?? ''));
- $cgymc = trim((string)($params['CGYMC'] ?? ''));
- $ccydh = trim((string)($params['CCYDH'] ?? ''));
- if ($ccydh === '') {
- $ccydh = $this->allocateManualOrderCcydh();
- }
- $now = date('Y-m-d H:i:s');
- $sid = $this->allocateManualScydgyId();
- $data = [
- 'scydgy_id' => $sid,
- 'CCYDH' => $ccydh,
- 'CYJMC' => $cyjmc,
- 'CGYMC' => $cgymc,
- 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
- 'CDW' => trim((string)($params['CDW'] ?? '')),
- 'NGZL' => trim((string)($params['NGZL'] ?? '')),
- 'CDF' => trim((string)($params['CDF'] ?? '')),
- 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
- 'MBZ' => trim((string)($params['MBZ'] ?? '')),
- 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
- 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
- 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
- 'wflow_status' => 0,
- 'createtime' => $now,
- 'dStamp' => $now,
- 'dputrecord' => $now,
- ];
- Db::table('purchase_order')->insert($data);
- $poId = (int)Db::getLastInsID();
- $this->addOrderLog($sid, 'manual_add', '手工新增外发工序', $poId > 0 ? $poId : null);
- return $sid;
- }
- protected function formatProcuremenRowLabel(array $row): string
- {
- $dh = trim((string)($row['CCYDH'] ?? ''));
- $gymc = trim((string)($row['CGYMC'] ?? ''));
- if ($dh !== '' && $gymc !== '') {
- return '订单「' . $dh . '」、工序「' . $gymc . '」';
- }
- if ($dh !== '') {
- return '订单「' . $dh . '」';
- }
- if ($gymc !== '') {
- return '工序「' . $gymc . '」';
- }
- $id = $this->extractScydgyRowId($row);
- return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
- }
- /**
- * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
- */
- protected function extractScydgyRowId(array $row): int
- {
- return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
- }
- protected function isValidScydgyRowId(int $id): bool
- {
- return $id !== 0;
- }
- protected function isManualScydgyRowId(int $id): bool
- {
- return $id < 0;
- }
- /**
- * 采购确认已选定供应商:明细 purchase_order_detail.status = 1 的工序行 scydgy_id 集合
- *
- * @return array<int, true>
- */
- protected function loadScydgyIdsWithPickedSupplierDetail(): array
- {
- $set = [];
- try {
- $rows = Db::table('purchase_order_detail')->where('status', 1)->field('scydgy_id')->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- return $set;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
- if ($sid > 0) {
- $set[$sid] = true;
- }
- }
- return $set;
- }
- /**
- * 每个工序行对应已选中供应商名称(取 status=1 的首条明细 company_name)
- *
- * @param int[] $scydgyIds
- * @return array<int, string> scydgy_id => company_name
- */
- protected function loadPickedSupplierCompanyByScydgyIds(array $scydgyIds): array
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->where('status', 1)
- ->field('scydgy_id,company_name')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->where('status', 1)
- ->field('scydgy_id,company_name')
- ->order('ID', 'asc')
- ->select();
- } catch (\Throwable $e2) {
- $rows = [];
- }
- }
- if (!is_array($rows)) {
- return $out;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
- if (!$this->isValidScydgyRowId($sid) || isset($out[$sid])) {
- continue;
- }
- $name = trim((string)($r['company_name'] ?? ''));
- $out[$sid] = $name;
- }
- return $out;
- }
- /**
- * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
- *
- * @param int[] $scydgyIds
- * @return array<int, string[]>
- */
- protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('scydgy_id,company_name')
- ->order('company_name', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- return $out;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $cn = trim((string)($r['company_name'] ?? ''));
- if (!$this->isValidScydgyRowId($sid) || $cn === '') {
- continue;
- }
- if (!isset($out[$sid])) {
- $out[$sid] = [];
- }
- if (!in_array($cn, $out[$sid], true)) {
- $out[$sid][] = $cn;
- }
- }
- return $out;
- }
- /**
- * 列表展示通知供应商(完整列表,前端单行省略展开)
- *
- * @param string[] $names
- */
- protected function formatNotifySupplierDisplay(array $names): string
- {
- $names = array_values(array_unique(array_filter(array_map(function ($n) {
- return trim((string)$n);
- }, $names))));
- if ($names === []) {
- return '';
- }
- sort($names, SORT_STRING);
- return implode('、', $names);
- }
- /**
- * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
- *
- * @param int[] $scydgyIds
- * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
- */
- protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('scydgy_id,company_name,amount')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- return $out;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $cn = trim((string)($r['company_name'] ?? ''));
- if (!$this->isValidScydgyRowId($sid) || $cn === '') {
- continue;
- }
- if (!isset($out[$sid])) {
- $out[$sid] = ['all' => [], 'quoted' => []];
- }
- $out[$sid]['all'][$cn] = true;
- $am = trim((string)($r['amount'] ?? ''));
- if ($am !== '' && $am !== '0' && $am !== '0.00') {
- $out[$sid]['quoted'][$cn] = true;
- }
- }
- return $out;
- }
- /**
- * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
- * @return array{all: array<string, bool>, quoted: array<string, bool>}
- */
- protected function mergeQuotedSupplierBuckets(array $buckets): array
- {
- $merged = ['all' => [], 'quoted' => []];
- foreach ($buckets as $b) {
- if (!is_array($b)) {
- continue;
- }
- foreach ($b['all'] ?? [] as $cn => $_) {
- $merged['all'][$cn] = true;
- }
- foreach ($b['quoted'] ?? [] as $cn => $_) {
- $merged['quoted'][$cn] = true;
- }
- }
- return $merged;
- }
- /**
- * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
- */
- protected function formatQuotedSupplierLines(array $bucket): string
- {
- $all = array_keys($bucket['all'] ?? []);
- if ($all === []) {
- return '';
- }
- sort($all, SORT_STRING);
- $lines = [];
- foreach ($all as $cn) {
- $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
- $lines[] = $cn . '(' . $status . ')';
- }
- return implode("\n", $lines);
- }
- /**
- * @param int[] $scydgyIds
- * @return array<int, string>
- */
- protected function loadQuotedSupplierSummaryByScydgyIds(array $scydgyIds): array
- {
- $out = [];
- foreach ($this->loadQuotedSupplierBucketByScydgyIds($scydgyIds) as $sid => $bucket) {
- $text = $this->formatQuotedSupplierLines($bucket);
- if ($text !== '') {
- $out[$sid] = $text;
- }
- }
- return $out;
- }
- /**
- * 审核弹窗:按供应商汇总报价明细
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, array<string, mixed>>
- */
- protected function loadAuditSupplierQuoteGroups(array $bundle): array
- {
- $sids = [];
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- }
- }
- if ($sids === []) {
- return [];
- }
- $gymcMap = [];
- foreach ($bundle['merge_rows'] ?? [] as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $gid = $this->extractScydgyRowId($mr);
- if ($this->isValidScydgyRowId($gid)) {
- $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
- }
- }
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $gid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($gid)) {
- $nm = trim((string)($po['CGYMC'] ?? ''));
- if ($nm !== '') {
- $gymcMap[$gid] = $nm;
- }
- }
- }
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids));
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids));
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
- } catch (\Throwable $e2) {
- $details = [];
- }
- }
- if (!is_array($details)) {
- $details = [];
- }
- $byCompany = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $cn = trim((string)($d['company_name'] ?? ''));
- if ($cn === '') {
- continue;
- }
- if (!isset($byCompany[$cn])) {
- $ph = trim((string)($d['phone'] ?? ''));
- $username = trim((string)($d['username'] ?? ''));
- if ($username === '') {
- $username = $this->resolveCustomerContactName($ph, $cn);
- }
- $byCompany[$cn] = [
- 'name' => $cn,
- 'email' => trim((string)($d['email'] ?? '')),
- 'phone' => $ph,
- 'username' => $username,
- 'has_quote' => false,
- 'lines' => [],
- ];
- }
- $sid = (int)($d['scydgy_id'] ?? 0);
- $am = trim((string)($d['amount'] ?? ''));
- $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
- if ($gymc === '') {
- $gymc = '工序';
- }
- $deliveryRaw = trim((string)($d['delivery'] ?? ''));
- $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
- if ($deliveryShow === '' && $deliveryRaw !== '') {
- $deliveryShow = $deliveryRaw;
- }
- $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
- $deliveryFilled = ($deliveryShow !== '');
- $byCompany[$cn]['lines'][] = [
- 'cgymc' => $gymc,
- 'amount' => $am,
- 'amount_show' => $amountFilled ? $am : '',
- 'amount_filled' => $amountFilled,
- 'delivery' => $deliveryRaw,
- 'delivery_show' => $deliveryFilled ? $deliveryShow : '',
- 'delivery_filled' => $deliveryFilled,
- 'status_name' => trim((string)($d['status_name'] ?? '')),
- 'is_quoted' => $amountFilled,
- 'quote_label' => $amountFilled ? '已报价' : '未报价',
- ];
- }
- foreach ($byCompany as $cn => $g) {
- $total = count($g['lines']);
- $quoted = 0;
- foreach ($g['lines'] as $ln) {
- $am = trim((string)($ln['amount'] ?? ''));
- if ($am !== '' && $am !== '0' && $am !== '0.00') {
- $quoted++;
- }
- }
- $byCompany[$cn]['has_quote'] = $total > 0 && $quoted === $total;
- }
- return array_values($byCompany);
- }
- /**
- * 确认供应商弹窗:通知对象(不含报价,仅工序与联系方式)
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, array<string, mixed>>
- */
- protected function loadAuditSupplierNotifyGroups(array $bundle): array
- {
- $groups = $this->loadAuditSupplierQuoteGroups($bundle);
- $out = [];
- foreach ($groups as $g) {
- if (!is_array($g)) {
- continue;
- }
- $processNames = [];
- foreach ($g['lines'] ?? [] as $ln) {
- if (!is_array($ln)) {
- continue;
- }
- $n = trim((string)($ln['cgymc'] ?? ''));
- if ($n !== '' && !in_array($n, $processNames, true)) {
- $processNames[] = $n;
- }
- }
- $out[] = [
- 'name' => trim((string)($g['name'] ?? '')),
- 'email' => trim((string)($g['email'] ?? '')),
- 'phone' => trim((string)($g['phone'] ?? '')),
- 'username' => trim((string)($g['username'] ?? '')),
- 'process_names' => $processNames,
- 'process_text' => implode('、', $processNames),
- ];
- }
- return $out;
- }
- /**
- * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, array<string, mixed>>
- */
- protected function loadConfirmSupplierPickGroups(array $bundle): array
- {
- $sids = [];
- $poIdMap = [];
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- }
- if ($sids === []) {
- return [];
- }
- $gymcMap = [];
- foreach ($bundle['merge_rows'] ?? [] as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $gid = $this->extractScydgyRowId($mr);
- if ($this->isValidScydgyRowId($gid)) {
- $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
- }
- }
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $gid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($gid)) {
- $nm = trim((string)($po['CGYMC'] ?? ''));
- if ($nm !== '') {
- $gymcMap[$gid] = $nm;
- }
- }
- }
- try {
- $details = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->order('company_name', 'asc')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $details = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->order('company_name', 'asc')
- ->order('ID', 'asc')
- ->select();
- } catch (\Throwable $e2) {
- $details = [];
- }
- }
- if (!is_array($details)) {
- $details = [];
- }
- $byCompany = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $cn = trim((string)($d['company_name'] ?? ''));
- if ($cn === '') {
- continue;
- }
- $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
- $sid = (int)($d['scydgy_id'] ?? 0);
- if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
- continue;
- }
- if (!isset($byCompany[$cn])) {
- $ph = trim((string)($d['phone'] ?? ''));
- $username = trim((string)($d['username'] ?? ''));
- if ($username === '') {
- $username = $this->resolveCustomerContactName($ph, $cn);
- }
- $byCompany[$cn] = [
- 'name' => $cn,
- 'email' => trim((string)($d['email'] ?? '')),
- 'phone' => $ph,
- 'username' => $username,
- 'pick_lines' => [],
- 'detail_picks' => [],
- ];
- }
- $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
- if ($gymc === '') {
- $gymc = '工序';
- }
- $am = trim((string)($d['amount'] ?? ''));
- $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
- $deliveryRaw = trim((string)($d['delivery'] ?? ''));
- $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
- if ($deliveryShow === '' && $deliveryRaw !== '') {
- $deliveryShow = $deliveryRaw;
- }
- $byCompany[$cn]['pick_lines'][$sid] = [
- 'cgymc' => $gymc,
- 'amount_text' => $amountFilled ? $am : '未填写',
- 'delivery_text' => $deliveryShow !== '' ? $deliveryShow : '未填写',
- 'is_quoted' => $amountFilled,
- ];
- $byCompany[$cn]['detail_picks'][$sid] = [
- 'scydgy_id' => $sid,
- 'detail_id' => $detailId,
- 'purchase_order_id' => $poIdMap[$sid] ?? 0,
- 'cgymc' => $gymc,
- ];
- }
- $out = [];
- foreach ($byCompany as $g) {
- $pickLines = $g['pick_lines'] ?? [];
- if (!is_array($pickLines) || $pickLines === []) {
- continue;
- }
- $g['pick_lines'] = array_values($pickLines);
- $detailPicks = $g['detail_picks'] ?? [];
- $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
- $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
- unset($g['detail_picks']);
- $out[] = $g;
- }
- return $out;
- }
- /**
- * @param array<int, array<string, mixed>> $details purchase_order_detail 行
- * @return array<int, int[]> scydgy_id => detail_id[]
- */
- protected function mapDetailIdsByScydgyId(array $details): array
- {
- $out = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $sid = (int)($d['scydgy_id'] ?? 0);
- $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
- if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
- continue;
- }
- if (!isset($out[$sid])) {
- $out[$sid] = [];
- }
- $out[$sid][] = $pk;
- }
- foreach ($out as $sid => $ids) {
- $out[$sid] = array_values(array_unique($ids));
- }
- return $out;
- }
- /**
- * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
- *
- * @param array<string, mixed> $dbRow
- * @param array<int, mixed> $dStampMap scydgy_id => dStamp
- */
- protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
- {
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- $r = [
- 'ID' => $sid,
- 'CCYDH' => $dbRow['CCYDH'] ?? '',
- 'CYJMC' => $dbRow['CYJMC'] ?? '',
- 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
- 'CDXMC' => $dbRow['CDXMC'] ?? '',
- 'CGYBH' => $dbRow['CGYBH'] ?? '',
- 'CGYMC' => $dbRow['CGYMC'] ?? '',
- 'CDW' => $dbRow['CDW'] ?? '',
- 'NGZL' => $dbRow['NGZL'] ?? '',
- 'CDF' => $dbRow['CDF'] ?? '',
- 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
- 'MBZ' => $dbRow['MBZ'] ?? '',
- 'bwjg' => $dbRow['bwjg'] ?? '',
- 'iStatus' => $dbRow['iStatus'] ?? '',
- 'dputrecord' => $dbRow['dputrecord'] ?? '',
- 'cywyxm' => $dbRow['cywyxm'] ?? '',
- 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
- 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
- 'dStamp' => $dbRow['dStamp'] ?? '',
- 'pick_time' => $dbRow['pick_time'] ?? '',
- ];
- if ($sid > 0 && isset($dStampMap[$sid])) {
- $t = trim((string)$dStampMap[$sid]);
- if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
- $r['dStamp'] = $dStampMap[$sid];
- }
- }
- $dsOut = trim((string)($r['dStamp'] ?? ''));
- if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
- $ct = $dbRow['createtime'];
- if (is_numeric($ct) && (int)$ct > 946684800) {
- $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
- } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
- $r['dStamp'] = trim($ct);
- }
- }
- // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
- $dpOut = trim((string)($r['dputrecord'] ?? ''));
- if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
- $fallback = trim((string)($r['dStamp'] ?? ''));
- if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
- $r['dputrecord'] = $fallback;
- }
- }
- if (array_key_exists('id', $dbRow)) {
- $r['purchase_order_id'] = (int)$dbRow['id'];
- }
- if ($sid < 0) {
- $r['_is_manual'] = 1;
- }
- $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
- $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
- if ($pickNm !== '') {
- $r['pick_company_name'] = $pickNm;
- $r['picked_supplier_name'] = $pickNm;
- }
- return $r;
- }
- /**
- * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
- *
- * @return array<int, array<string, mixed>>
- */
- protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
- {
- $pool = [];
- if (!is_array($dbRows) || $dbRows === []) {
- return $pool;
- }
- $dStampMap = [];
- $sidList = [];
- foreach ($dbRows as $tmpRow) {
- if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
- $sid = (int)$tmpRow['scydgy_id'];
- if ($sid > 0) {
- $ds = trim((string)($tmpRow['dStamp'] ?? ''));
- if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
- $sidList[$sid] = true;
- }
- }
- }
- }
- if ($sidList !== []) {
- try {
- $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
- } catch (\Throwable $e) {
- $dStampMap = [];
- }
- }
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
- }
- return $pool;
- }
- /**
- * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
- *
- * @param int[] $scydgyIds
- * @return array<int, array{cnt:int, amt:int, deliv:int}>
- */
- protected function OrderDetailSummary(array $scydgyIds)
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- $list = [];
- try {
- $list = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('id,scydgy_id,amount,delivery')
- ->select();
- } catch (\Throwable $e) {
- $list = [];
- }
- if (!is_array($list)) {
- return $out;
- }
- foreach ($list as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ids = (int)($r['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($ids)) {
- continue;
- }
- if (!isset($out[$ids])) {
- $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
- }
- $out[$ids]['cnt']++;
- $am = $r['amount'] ?? null;
- if ($am !== null && $am !== '') {
- if (!(is_string($am) && trim($am) === '')) {
- $out[$ids]['amt']++;
- }
- }
- $dv = $r['delivery'] ?? null;
- if ($dv !== null && trim((string)$dv) !== '') {
- $out[$ids]['deliv']++;
- }
- }
- return $out;
- }
- /**
- * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
- *
- * @return array
- */
- protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
- {
- $strContains = function ($haystack, $needle) {
- if ($needle === '') {
- return false;
- }
- $haystack = (string)$haystack;
- if (function_exists('mb_stripos')) {
- return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
- }
- return stripos($haystack, $needle) !== false;
- };
- $stripAlias = function ($f) {
- return preg_replace('/^[ab]\./i', '', (string)$f);
- };
- $searchColNames = [];
- foreach (explode(',', $this->searchFields) as $colRaw) {
- $c = $stripAlias(trim($colRaw));
- if ($c !== '') {
- $searchColNames[] = $c;
- }
- }
- $filtered = [];
- foreach ($pool as $r) {
- if (!is_array($r)) {
- continue;
- }
- $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
- $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
- if (!$isManual) {
- if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
- || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
- continue;
- }
- if ($applyMonthRange) {
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- continue;
- }
- $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
- $rowMonthStart = $ymRow . '-01 00:00:00';
- $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
- if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
- continue;
- }
- }
- } elseif ($applyMonthRange) {
- $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
- if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
- $ds = $listTime;
- }
- if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
- continue;
- }
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- continue;
- }
- $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
- $rowMonthStart = $ymRow . '-01 00:00:00';
- $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
- if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
- continue;
- }
- }
- if ($search !== '') {
- $hitSearch = false;
- foreach ($searchColNames as $c) {
- $cell = isset($r[$c]) ? (string)$r[$c] : '';
- if ($cell !== '' && $strContains($cell, $search)) {
- $hitSearch = true;
- break;
- }
- }
- if (!$hitSearch) {
- continue;
- }
- }
- foreach ($filterArr as $fk => $fv) {
- if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
- continue;
- }
- if (is_array($fv)) {
- continue;
- }
- if ($fv === '' && $fv !== '0' && $fv !== 0) {
- continue;
- }
- $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
- $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
- $field = $stripAlias($fk);
- $cell = array_key_exists($field, $r) ? $r[$field] : null;
- $cellStr = trim((string)$cell);
- switch ($sym) {
- case '=':
- if ((string)$cell !== (string)$fv) {
- continue 3;
- }
- break;
- case '<>':
- if ((string)$cell === (string)$fv) {
- continue 3;
- }
- break;
- case 'LIKE':
- case 'NOT LIKE':
- $needle = trim((string)$fv);
- $hit = ($needle !== '' && $strContains($cellStr, $needle));
- if ($sym === 'LIKE' && !$hit) {
- continue 3;
- }
- if ($sym === 'NOT LIKE' && $hit) {
- continue 3;
- }
- break;
- case '>':
- case '>=':
- case '<':
- case '<=':
- if (!is_numeric($cell) && $cellStr === '') {
- continue 3;
- }
- $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
- $vv = (float)$fv;
- if ($sym === '>' && !($cv > $vv)) {
- continue 3;
- }
- if ($sym === '>=' && !($cv >= $vv)) {
- continue 3;
- }
- if ($sym === '<' && !($cv < $vv)) {
- continue 3;
- }
- if ($sym === '<=' && !($cv <= $vv)) {
- continue 3;
- }
- break;
- case 'RANGE':
- case 'NOT RANGE':
- case 'BETWEEN':
- case 'NOT BETWEEN':
- case 'BETWEEN TIME':
- case 'NOT BETWEEN TIME':
- $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
- $rawR = str_replace(' - ', ',', $rawR);
- $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
- if (count($arr) < 2) {
- break;
- }
- $lo = $arr[0];
- $hi = $arr[1];
- if ($lo === '' && $hi === '') {
- break;
- }
- $isNot = (strpos($sym, 'NOT') !== false);
- if ($lo === '') {
- $in = ($cellStr !== '' && $cellStr <= $hi);
- if ($isNot ? $in : !$in) {
- continue 3;
- }
- break;
- }
- if ($hi === '') {
- $in = ($cellStr !== '' && $cellStr >= $lo);
- if ($isNot ? $in : !$in) {
- continue 3;
- }
- break;
- }
- $in = ($cellStr >= $lo && $cellStr <= $hi);
- if ($isNot ? $in : !$in) {
- continue 3;
- }
- break;
- case 'NULL':
- case 'IS NULL':
- if ($cell !== null && $cell !== '') {
- continue 3;
- }
- break;
- case 'NOT NULL':
- case 'IS NOT NULL':
- if ($cell === null || $cell === '') {
- continue 3;
- }
- break;
- default:
- break;
- }
- }
- $filtered[] = $r;
- }
- return $filtered;
- }
- /**
- * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
- */
- public function snapshotToProcure()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $row = json_decode($this->request->post('row_json', ''), true);
- if (!is_array($row)) {
- $this->error(__('Invalid parameters'));
- }
- try {
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
- }
- $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- $data = [
- 'scydgy_id' => $ids,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- ];
- $qtySnap = trim((string)($data['This_quantity'] ?? ''));
- $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
- if (!$exists && $qtySnap === '' && $priceSnap === '') {
- $this->success('操作成功');
- return;
- }
- if ($exists) {
- $upd = $data;
- unset($upd['scydgy_id'], $upd['status']);
- Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
- } else {
- // 新增:不写 status(空/走库默认);仅写创建时间
- $data['createtime'] = date('Y-m-d H:i:s');
- Db::table('purchase_order')->insert($data);
- }
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
- $this->success('操作成功');
- }
- /**
- * 未发列表
- * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
- * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
- */
- public function completeDirectly()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('参数错误'));
- }
- $row = json_decode($this->request->post('row_json', ''), true);
- if (!is_array($row)) {
- $this->error(__('Invalid parameters'));
- }
- $finishRaw = $this->request->post('finish', '1');
- $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
- try {
- // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
- }
- $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- $data = [
- 'scydgy_id' => $ids,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- ];
- if ($asComplete) {
- // 主表 status 为 varchar 时统一写 '1',档案 procuremenarchive 按 status=1 查询
- $data['status'] = '1';
- }
- $qtyCd = trim((string)($data['This_quantity'] ?? ''));
- $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
- if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
- $this->success('操作成功');
- return;
- }
- if ($exists) {
- $upd = $data;
- unset($upd['scydgy_id']);
- if (!$asComplete) {
- unset($upd['status']);
- }
- Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
- } else {
- // 新增:不写 status;完结时 $data 已含 status=1
- $data['createtime'] = date('Y-m-d H:i:s');
- Db::table('purchase_order')->insert($data);
- }
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $poIdLog = null;
- try {
- $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- if (is_array($rpo)) {
- $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
- $poIdLog = $tid > 0 ? $tid : null;
- }
- } catch (\Throwable $e) {
- $poIdLog = null;
- }
- $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
- $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
- if ($asComplete) {
- $this->addOrderLog(
- $ids,
- 'mark_complete',
- '点击「完结」,已标记为已完结',
- $poIdLog
- );
- try {
- $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
- if ($pdfPublicPath === '') {
- Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
- }
- } catch (\Throwable $e) {
- Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
- }
- } else {
- $this->addOrderLog(
- $ids,
- 'save_qty_price',
- '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
- $poIdLog
- );
- }
- $this->success("操作成功");
- }
- /**
- * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
- *
- * @param array<int, array> $rows 引用传递当前页行
- */
- protected function mergePurchaseOrder(array &$rows)
- {
- if ($rows === []) {
- return;
- }
- $ids = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($id > 0) {
- $ids[$id] = true;
- }
- }
- $idList = array_keys($ids);
- if ($idList === []) {
- return;
- }
- try {
- $list = Db::table('purchase_order')
- ->where('scydgy_id', 'in', $idList)
- ->field('scydgy_id,This_quantity,ceilingPrice')
- ->select();
- } catch (\Throwable $e) {
- return;
- }
- if (!is_array($list)) {
- return;
- }
- $byId = [];
- foreach ($list as $dbRow) {
- if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
- continue;
- }
- $byId[(int)$dbRow['scydgy_id']] = $dbRow;
- }
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $sid = (int)($rw['ID'] ?? 0);
- if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
- continue;
- }
- $db = $byId[$sid];
- if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
- $rw['This_quantity'] = $db['This_quantity'];
- }
- if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
- $rw['ceilingPrice'] = $db['ceilingPrice'];
- } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
- $rw['ceilingPrice'] = $db['ceiling_price'];
- }
- }
- unset($rw);
- }
- /**
- * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
- */
- public function purchaseConfirmPick()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
- if ($batchRaw !== '') {
- $this->handlePurchaseConfirmOrderBatch($batchRaw);
- return;
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- $sid = (int)$scydgyId;
- if (!$this->isValidScydgyRowId($sid)) {
- $this->error('参数无效');
- }
- $parseIdList = function ($raw) {
- if (is_array($raw)) {
- $arr = $raw;
- } else {
- $decoded = json_decode((string)$raw, true);
- $arr = is_array($decoded) ? $decoded : [];
- }
- return array_values(array_unique(array_filter(array_map('intval', $arr))));
- };
- $selectedRaw = $this->request->post('selected_ids', null);
- if ($selectedRaw === null || $selectedRaw === '') {
- $legacy = (int)$this->request->post('selected_id', 0);
- $selectedIds = $legacy > 0 ? [$legacy] : [];
- } else {
- $selectedIds = $parseIdList($selectedRaw);
- }
- $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
- $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
- try {
- $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
- } catch (\InvalidArgumentException $e) {
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $this->success('操作成功', '', $result);
- }
- /**
- * 整单采购确认(多道工序一次提交)
- */
- protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
- {
- $decoded = json_decode($batchRaw, true);
- if (!is_array($decoded) || $decoded === []) {
- $this->error('提交数据无效');
- }
- $picks = [];
- foreach ($decoded as $item) {
- if (!is_array($item)) {
- continue;
- }
- $sid = (int)($item['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
- if (!is_array($sel)) {
- $sel = [(int)$sel];
- }
- $unsel = $item['unselected_ids'] ?? [];
- if (!is_array($unsel)) {
- $unsel = json_decode((string)$unsel, true);
- $unsel = is_array($unsel) ? $unsel : [];
- }
- $picks[] = [
- 'scydgy_id' => $sid,
- 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
- 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
- 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
- ];
- }
- if ($picks === []) {
- $this->error('提交数据无效');
- }
- Db::startTrans();
- $results = [];
- try {
- foreach ($picks as $pick) {
- $results[] = $this->runPurchaseConfirmPick(
- (int)$pick['scydgy_id'],
- $pick['selected_ids'],
- $pick['unselected_ids'],
- (int)$pick['purchase_order_id'],
- false
- );
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $msg = $e->getMessage();
- $this->error($msg !== '' ? $msg : '提交失败');
- }
- $this->success('操作成功', '', ['batch' => $results]);
- }
- /**
- * @return array<string, mixed>
- */
- protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true): array
- {
- $scydgyId = (string)$sid;
- if ($selectedIds === []) {
- throw new \InvalidArgumentException('请至少勾选一条明细');
- }
- $inter = array_intersect($selectedIds, $unselectedIds);
- if ($inter !== []) {
- throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
- }
- $allIds = $this->purchaseOrderDetail($sid);
- if ($allIds === []) {
- throw new \InvalidArgumentException('未找到该工序行的下发明细');
- }
- foreach ($selectedIds as $id) {
- if (!in_array($id, $allIds, true)) {
- throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
- }
- }
- foreach ($unselectedIds as $id) {
- if (!in_array($id, $allIds, true)) {
- throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
- }
- }
- $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
- sort($union, SORT_NUMERIC);
- $expect = $allIds;
- sort($expect, SORT_NUMERIC);
- if ($union !== $expect) {
- throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
- }
- if ($manageTransaction) {
- Db::startTrans();
- }
- try {
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
- $aff = 0;
- try {
- $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => 1]);
- } catch (\Throwable $e) {
- $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => 1]);
- }
- if ($aff < 1) {
- throw new \Exception('更新选中状态失败');
- }
- if ($purchaseOrderId > 0) {
- $poAff = (int)Db::table('purchase_order')
- ->where('id', $purchaseOrderId)
- ->where('scydgy_id', $sid)
- ->update(['status' => 1]);
- if ($poAff < 1) {
- throw new \Exception('主表订单不存在或与工序行不匹配');
- }
- } else {
- $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update(['status' => '1']);
- if ($poAff < 1) {
- throw new \Exception('未找到');
- }
- }
- $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
- $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
- if ($manageTransaction) {
- Db::commit();
- }
- } catch (\Throwable $e) {
- if ($manageTransaction) {
- Db::rollback();
- }
- throw $e;
- }
- $poIdFinal = $purchaseOrderId;
- if ($poIdFinal <= 0) {
- try {
- $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($rpo)) {
- $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
- }
- } catch (\Throwable $e) {
- $poIdFinal = 0;
- }
- }
- $pickNames = [];
- foreach ($selectedIds as $pid) {
- $dr = $this->purchaseOrderDetai($sid, $pid);
- $nm = trim((string)($dr['company_name'] ?? ''));
- $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
- }
- $this->addOrderLog(
- $sid,
- 'purchase_confirm',
- '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
- $poIdFinal > 0 ? $poIdFinal : null
- );
- $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
- $sendSmsSafe = function ($phone, $content) {
- $phone = trim((string)$phone);
- if ($phone === '') {
- return;
- }
- try {
- $this->smsbao($phone, $content);
- } catch (\Throwable $e) {
- Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
- }
- };
- foreach ($selectedIds as $pid) {
- $dr = $this->purchaseOrderDetai($sid, $pid);
- if (!is_array($dr)) {
- continue;
- }
- $cname = trim((string)($dr['company_name'] ?? ''));
- $ph = trim((string)($dr['phone'] ?? ''));
- $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
- 'company_name' => $cname,
- 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
- 'phone' => $ph,
- ]));
- $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
- }
- foreach ($unselectedIds as $pid) {
- $dr = $this->purchaseOrderDetai($sid, $pid);
- if (!is_array($dr)) {
- continue;
- }
- $cname = trim((string)($dr['company_name'] ?? ''));
- $ph = trim((string)($dr['phone'] ?? ''));
- $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
- 'company_name' => $cname,
- 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
- 'phone' => $ph,
- ]));
- $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
- }
- Log::write(sprintf(
- 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
- $scydgyId,
- $purchaseOrderId,
- json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
- json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
- ), 'notice');
- $pdfPublicPath = '';
- try {
- $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
- } catch (\Throwable $e) {
- Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
- }
- return [
- 'scydgy_id' => $scydgyId,
- 'purchase_order_id' => $purchaseOrderId,
- 'selected_ids' => $selectedIds,
- 'unselected_ids' => $unselectedIds,
- 'purchase_confirm_pdf' => $pdfPublicPath,
- ];
- }
- /**
- * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
- *
- * @param int[] $detailIds
- */
- protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
- {
- $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
- if ($detailIds === []) {
- return;
- }
- $payload = ['status_name' => $statusName];
- try {
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
- } catch (\Throwable $e) {
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
- }
- }
- /**
- * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
- */
- protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
- {
- try {
- $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
- } catch (\Throwable $e) {
- return;
- }
- if (!is_array($rows)) {
- return;
- }
- foreach ($rows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
- $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
- try {
- Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
- } catch (\Throwable $e) {
- }
- }
- }
- /**
- * @param array<string, mixed> $detailRow
- */
- protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
- {
- $am = $detailRow['amount'] ?? null;
- $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
- $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
- $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
- return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
- }
- /**
- * @return int[]
- */
- protected function purchaseOrderDetail(int $scydgyId): array
- {
- if (!$this->isValidScydgyRowId($scydgyId)) {
- return [];
- }
- try {
- $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
- $this->applyActivePurchaseOrderDetailWhere($listQuery);
- $list = $listQuery->select();
- } catch (\Throwable $e) {
- return [];
- }
- if (!is_array($list)) {
- return [];
- }
- $ids = [];
- foreach ($list as $r) {
- if (!is_array($r)) {
- continue;
- }
- $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
- if ($pk > 0) {
- $ids[] = $pk;
- }
- }
- return array_values(array_unique($ids));
- }
- /**
- * 获取当前登录用户信息 [id, 展示名]
- */
- protected function GetUseName(): array
- {
- $id = 0;
- $name = '';
- try {
- if ($this->auth && $this->auth->isLogin()) {
- $u = $this->auth->getUserInfo();
- if (is_array($u)) {
- $id = (int)($u['id'] ?? 0);
- $name = trim((string)($u['nickname'] ?? ''));
- if ($name === '') {
- $name = trim((string)($u['username'] ?? ''));
- }
- }
- }
- } catch (\Throwable $e) {
- }
- if ($name === '') {
- $name = '未知用户';
- }
- return [$id, $name];
- }
- /**
- * 外发采购操作日志(表未建时仅写 runtime 日志,不中断业务)
- */
- protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
- {
- if (!$this->isValidScydgyRowId($scydgyId) || $content === '') {
- return;
- }
- list($adminId, $adminName) = $this->GetUseName();
- $cut = function ($s, $max) {
- if (function_exists('mb_substr')) {
- return mb_substr($s, 0, $max, 'UTF-8');
- }
- return strlen($s) <= $max ? $s : substr($s, 0, $max);
- };
- try {
- Db::table('purchase_order_oper_log')->insert([
- 'scydgy_id' => $scydgyId,
- 'purchase_order_id' => $purchaseOrderId,
- 'admin_id' => $adminId,
- 'admin_name' => $cut($adminName, 64),
- 'action' => $cut((string)$action, 64),
- 'content' => $cut($content, 1000),
- // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
- 'createtime' => time(),
- ]);
- } catch (\Throwable $e) {
- Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
- }
- }
- /**
- * 按主键取一条
- */
- protected function purchaseOrderDetai(int $scydgyId, int $pk): array
- {
- if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
- return [];
- }
- try {
- $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
- if (is_array($one)) {
- return $one;
- }
- } catch (\Throwable $e) {
- }
- try {
- $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
- if (is_array($one)) {
- return $one;
- }
- } catch (\Throwable $e) {
- }
- return [];
- }
- /**
- * 主表/明细时间字段统一为可读字符串(用于详情进度)
- */
- protected function formatProcuremenDetailTime($v): string
- {
- if ($v === null || $v === '') {
- return '';
- }
- if (is_numeric($v) && (int)$v > 946684800) {
- return date('Y-m-d H:i:s', (int)$v);
- }
- $s = trim((string)$v);
- if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
- return $s;
- }
- return '';
- }
- /**
- * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
- */
- protected function formatDeliveryYmd($v): string
- {
- if ($v === null || $v === '') {
- return '';
- }
- $s = trim((string)$v);
- if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
- return '';
- }
- if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
- return $m[1];
- }
- $ts = strtotime($s);
- return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
- }
- /**
- * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
- */
- protected function detailRowSupplierAccepted(array $r): bool
- {
- $am = $r['amount'] ?? null;
- $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
- $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
- $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
- return $okAmt && $okDel;
- }
- /**
- * 是否已向外发/供应商下发(有下发明细、已进入审批流或记录下发时间)
- */
- protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
- {
- if ($detailCount > 0) {
- return true;
- }
- $wf = (int)($main['wflow_status'] ?? 0);
- if ($wf >= 1) {
- return true;
- }
- $pickTime = trim((string)($main['pick_time'] ?? ''));
- if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
- return true;
- }
- return false;
- }
- /**
- * 下发时间:优先 pick_time,其次首条下发明细时间
- */
- protected function resolveProcuremenIssueTime(array $main, array $details): string
- {
- $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
- if ($issueTime !== '') {
- return $issueTime;
- }
- foreach ($details as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
- if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
- $issueTime = $t;
- }
- }
- if ($issueTime !== '') {
- return $issueTime;
- }
- return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
- }
- /**
- * 直接点「完结」时间:优先操作记录 mark_complete
- */
- protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
- {
- if (!$this->isValidScydgyRowId($scydgyId)) {
- return '';
- }
- try {
- $log = Db::table('purchase_order_oper_log')
- ->where('scydgy_id', $scydgyId)
- ->where('action', 'mark_complete')
- ->order('id', 'desc')
- ->find();
- if (is_array($log)) {
- $ct = (int)($log['createtime'] ?? 0);
- if ($ct > 946684800) {
- return date('Y-m-d H:i:s', $ct);
- }
- }
- } catch (\Throwable $e) {
- }
- return '';
- }
- /**
- * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
- *
- * @param array $main purchase_order 一行
- * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
- * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
- */
- protected function buildProcuremenDetailsViewData(array $main, array $details): array
- {
- $issueCnt = count($details);
- $acceptCnt = 0;
- $pickedName = '';
- $pickedTime = '';
- foreach ($details as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- if ($this->detailRowSupplierAccepted($dr)) {
- $acceptCnt++;
- }
- if ((int)($dr['status'] ?? 0) === 1) {
- if ($pickedName === '') {
- $pickedName = trim((string)($dr['company_name'] ?? ''));
- }
- if ($pickedTime === '') {
- $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
- if ($pickedTime === '') {
- $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
- }
- }
- }
- }
- $hasMain = $main !== [];
- $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
- if ($poTime === '') {
- $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
- }
- $mainStatus = isset($main['status']) ? (int)$main['status'] : 0;
- $wflowStatus = (int)($main['wflow_status'] ?? 0);
- $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
- $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
- $auditNotifyTime = '';
- if ($wflowStatus >= 2 || ($wflowStatus === 0 && $issueCnt > 0)) {
- $scydgyId = (int)($main['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($scydgyId)) {
- try {
- $auditLog = Db::table('purchase_order_oper_log')
- ->where('scydgy_id', $scydgyId)
- ->where('action', 'audit_confirm')
- ->order('id', 'desc')
- ->find();
- if (is_array($auditLog)) {
- $ct = (int)($auditLog['createtime'] ?? 0);
- if ($ct > 946684800) {
- $auditNotifyTime = date('Y-m-d H:i:s', $ct);
- }
- }
- } catch (\Throwable $e) {
- }
- }
- if ($auditNotifyTime === '' && $issueTime !== '') {
- $auditNotifyTime = $issueTime;
- }
- }
- $supplierTime = '';
- if ($acceptCnt > 0) {
- foreach ($details as $dr) {
- if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
- continue;
- }
- $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
- if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
- $supplierTime = $t;
- }
- }
- }
- $directComplete = ($mainStatus === 1 && !$issued);
- $scydgyId = (int)($main['scydgy_id'] ?? 0);
- $doneTime = '';
- if ($mainStatus === 1) {
- if ($directComplete) {
- $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
- }
- if ($doneTime === '') {
- $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
- }
- if ($doneTime === '') {
- foreach ($details as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
- if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
- $doneTime = $t;
- }
- }
- }
- if ($doneTime === '') {
- $doneTime = $poTime;
- }
- }
- if ($directComplete) {
- // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
- $step1Done = $hasMain;
- $step2Done = false;
- $step3Done = false;
- $step4Done = false;
- $step5Done = false;
- $step6Done = true;
- } else {
- $step1Done = $issued;
- $step2Done = $issued;
- // wflow=1:初选已下发、待审批确认通知;wflow>=2 或旧数据(有明细且 wf=0)视为已通知
- $step3Done = $wflowStatus >= 2 || ($wflowStatus === 0 && $issueCnt > 0);
- $step4Done = $acceptCnt > 0;
- $step5Done = false;
- foreach ($details as $dr) {
- if (is_array($dr) && (int)($dr['status'] ?? 0) === 1) {
- $step5Done = true;
- break;
- }
- }
- $step6Done = $mainStatus === 1;
- // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
- if ($mainStatus === 1 && $issued) {
- $step3Done = true;
- $step4Done = true;
- $step5Done = true;
- if ($supplierTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $supplierTime = $fillT;
- }
- }
- if ($pickedTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $pickedTime = $fillT;
- }
- }
- if ($auditNotifyTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $auditNotifyTime = $fillT;
- }
- }
- }
- }
- $auditPendingSubtitle = '待确认通知';
- $steps = [
- [
- 'title' => '未发',
- 'subtitle' => '',
- 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
- 'done' => $step1Done,
- ],
- [
- 'title' => '初选下发',
- 'subtitle' => '',
- 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
- 'done' => $step2Done,
- ],
- [
- 'title' => '待审批',
- 'subtitle' => $step3Done ? '' : $auditPendingSubtitle,
- 'time' => $step3Done ? $auditNotifyTime : '',
- 'done' => $step3Done,
- ],
- [
- 'title' => '供应商接单',
- 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
- 'time' => $step4Done ? $supplierTime : '',
- 'done' => $step4Done,
- ],
- [
- 'title' => '采购确认',
- 'subtitle' => $pickedName !== '' ? ('选中供应商:' . $pickedName) : '',
- 'time' => $step5Done ? ($pickedTime !== '' ? $pickedTime : '') : '',
- 'done' => $step5Done,
- ],
- [
- 'title' => '已完结',
- 'subtitle' => '',
- 'time' => $step6Done ? $doneTime : '',
- 'done' => $step6Done,
- ],
- ];
- $currentIdx = count($steps) - 1;
- if (!$directComplete) {
- foreach ($steps as $i => $s) {
- if (!$s['done']) {
- $currentIdx = $i;
- break;
- }
- }
- }
- $nSteps = count($steps);
- foreach ($steps as $idx => &$s) {
- $s['current'] = ($idx === $currentIdx);
- if ($idx === 0) {
- $s['pdf_left_bg'] = '';
- } else {
- $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
- }
- if ($idx >= $nSteps - 1) {
- $s['pdf_right_bg'] = '';
- } else {
- $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
- }
- }
- unset($s);
- $labelMap = [
- 'CCYDH' => '订单号',
- 'CYJMC' => '印件名称',
- 'CCLBMMC' => '承揽部门',
- 'CGYMC' => '工序名称',
- 'CDW' => '单位',
- 'NGZL' => '工作量',
- 'CDF' => '单价',
- 'cGzzxMc' => '工作中心',
- 'MBZ' => '备注',
- 'This_quantity' => '本次数量',
- 'ceilingPrice' => '最高限价',
- ];
- $orderSummary = [];
- foreach ($labelMap as $key => $lab) {
- if (!array_key_exists($key, $main)) {
- continue;
- }
- $val = $main[$key];
- if ($val === null) {
- $val = '';
- } elseif (!is_scalar($val)) {
- $val = json_encode($val, JSON_UNESCAPED_UNICODE);
- } else {
- $val = (string)$val;
- }
- $orderSummary[] = ['label' => $lab, 'value' => $val];
- }
- $orderSummaryGrid = [];
- $n = count($orderSummary);
- for ($i = 0; $i < $n; $i += 2) {
- $left = $orderSummary[$i];
- $hasRight = ($i + 1) < $n;
- $orderSummaryGrid[] = [
- 'l1' => $left['label'],
- 'v1' => $left['value'],
- 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
- 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
- ];
- }
- return [
- 'steps' => $steps,
- 'orderSummary' => $orderSummary,
- 'orderSummaryGrid' => $orderSummaryGrid,
- 'detailRows' => $details,
- ];
- }
- /**
- * 加载并 assign 外发采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
- *
- * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
- */
- protected function prepareProcuremenDetailsView(string $ids): array
- {
- $main = [];
- try {
- $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- $main = is_array($one) ? $one : [];
- } catch (\Throwable $e) {
- $main = [];
- }
- $details = [];
- $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
- if ($mergeRows === []) {
- $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
- if ($mergeRows === [] && $main !== []) {
- $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
- }
- }
- $detailSidList = [];
- $anchorSid = (int)$ids;
- if ($anchorSid !== 0) {
- $detailSidList[$anchorSid] = true;
- }
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($mr);
- if ($sid !== 0) {
- $detailSidList[$sid] = true;
- }
- }
- try {
- if ($detailSidList !== []) {
- $details = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($detailSidList))
- ->order('id', 'asc')
- ->select();
- }
- } catch (\Throwable $e) {
- $details = [];
- }
- if (!is_array($details)) {
- $details = [];
- }
- foreach ($details as &$r) {
- if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
- $r['id'] = $r['ID'];
- }
- if (isset($r['createtime'])) {
- if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
- $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
- } else {
- $r['createtime_text'] = (string)$r['createtime'];
- }
- } else {
- $r['createtime_text'] = '';
- }
- $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
- $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
- }
- unset($r);
- $activeDetails = [];
- foreach ($details as $r) {
- if (is_array($r) && empty($r['is_void'])) {
- $activeDetails[] = $r;
- }
- }
- $operLogs = [];
- try {
- $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $operLogs = [];
- }
- if (!is_array($operLogs)) {
- $operLogs = [];
- }
- foreach ($operLogs as &$lg) {
- if (!is_array($lg)) {
- continue;
- }
- $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
- $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
- }
- unset($lg);
- $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
- $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
- $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
- if ($ccydh === '') {
- foreach ($details as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ccydh = trim((string)($r['CCYDH'] ?? ''));
- if ($ccydh !== '') {
- break;
- }
- }
- }
- $this->view->assign('ccydh', $ccydh);
- $this->view->assign('steps', $bundle['steps']);
- $this->view->assign('orderSummary', $bundle['orderSummary']);
- $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
- $this->view->assign('processDisplayRows', $quoteView['process_rows']);
- $this->view->assign('processCount', count($mergeRows));
- $this->view->assign('detailRows', $details);
- $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
- $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
- $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
- $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
- $this->view->assign('operLogs', $operLogs);
- return [
- 'ok' => $main !== [] || $details !== [],
- 'ccydh' => $ccydh,
- ];
- }
- /**
- * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
- */
- public function details()
- {
- $ids = $this->request->param('ids', $this->request->param('id', ''));
- if (is_array($ids)) {
- $ids = isset($ids[0]) ? $ids[0] : '';
- }
- $ids = trim((string)$ids);
- if ($ids === '') {
- $this->error(__('Invalid parameters'));
- }
- $this->assertManualOrderDetailsViewable((int)$ids);
- $this->prepareProcuremenDetailsView($ids);
- /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
- $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
- $this->view->engine->layout(false);
- try {
- return $this->view->fetch('procuremen/details_dialog_shell');
- } finally {
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- }
- }
- /**
- * 解析合并审核工序行(订单号须一致,且均未外发)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
- {
- $primary = json_decode($rowJson, true);
- if (!is_array($primary)) {
- $this->error(__('Invalid parameters'));
- }
- $merge = json_decode($mergeRowsJson, true);
- if (!is_array($merge) || $merge === []) {
- $merge = [$primary];
- }
- $seen = [];
- $out = [];
- foreach ($merge as $r) {
- if (!is_array($r)) {
- continue;
- }
- $id = $this->extractScydgyRowId($r);
- if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
- continue;
- }
- $seen[$id] = true;
- $out[] = $r;
- }
- if ($out === []) {
- $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
- }
- $ccydh = null;
- foreach ($out as $r) {
- $dh = trim((string)($r['CCYDH'] ?? ''));
- if ($ccydh === null) {
- $ccydh = $dh;
- } elseif ($dh !== $ccydh) {
- $this->error('合并审核要求所选行的订单号一致');
- }
- }
- $ids = [];
- foreach ($out as $r) {
- $id = $this->extractScydgyRowId($r);
- if ($this->isValidScydgyRowId($id)) {
- $ids[$id] = true;
- }
- }
- $poBySid = [];
- $detCntBySid = [];
- if ($ids !== []) {
- $idList = array_keys($ids);
- try {
- $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
- if (is_array($poList)) {
- foreach ($poList as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $poBySid[$sid] = $po;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- try {
- $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
- $this->applyActivePurchaseOrderDetailWhere($detQuery);
- $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
- if (is_array($detRows)) {
- foreach ($detRows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $sid = (int)($dr['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
- }
- }
- }
- } catch (\Throwable $e) {
- }
- }
- foreach ($out as $r) {
- $id = $this->extractScydgyRowId($r);
- if (!$this->isValidScydgyRowId($id)) {
- continue;
- }
- $po = $poBySid[$id] ?? null;
- if (!is_array($po)) {
- continue;
- }
- $wf = (int)($po['wflow_status'] ?? 0);
- $st = $po['status'] ?? null;
- if ($wf >= 1 || $st === 1 || $st === '1') {
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
- }
- $detCnt = (int)($detCntBySid[$id] ?? 0);
- if ($detCnt > 0 && $wf < 1) {
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
- }
- }
- return $out;
- }
- /**
- * 规范化下发/确认时勾选的供应商
- *
- * @param array<int, mixed> $companies
- * @return array<int, array<string, string>>
- */
- protected function normalizePickCompanies(array $companies): array
- {
- $out = [];
- foreach ($companies as $c) {
- if (!is_array($c)) {
- continue;
- }
- $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
- if ($name === '') {
- continue;
- }
- $out[] = [
- 'name' => $name,
- 'company_name' => $name,
- 'username' => trim((string)($c['username'] ?? '')),
- 'email' => trim((string)($c['email'] ?? '')),
- 'phone' => trim((string)($c['phone'] ?? '')),
- 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
- ];
- }
- return $out;
- }
- /**
- * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
- *
- * @param array<int, array<string, mixed>> $pool
- * @return array<int, array<string, mixed>>
- */
- protected function collapseProcuremenPoolByOrder(array $pool): array
- {
- if ($pool === []) {
- return [];
- }
- $groups = [];
- foreach ($pool as $row) {
- if (!is_array($row)) {
- continue;
- }
- $dh = trim((string)($row['CCYDH'] ?? ''));
- $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
- if (!isset($groups[$key])) {
- $groups[$key] = [];
- }
- $groups[$key][] = $row;
- }
- $out = [];
- foreach ($groups as $ccydh => $rows) {
- if ($rows === []) {
- continue;
- }
- usort($rows, function ($a, $b) {
- return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
- });
- $head = $rows[0];
- $gymcList = [];
- foreach ($rows as $r) {
- $g = trim((string)($r['CGYMC'] ?? ''));
- if ($g !== '' && !in_array($g, $gymcList, true)) {
- $gymcList[] = $g;
- }
- }
- $merged = $head;
- $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
- $merged['process_count'] = count($rows);
- $merged['_order_merge_rows'] = $rows;
- if (count($rows) > 1) {
- $merged['CGYMC'] = implode('、', $gymcList);
- }
- $mergedPickTime = '';
- foreach ($rows as $r) {
- $t = $this->procuremenRowListSortTime($r, 'pick_time');
- if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
- $mergedPickTime = $t;
- }
- }
- if ($mergedPickTime !== '') {
- $merged['pick_time'] = $mergedPickTime;
- }
- $out[] = $merged;
- }
- usort($out, function ($a, $b) {
- $ta = $this->procuremenRowListSortTime($a, 'pick_time');
- $tb = $this->procuremenRowListSortTime($b, 'pick_time');
- if ($ta === $tb) {
- $ida = (int)($a['purchase_order_id'] ?? 0);
- $idb = (int)($b['purchase_order_id'] ?? 0);
- if ($ida !== $idb) {
- return $idb <=> $ida;
- }
- return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
- }
- if ($ta === '') {
- return 1;
- }
- if ($tb === '') {
- return -1;
- }
- return strcmp($tb, $ta);
- });
- return $out;
- }
- /**
- * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
- *
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- if ($scydgyId === '') {
- return $empty;
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor) || (int)($anchor['wflow_status'] ?? 0) !== 1) {
- return $empty;
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- if ($ccydh === '') {
- return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
- }
- try {
- $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('wflow_status', 1)->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- /**
- * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
- */
- protected function purchaseOrderRowInConfirmStage(array $po): bool
- {
- $st = $po['status'] ?? null;
- if ($st === 1 || $st === '1') {
- return false;
- }
- $wf = (int)($po['wflow_status'] ?? 0);
- if ($wf === 2) {
- return true;
- }
- if ($wf === 0) {
- $sid = (int)($po['scydgy_id'] ?? 0);
- return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
- }
- return false;
- }
- /**
- * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
- *
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- if ($scydgyId === '') {
- return $empty;
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
- return $empty;
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- if ($ccydh === '') {
- return [
- 'ccydh' => '',
- 'pos' => [$anchor],
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
- ];
- }
- try {
- $pos = Db::table('purchase_order')
- ->where('CCYDH', $ccydh)
- ->where('status', 0)
- ->where(function ($q) {
- $q->where('wflow_status', 2)
- ->whereOr(function ($q2) {
- $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
- });
- })
- ->order('scydgy_id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- $pos = array_values(array_filter($pos, function ($po) {
- return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
- }));
- if ($pos === []) {
- $pos = [$anchor];
- }
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- /**
- * @param array<int, array<string, mixed>> $purchaseOrders
- * @return array<int, array<string, mixed>>
- */
- protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
- {
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
- $byId = [];
- foreach ($pool as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $byId[$sid] = $r;
- }
- }
- $out = [];
- foreach ($purchaseOrders as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
- $out[] = $byId[$sid];
- }
- }
- return $out;
- }
- /**
- * 详情 / PDF:同一外发批次下的全部工序行(与确认供应商弹窗一致)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- if ($scydgyId === '') {
- return [];
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor)) {
- return [];
- }
- if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
- return [];
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- $pickTime = trim((string)($anchor['pick_time'] ?? ''));
- $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
- try {
- $q = Db::table('purchase_order');
- if ($ccydh !== '') {
- $q->where('CCYDH', $ccydh);
- } else {
- $q->where('scydgy_id', $scydgyId);
- }
- if ($isValidPick) {
- $q->where('pick_time', $pickTime);
- }
- $pos = $q->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- $pos = array_values(array_filter($pos, function ($po) {
- if (!is_array($po)) {
- return false;
- }
- $mr = $po['mod_rq'] ?? null;
- if ($mr === null || $mr === '') {
- return true;
- }
- $mrs = trim((string)$mr);
- return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
- }));
- if ($pos === []) {
- $pos = [$anchor];
- }
- $rows = $this->scydgyRowsForPurchaseOrders($pos);
- if ($rows === []) {
- $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
- }
- return $rows;
- }
- /**
- * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
- *
- * @param array<int, array<string, mixed>> $mergeRows
- * @return array<int, array<string, mixed>>
- */
- protected function buildAuditProcessDisplayRows(array $mergeRows): array
- {
- $list = array_values($mergeRows);
- $n = count($list);
- $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
- $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
- $mergeSame = $n > 1 && $orderKey0 !== '';
- if ($mergeSame) {
- foreach ($list as $rr) {
- if (!is_array($rr)) {
- $mergeSame = false;
- break;
- }
- if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
- || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
- $mergeSame = false;
- break;
- }
- }
- }
- $out = [];
- foreach ($list as $idx => $r) {
- if (!is_array($r)) {
- continue;
- }
- $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
- if (is_scalar($qty)) {
- $qty = trim((string)$qty);
- } else {
- $qty = '';
- }
- if ($qty === '') {
- $gzl = $r['NGZL'] ?? '';
- if (is_scalar($gzl)) {
- $qty = trim((string)$gzl);
- }
- }
- $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
- $sid = $this->extractScydgyRowId($r);
- $out[] = [
- 'seq' => $idx + 1,
- 'scydgy_id' => $sid,
- 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
- 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
- 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
- 'CDW' => trim((string)($r['CDW'] ?? '')),
- 'NGZL' => $r['NGZL'] ?? '',
- 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
- 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
- 'CDF' => trim((string)($r['CDF'] ?? '')),
- 'MBZ' => trim((string)($r['MBZ'] ?? '')),
- 'show_order_cells' => !$mergeSame || $idx === 0,
- 'order_rowspan' => $mergeSame ? $n : 1,
- ];
- }
- return $out;
- }
- /**
- * 解析金额/数量(去千分位等非数字字符)
- */
- protected function parseProcuremenMoneyNumber($value): ?float
- {
- if ($value === null || $value === '') {
- return null;
- }
- if (is_numeric($value)) {
- return (float)$value;
- }
- $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
- return ($v !== '' && is_numeric($v)) ? (float)$v : null;
- }
- protected function formatProcuremenMoneyDisplay(?float $amount): string
- {
- if ($amount === null) {
- return '';
- }
- return (string)(int)round($amount);
- }
- /**
- * 列表/详情展示:工作量为 0 时显示空
- */
- protected function formatProcuremenWorkloadDisplay($value): string
- {
- if ($value === null || $value === '') {
- return '';
- }
- $s = trim((string)$value);
- if ($s === '') {
- return '';
- }
- if (is_numeric($s) && (float)$s == 0) {
- return '';
- }
- return $s;
- }
- /**
- * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
- */
- protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
- {
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- if (!$this->isPurchaseOrderDetailVoid($d) && (int)($d['status'] ?? 0) === 1) {
- $cn = trim((string)($d['company_name'] ?? ''));
- if ($cn !== '') {
- return $cn;
- }
- }
- }
- return trim((string)($main['pick_company_name'] ?? ''));
- }
- /**
- * 详情报价小计:单价 × 本工序本次数量
- */
- protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
- {
- $unit = $this->parseProcuremenMoneyNumber($amountRaw);
- if ($unit === null) {
- return null;
- }
- $qty = $this->parseProcuremenMoneyNumber($qtyStr);
- if ($qty === null || $qty <= 0) {
- return null;
- }
- return $unit * $qty;
- }
- /**
- * 详情页:工序小计 + 供应商分组报价与总计
- *
- * @param array<int, array<string, mixed>> $mergeRows
- * @param array<int, array<string, mixed>> $details 含有效与历史明细
- * @return array{
- * process_rows: array,
- * supplier_groups: array,
- * order_total_text: string,
- * order_total_has: bool,
- * selected_company: string
- * }
- */
- protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
- {
- $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
- $qtyBySid = [];
- $gymcBySid = [];
- $orderedSids = [];
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($mr);
- if ($sid > 0) {
- $orderedSids[] = $sid;
- }
- $qty = trim((string)($mr['This_quantity'] ?? ''));
- if ($qty === '') {
- $qty = trim((string)($mr['NGZL'] ?? ''));
- }
- $qtyBySid[$sid] = $qty;
- $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
- }
- $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
- $detailByCompanySid = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $cn = trim((string)($d['company_name'] ?? ''));
- $sid = (int)($d['scydgy_id'] ?? 0);
- if ($cn === '' || $sid === 0) {
- continue;
- }
- if (!isset($detailByCompanySid[$cn])) {
- $detailByCompanySid[$cn] = [];
- }
- $detailByCompanySid[$cn][$sid] = $d;
- }
- $supplierGroups = [];
- foreach ($detailByCompanySid as $cn => $bySid) {
- $lines = [];
- $groupTotal = 0.0;
- $groupHas = false;
- $groupVoid = true;
- $usedSids = [];
- $appendLine = function (int $sid, array $d) use (
- &$lines,
- &$groupTotal,
- &$groupHas,
- &$groupVoid,
- $qtyBySid,
- $gymcBySid
- ) {
- $isVoid = $this->isPurchaseOrderDetailVoid($d);
- if (!$isVoid) {
- $groupVoid = false;
- }
- $qtyStr = $qtyBySid[$sid] ?? '';
- $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
- $sub = null;
- if (!$isVoid && $amountNum !== null) {
- $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
- if ($sub !== null) {
- $groupTotal += $sub;
- $groupHas = true;
- }
- }
- $ct = $d['createtime_text'] ?? '';
- if ($ct === '' && isset($d['createtime'])) {
- $ct = $this->formatProcuremenDetailTime($d['createtime'] ?? null);
- }
- $lines[] = [
- 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
- 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : trim((string)($d['amount'] ?? '')),
- 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
- 'delivery_ymd' => $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null),
- 'status' => (int)($d['status'] ?? 0),
- 'is_void' => $isVoid,
- 'createtime_text' => $ct,
- ];
- };
- foreach ($orderedSids as $sid) {
- if (!isset($bySid[$sid])) {
- continue;
- }
- $usedSids[$sid] = true;
- $appendLine($sid, $bySid[$sid]);
- }
- foreach ($bySid as $sid => $d) {
- if (isset($usedSids[$sid])) {
- continue;
- }
- $appendLine((int)$sid, $d);
- }
- $supplierGroups[] = [
- 'company_name' => $cn,
- 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
- 'is_void' => $groupVoid,
- 'lines' => $lines,
- 'line_count' => count($lines),
- 'total_text' => $groupHas ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
- 'has_total' => $groupHas,
- ];
- }
- usort($supplierGroups, function ($a, $b) {
- if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
- return ($a['is_void'] ?? false) ? 1 : -1;
- }
- if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
- return ($a['is_selected'] ?? false) ? -1 : 1;
- }
- return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
- });
- return [
- 'process_rows' => $processRows,
- 'supplier_groups' => $supplierGroups,
- 'order_total_text' => '',
- 'order_total_has' => false,
- 'selected_company' => $selectedCompany,
- ];
- }
- /**
- * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
- */
- protected function buildProcessLinesPlain(array $mergeRows): string
- {
- $lines = [];
- $i = 1;
- foreach ($mergeRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $dw = trim((string)($r['CDW'] ?? ''));
- $gzl = trim((string)($r['NGZL'] ?? ''));
- $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
- $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
- if ($dw !== '') {
- $parts[] = '单位:' . $dw;
- }
- if ($gzl !== '') {
- $parts[] = '工作量:' . $gzl;
- }
- if ($qty !== '') {
- $parts[] = '本次数量:' . $qty;
- }
- $lines[] = implode(' ', $parts);
- $i++;
- }
- return implode("\n", $lines);
- }
- /**
- * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
- *
- * @return array<string, string>
- */
- protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
- {
- $po = null;
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
- $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
- if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
- $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
- if (is_array($any)) {
- if ($ccydh === '') {
- $ccydh = trim((string)($any['CCYDH'] ?? ''));
- }
- if ($cyjmc === '') {
- $cyjmc = trim((string)($any['CYJMC'] ?? ''));
- }
- }
- }
- $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
- $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
- $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
- return [
- 'ccydh' => $ccydh,
- 'cyjmc' => $cyjmc,
- 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
- 'process_lines' => $processLines,
- 'process_lines_html' => '',
- ];
- }
- /**
- * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
- */
- protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
- {
- $lines = [];
- if ($ccydh !== '') {
- $lines[] = '订单号:' . $ccydh;
- }
- if ($cyjmc !== '') {
- $lines[] = '印件名称:' . $cyjmc;
- }
- if ($processPlain !== '') {
- $lines[] = $processPlain;
- }
- return implode("\n", $lines);
- }
- /**
- * 各工序手机端链接(纯文本,供短信模版 {platform_links})
- *
- * @param array<int, array{cgymc:string,url:string}> $detailLinks
- */
- protected function buildPlatformLinksPlain(array $detailLinks): string
- {
- $lines = [];
- $i = 1;
- foreach ($detailLinks as $lk) {
- if (!is_array($lk)) {
- continue;
- }
- $url = trim((string)($lk['url'] ?? ''));
- if ($url === '') {
- continue;
- }
- $label = trim((string)($lk['cgymc'] ?? ''));
- if ($label === '') {
- $label = '工序' . $i;
- }
- $lines[] = $label . ':' . $url;
- $i++;
- }
- return implode("\n", $lines);
- }
- /**
- * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
- *
- * @param array<int, array{cgymc:string,url:string}> $detailLinks
- */
- protected function buildPlatformLinksHtml(array $detailLinks): string
- {
- $parts = [];
- $i = 1;
- foreach ($detailLinks as $lk) {
- if (!is_array($lk)) {
- continue;
- }
- $url = trim((string)($lk['url'] ?? ''));
- if ($url === '') {
- continue;
- }
- $label = trim((string)($lk['cgymc'] ?? ''));
- if ($label === '') {
- $label = '工序' . $i;
- }
- $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
- $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
- . ' — <a href="' . $urlEsc . '">点击查看</a>';
- $i++;
- }
- return implode("<br>\n", $parts);
- }
- /**
- * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
- *
- * @return array<string, mixed>
- */
- protected function loadMailerConfig(): array
- {
- try {
- $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
- } catch (\Throwable $e) {
- $cfg = [];
- }
- return is_array($cfg) ? $cfg : [];
- }
- protected function loadNotifyTemplateRow(string $scene): ?array
- {
- try {
- $row = Db::table('purchase_sms_template')
- ->where('scene', $scene)
- ->where(function ($q) {
- $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
- })
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- if (!is_array($row) || $row === []) {
- return null;
- }
- return [
- 'title' => trim((string)($row['title'] ?? '')),
- 'content' => trim((string)($row['content'] ?? '')),
- ];
- }
- /**
- * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
- */
- protected function buildProcessLinesHtml(array $mergeRows): string
- {
- if (count($mergeRows) <= 1) {
- $r = $mergeRows[0] ?? [];
- if (!is_array($r)) {
- return '';
- }
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $dw = trim((string)($r['CDW'] ?? ''));
- $gzl = trim((string)($r['NGZL'] ?? ''));
- $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
- $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
- if ($dw !== '') {
- $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
- }
- if ($gzl !== '') {
- $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
- }
- if ($qty !== '') {
- $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
- }
- return $html;
- }
- $rows = '';
- $i = 1;
- foreach ($mergeRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
- $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
- $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
- $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
- $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
- $i++;
- }
- if ($rows === '') {
- return '';
- }
- return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
- . '<thead><tr style="background:#f5f5f5;">'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
- . '</tr></thead><tbody>' . $rows . '</tbody></table>';
- }
- protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
- {
- $sysRq = trim($sysRq);
- if ($sysRq === '') {
- if ($required) {
- $this->error('请选择截止时间');
- }
- return '';
- }
- $ts = strtotime($sysRq);
- if ($ts === false || $ts <= 0) {
- $this->error('截止时间格式无效');
- }
- return date('Y-m-d H:i:s', $ts);
- }
- protected function formatProcuremenSysRqForInput($sysRq): string
- {
- $sr = trim((string)$sysRq);
- if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
- return '';
- }
- $ts = strtotime($sr);
- return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
- }
- /**
- * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
- * @return array{ccydh?:string,pos:array,merge_rows:array}
- */
- protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
- {
- $sysRqPost = trim($sysRqPost);
- if ($sysRqPost === '') {
- return $bundle;
- }
- $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
- $pos = $bundle['pos'] ?? [];
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
- }
- foreach ($pos as $i => $poRow) {
- if (is_array($pos[$i])) {
- $pos[$i]['sys_rq'] = $sysRqDb;
- }
- }
- $bundle['pos'] = $pos;
- return $bundle;
- }
- /**
- * 写入/更新 purchase_order(单道工序行)
- */
- protected function upsertPurchaseOrderFromRow(
- array $row,
- string $sysRqDb,
- ?int $wflowStatus = null,
- ?string $pickTime = null,
- ?array $exists = null
- ): void {
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
- }
- if ($exists === null) {
- $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- }
- $data = [
- 'scydgy_id' => $ids,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- 'status' => 0,
- 'sys_rq' => $sysRqDb,
- ];
- if ($wflowStatus !== null) {
- $data['wflow_status'] = $wflowStatus;
- }
- if ($pickTime !== null && $pickTime !== '') {
- $data['pick_time'] = $pickTime;
- $data['pick_company_name'] = '';
- }
- if ($exists) {
- $upd = $data;
- unset($upd['scydgy_id']);
- Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
- } else {
- $data['createtime'] = date('Y-m-d H:i:s');
- Db::table('purchase_order')->insert($data);
- }
- }
- /**
- * 外发下发 — 仅写入 purchase_order_detail(第一步不发通知)
- *
- * @return array<int, array{detail_id:int, cgymc:string, url:string}>
- */
- protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
- {
- $toDb = function ($value) {
- if ($value === null) {
- return null;
- }
- if (is_scalar($value)) {
- return $value;
- }
- return json_encode($value, JSON_UNESCAPED_UNICODE);
- };
- $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
- $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
- $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
- $username = isset($c['username']) ? trim((string)$c['username']) : '';
- if ($username === '') {
- $username = $this->resolveCustomerContactName($phone, $companyName);
- }
- if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
- throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
- }
- if ($phone === '') {
- throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
- }
- $detailLinks = [];
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($row);
- $detailId = 0;
- if ($skipExisting) {
- try {
- $existsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', $sid)
- ->where('company_name', $companyName);
- $this->applyActivePurchaseOrderDetailWhere($existsQuery);
- $exists = $existsQuery->find();
- } catch (\Throwable $e) {
- $exists = null;
- }
- if (is_array($exists)) {
- $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
- }
- }
- if ($detailId <= 0) {
- $one = [
- 'scydgy_id' => $toDb($sid),
- 'CCYDH' => $toDb($row['CCYDH'] ?? null),
- 'CYJMC' => $toDb($row['CYJMC'] ?? null),
- 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
- 'username' => $username !== '' ? $username : null,
- 'email' => isset($c['email']) ? (string)$c['email'] : null,
- 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
- 'createtime' => date('Y-m-d H:i:s'),
- 'status' => 0,
- 'status_name' => '未提交',
- ];
- Db::table('purchase_order_detail')->insert($one);
- $detailId = (int)Db::getLastInsID();
- }
- $mprocUrl = '';
- if ($buildMobileLinks && $detailId > 0) {
- $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
- }
- $detailLinks[] = [
- 'detail_id' => $detailId,
- 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
- 'url' => $mprocUrl,
- ];
- }
- return $detailLinks;
- }
- /**
- * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
- * @return array<string, mixed>
- */
- protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
- {
- $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
- $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
- $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
- $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
- $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
- $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
- $isMerge = !empty($ctx['is_merge']);
- $contactName = trim((string)($c['username'] ?? ''));
- if ($contactName === '') {
- $contactName = $this->resolveCustomerContactName($phone, $companyName);
- }
- $notifyVars = [
- 'company_name' => $companyName,
- 'contact_name' => $contactName,
- 'phone' => $phone,
- 'email' => $toEmail,
- 'ccydh' => (string)($ctx['ccydh'] ?? ''),
- 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
- 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
- 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
- 'deadline' => (string)($ctx['deadline'] ?? ''),
- 'process_lines' => (string)($ctx['process_plain'] ?? ''),
- 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
- 'platform_url' => $platformUrl,
- 'platform_links' => $platformLinksPlain,
- 'platform_links_html' => $platformLinksHtml,
- ];
- $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
- $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
- $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
- return [
- 'company_name' => $companyName,
- 'phone' => $phone,
- 'email' => $toEmail,
- 'sms_content' => $smsContent,
- 'mail_plain' => $mailPlain,
- 'mail_body' => $mailBody,
- 'notify_vars' => $notifyVars,
- 'detail_links' => $detailLinks,
- ];
- }
- /**
- * 确认供应商 — 向选定一家发送短信/邮件(第二步)
- *
- * @param array<string, mixed> $chosen
- * @param array<int, array<string, mixed>> $mergeRows
- * @param array{ccydh:string, pos:array} $bundle
- */
- protected function sendAuditSupplierConfirmNotify(array $chosen, array $mergeRows, array $bundle): void
- {
- $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, true, true);
- }
- /**
- * @param array<string, mixed> $chosen
- * @param array<int, array<string, mixed>> $mergeRows
- * @param array{ccydh:string, pos:array} $bundle
- */
- protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
- {
- if (!$sendSms && !$sendEmail) {
- return;
- }
- $companyName = trim((string)($chosen['name'] ?? ''));
- $phone = trim((string)($chosen['phone'] ?? ''));
- $toEmail = trim((string)($chosen['email'] ?? ''));
- if ($companyName === '') {
- throw new \Exception('供应商名称无效');
- }
- if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
- throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
- }
- if ($sendSms && $phone === '') {
- throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
- }
- $sids = [];
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($mr);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- }
- }
- if ($sids === []) {
- throw new \Exception('未找到工序行,无法发送通知');
- }
- $sysRqNotify = '';
- $pos = $bundle['pos'] ?? [];
- if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
- $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
- if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
- $ts = strtotime($sr);
- $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
- }
- }
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->where('company_name', $companyName);
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $details = [];
- }
- if (!is_array($details) || $details === []) {
- $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->where('company_name', $companyName);
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $details = [];
- }
- }
- if (!is_array($details) || $details === []) {
- throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
- }
- $detailLinks = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
- if ($detailId <= 0) {
- continue;
- }
- $sid = (int)($d['scydgy_id'] ?? 0);
- $gymc = '';
- foreach ($mergeRows as $mr) {
- if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
- $gymc = trim((string)($mr['CGYMC'] ?? ''));
- break;
- }
- }
- $detailLinks[] = [
- 'detail_id' => $detailId,
- 'cgymc' => $gymc,
- 'url' => $this->buildMprocMobileOrderUrl($detailId),
- ];
- }
- if ($detailLinks === []) {
- throw new \Exception('未找到有效的手机端链接,无法发送通知');
- }
- $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
- $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
- if ($sendEmail) {
- $mailTplRow = $this->loadNotifyTemplateRow('review_email');
- if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
- throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
- }
- $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
- $mailConfig = $this->loadMailerConfig();
- if (!$this->isProcuremenNotifyDryRun()) {
- if (empty($mailConfig['host'])) {
- throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
- }
- if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
- throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
- }
- }
- $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
- }
- if ($sendSms) {
- $this->issueSendSupplierSms($notifyBundle);
- }
- }
- /**
- * @param array<int, array<string, mixed>> $quoteGroups
- * @return array<int, array<string, mixed>>
- */
- protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
- {
- $names = [];
- if (is_string($companiesJson) && $companiesJson !== '') {
- $decoded = json_decode($companiesJson, true);
- if (is_array($decoded)) {
- foreach ($decoded as $nm) {
- $nm = trim((string)$nm);
- if ($nm !== '') {
- $names[] = $nm;
- }
- }
- }
- }
- $names = array_values(array_unique($names));
- if ($names === [] && $selectedCompany !== '') {
- $names = [$selectedCompany];
- }
- if ($names === []) {
- return $quoteGroups;
- }
- $targets = [];
- foreach ($quoteGroups as $g) {
- if (!is_array($g)) {
- continue;
- }
- $cn = trim((string)($g['name'] ?? ''));
- if ($cn !== '' && in_array($cn, $names, true)) {
- $targets[] = $g;
- }
- }
- return $targets;
- }
- /**
- * @return array{pos:array, merge_rows:array, bundle:array}
- */
- protected function loadAuditResendBundle(string $scydgyId): array
- {
- $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
- $pos = $bundle['pos'];
- $mergeRows = $bundle['merge_rows'];
- if ($pos === [] || $mergeRows === []) {
- $this->error('该订单不在待确认供应商状态');
- }
- $sysRqDb = '';
- if (isset($pos[0]) && is_array($pos[0])) {
- $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
- }
- foreach ($pos as $i => $poRow) {
- if (is_array($pos[$i]) && $sysRqDb !== '') {
- $pos[$i]['sys_rq'] = $sysRqDb;
- }
- }
- $bundle['pos'] = $pos;
- return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
- }
- /**
- * @param array<int, array<string, mixed>> $targets
- */
- protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
- {
- if ($targets === []) {
- $this->error('未找到可通知的供应商');
- }
- $notifyErrors = [];
- try {
- $this->notifyDryRunPreview = [];
- foreach ($targets as $g) {
- if (!is_array($g)) {
- continue;
- }
- $cname = trim((string)($g['name'] ?? ''));
- if ($cname === '') {
- continue;
- }
- $chosen = [
- 'name' => $cname,
- 'company_name' => $cname,
- 'email' => trim((string)($g['email'] ?? '')),
- 'phone' => trim((string)($g['phone'] ?? '')),
- 'username' => trim((string)($g['username'] ?? '')),
- ];
- try {
- $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
- } catch (\Throwable $e) {
- $notifyErrors[] = $cname . ':' . $e->getMessage();
- }
- }
- } catch (\Throwable $e) {
- $this->error('通知发送失败:' . $e->getMessage());
- }
- if ($notifyErrors !== []) {
- $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
- }
- if ($this->isProcuremenNotifyDryRun()) {
- $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
- 'notify_dry_run' => true,
- 'notify_preview' => $this->notifyDryRunPreview,
- ]);
- }
- $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
- }
- /**
- * 外发下发 — 写入下发明细并拼好短信/邮件内容(供第二步发送)
- *
- * @return array<string, mixed>
- */
- protected function issueBuildSupplierNotifyBundle(array $c, array $mergeRows, array $ctx): array
- {
- $detailLinks = $this->issuePersistSupplierDetails($c, $mergeRows);
- return $this->composeSupplierNotifyBundle($c, $ctx, $detailLinks);
- }
- /**
- * 外发下发 — 发送短信(一家供应商)
- *
- * @param array<string, mixed> $bundle issueBuildSupplierNotifyBundle 返回值
- */
- protected function issueSendSupplierSms(array $bundle): void
- {
- $companyName = (string)($bundle['company_name'] ?? '');
- $phone = (string)($bundle['phone'] ?? '');
- $smsContent = (string)($bundle['sms_content'] ?? '');
- $this->logIssueNotifyDebug('短信', [
- 'company' => $companyName,
- 'phone' => $phone,
- 'sms_content' => $smsContent,
- ]);
- if ($this->isProcuremenNotifyDryRun()) {
- $this->recordNotifyDryRunPreview([
- 'scene' => 'issue_sms',
- 'company_name' => $companyName,
- 'phone' => $phone,
- 'sms_content' => $smsContent,
- ]);
- return;
- }
- $this->smsbao($phone, $smsContent);
- }
- /**
- * 外发下发 — 发送邮件(一家供应商)
- *
- * @param array<string, mixed> $bundle
- * @param array<string, mixed> $mailConfig
- */
- protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
- {
- $companyName = (string)($bundle['company_name'] ?? '');
- $toEmail = (string)($bundle['email'] ?? '');
- $mailPlain = (string)($bundle['mail_plain'] ?? '');
- $mailBody = (string)($bundle['mail_body'] ?? '');
- $this->logIssueNotifyDebug('邮件', [
- 'company' => $companyName,
- 'email' => $toEmail,
- 'mail_subject' => $mailSubject,
- 'mail_body' => $mailPlain,
- ]);
- if ($this->isProcuremenNotifyDryRun()) {
- $this->recordNotifyDryRunPreview([
- 'scene' => 'issue_email',
- 'company_name' => $companyName,
- 'email' => $toEmail,
- 'mail_subject' => $mailSubject,
- 'mail_body' => $mailPlain,
- 'sms_content' => (string)($bundle['sms_content'] ?? ''),
- 'notify_vars' => $bundle['notify_vars'] ?? [],
- 'detail_links' => $bundle['detail_links'] ?? [],
- ]);
- return;
- }
- $mail = new PHPMailer(true);
- $mail->isSMTP();
- $mail->Host = $mailConfig['host'];
- $mail->SMTPAuth = true;
- $mail->Username = $mailConfig['addr'];
- $mail->Password = $mailConfig['pass'];
- $mail->SMTPSecure = $mailConfig['security'];
- $mail->Port = $mailConfig['port'];
- $mail->CharSet = $mailConfig['charset'];
- $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
- $mail->addAddress($toEmail, $companyName);
- $mail->isHTML(true);
- $mail->Subject = $mailSubject;
- $mail->Body = $mailBody;
- $mail->send();
- }
- /**
- * 外发下发通知上下文(订单号、工序明细等,供短信/邮件共用)
- *
- * @param array<int, array<string, mixed>> $mergeRows
- * @return array<string, mixed>
- */
- protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
- {
- $head = $mergeRows[0] ?? [];
- $isMerge = count($mergeRows) > 1;
- return [
- 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
- 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
- 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
- 'is_merge' => $isMerge,
- 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
- 'process_html' => $this->buildProcessLinesHtml($mergeRows),
- 'deadline' => $sysRqNotify,
- ];
- }
- /**
- * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
- *
- * @param array<string, mixed> $data
- */
- protected function logIssueNotifyDebug(string $type, array $data): void
- {
- if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
- return;
- }
- Log::write('[外发下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
- }
- /**
- * 外发下发弹窗(选多家供应商并通知)
- */
- public function pickReview()
- {
- if ($this->request->isPost()) {
- $this->error('请使用弹窗内「确认下发」提交');
- }
- $this->view->assign('pickMode', 1);
- return $this->view->fetch('procuremen/review');
- }
- /**
- * 外发新增(独立页面)
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post('row/a');
- if (!is_array($params)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- [, $adminName] = $this->GetUseName();
- $params['cywyxm'] = $adminName;
- try {
- $sid = $this->saveManualPickOrder($params);
- } catch (\InvalidArgumentException $e) {
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $this->success('新增成功', '', ['scydgy_id' => $sid]);
- }
- [, $adminName] = $this->GetUseName();
- $this->view->assign('adminNickname', $adminName);
- $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
- return $this->view->fetch();
- }
- /**
- * 业务员外发新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
- */
- public function rfqlist()
- {
- $this->relationSearch = false;
- $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $limit = max(10, min(500, (int)$limit));
- $applyFilters = function ($query) use ($where) {
- $query->where('scydgy_id', '<', 0);
- $query->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%\')'
- );
- if (!$this->auth->isSuperAdmin()) {
- [, $adminName] = $this->GetUseName();
- $query->where('cywyxm', $adminName);
- }
- if (!empty($where)) {
- $query->where($where);
- }
- };
- $countQuery = Db::table('purchase_order');
- $applyFilters($countQuery);
- $total = (int)$countQuery->count();
- $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
- $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
- $listQuery = Db::table('purchase_order');
- $applyFilters($listQuery);
- $rows = $listQuery
- ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
- ->order($sortField, $orderDir)
- ->limit($offset, $limit)
- ->select();
- if (!is_array($rows)) {
- $rows = [];
- }
- $out = [];
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if ($sid >= 0) {
- continue;
- }
- $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
- if ($createdText === '') {
- $createdText = trim((string)($r['dStamp'] ?? ''));
- }
- $out[] = [
- 'id' => (int)($r['id'] ?? 0),
- 'scydgy_id' => $sid,
- 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
- 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
- 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
- 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
- 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
- 'progress_text' => $this->formatProcuremenRfqProgressText($r),
- 'createtime' => $r['createtime'] ?? null,
- 'createtime_text' => $createdText,
- ];
- }
- return json(['total' => $total, 'rows' => $out]);
- }
- [, $adminName] = $this->GetUseName();
- $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
- $this->view->assign('adminNickname', $adminName);
- return $this->view->fetch('procuremen/rfqlist');
- }
- /**
- * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
- */
- public function rfqlistDetails()
- {
- return $this->details();
- }
- /**
- * 手工新增工序详情:业务员只看本人;超管及外发流程岗位可看全部
- */
- protected function assertManualOrderDetailsViewable(int $scydgyId): void
- {
- if ($scydgyId >= 0) {
- return;
- }
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (!is_array($po)) {
- $this->error('订单不存在');
- }
- $modRq = trim((string)($po['mod_rq'] ?? ''));
- if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
- $this->error('订单不存在');
- }
- if ($this->auth->isSuperAdmin()) {
- return;
- }
- [, $adminName] = $this->GetUseName();
- $cywy = trim((string)($po['cywyxm'] ?? ''));
- if ($cywy !== '' && $cywy === $adminName) {
- return;
- }
- foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
- try {
- if ($this->auth->check($rule)) {
- return;
- }
- } catch (\Throwable $e) {
- }
- }
- $this->error('无权查看该订单');
- }
- /**
- * @deprecated 使用 {@see assertManualOrderDetailsViewable}
- */
- protected function assertRfqRowViewable(int $scydgyId): void
- {
- $this->assertManualOrderDetailsViewable($scydgyId);
- }
- /**
- * 手工新增外发工序进度文案
- */
- protected function formatProcuremenRfqProgressText(array $row): string
- {
- $st = trim((string)($row['status'] ?? ''));
- // status=1 才表示主单已完结;status=0 为流程进行中(与详情 buildProcuremenDetailsViewData 一致)
- if ($st === '1') {
- return '已完结';
- }
- $wf = (int)($row['wflow_status'] ?? 0);
- if ($wf === 2) {
- return '待采购确认';
- }
- if ($wf === 1) {
- return '待确认供应商';
- }
- $sid = (int)($row['scydgy_id'] ?? 0);
- if ($sid < 0) {
- try {
- $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
- $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
- $detCnt = (int)$detCntQuery->count();
- if ($detCnt > 0) {
- return '已下发待确认';
- }
- } catch (\Throwable $e) {
- }
- }
- return '待外发下发';
- }
- /**
- * 外发初选列表 — 批量软删除
- */
- public function pickDelete()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $rowsRaw = $this->request->post('rows_json', '[]');
- $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
- if (!is_array($rows) || $rows === []) {
- $this->error('请至少勾选一条工序');
- }
- $done = 0;
- Db::startTrans();
- try {
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $this->softDeleteProcuremenPickRow($row);
- $done++;
- }
- if ($done < 1) {
- throw new \Exception('没有可删除的工序');
- }
- Db::commit();
- } catch (\InvalidArgumentException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('已删除 ' . $done . ' 条工序');
- }
- /**
- * 外发下发 — 手工新增工序(弹窗)
- */
- public function pickAdd()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post('row/a');
- if (!is_array($params)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- try {
- $sid = $this->saveManualPickOrder($params);
- } catch (\InvalidArgumentException $e) {
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $this->success('新增成功', '', ['scydgy_id' => $sid]);
- }
- return $this->view->fetch('procuremen/pick_add');
- }
- /**
- * 外发下发提交 — 弹窗「确认下发」→ POST procuremen/picksubmit
- */
- public function pickSubmit()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- // ---------- 接口订单数据 ----------
- $rowJson = $this->request->post('row_json', '');
- $mergeRowsJson = $this->request->post('merge_rows_json', '');
- $companiesJson = $this->request->post('companies_json', '[]');
- $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
- $companies = json_decode($companiesJson, true);
- if (!is_array($companies)) {
- $this->error('供应商数据无效');
- }
- $issueCompanies = $this->normalizePickCompanies($companies);
- if ($issueCompanies === []) {
- $this->error('请至少选择一家合作供应商');
- }
- $issueNameLabels = [];
- foreach ($issueCompanies as $pc) {
- $issueNameLabels[] = $pc['name'];
- }
- $issueNamesSummary = implode('、', $issueNameLabels);
- $sysRq = trim((string)$this->request->post('sys_rq', ''));
- if ($sysRq === '') {
- $this->error('请选择截止时间');
- }
- $sysRqTs = strtotime($sysRq);
- if ($sysRqTs === false || $sysRqTs <= 0) {
- $this->error('截止时间格式无效');
- }
- $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
- $isMerge = count($mergeRows) > 1;
- $logMsg = ($isMerge ? '合并外发初选(' . count($mergeRows) . ' 道工序)' : '外发初选')
- . ',通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
- $issueTime = date('Y-m-d H:i:s');
- $logSidList = [];
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($row);
- if ($this->isValidScydgyRowId($sid)) {
- $logSidList[$sid] = true;
- }
- }
- $existingBySid = [];
- if ($logSidList !== []) {
- try {
- $existingRows = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($logSidList))
- ->select();
- if (is_array($existingRows)) {
- foreach ($existingRows as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $existingBySid[$sid] = $poRow;
- }
- }
- }
- } catch (\Throwable $e) {
- $existingBySid = [];
- }
- }
- Db::startTrans();
- try {
- // ---------- 主表 wflow_status=1;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($row);
- $this->upsertPurchaseOrderFromRow(
- $row,
- $sysRqDb,
- 1,
- $issueTime,
- $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
- );
- }
- foreach ($issueCompanies as $c) {
- $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $poIdBySid = [];
- if ($logSidList !== []) {
- try {
- $poIdBySid = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($logSidList))
- ->column('id', 'scydgy_id');
- } catch (\Throwable $e) {
- $poIdBySid = [];
- }
- }
- // ---------- 操作日志记录(批量写入,减少提交等待) ----------
- if ($logSidList !== []) {
- list($adminId, $adminName) = $this->GetUseName();
- $cut = function ($s, $max) {
- if (function_exists('mb_substr')) {
- return mb_substr($s, 0, $max, 'UTF-8');
- }
- return strlen($s) <= $max ? $s : substr($s, 0, $max);
- };
- $logRows = [];
- $seenLogSid = [];
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
- continue;
- }
- $seenLogSid[$ids] = true;
- $poIdLog = null;
- if (isset($poIdBySid[$ids])) {
- $tid = (int)$poIdBySid[$ids];
- $poIdLog = $tid > 0 ? $tid : null;
- }
- $logRows[] = [
- 'scydgy_id' => $ids,
- 'purchase_order_id' => $poIdLog,
- 'admin_id' => $adminId,
- 'admin_name' => $cut($adminName, 64),
- 'action' => $cut('issue_submit', 64),
- 'content' => $cut($logMsg, 1000),
- 'createtime' => time(),
- ];
- }
- if ($logRows !== []) {
- try {
- Db::table('purchase_order_oper_log')->insertAll($logRows);
- } catch (\Throwable $e) {
- Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
- }
- }
- }
- $notifyErrors = [];
- $posNotify = [];
- if ($logSidList !== []) {
- try {
- $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
- } catch (\Throwable $e) {
- $posNotify = [];
- }
- }
- if (!is_array($posNotify)) {
- $posNotify = [];
- }
- foreach ($posNotify as $i => $prow) {
- if (is_array($posNotify[$i])) {
- $posNotify[$i]['sys_rq'] = $sysRqDb;
- }
- }
- $ccydhPick = '';
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
- if ($ccydhPick !== '') {
- break;
- }
- }
- $notifyBundleBase = [
- 'ccydh' => $ccydhPick,
- 'pos' => $posNotify,
- 'merge_rows' => $mergeRows,
- ];
- try {
- $this->notifyDryRunPreview = [];
- foreach ($issueCompanies as $c) {
- if (!is_array($c)) {
- continue;
- }
- $cname = trim((string)($c['name'] ?? ''));
- if ($cname === '') {
- continue;
- }
- try {
- $this->sendAuditSupplierConfirmNotify($c, $mergeRows, $notifyBundleBase);
- } catch (\Throwable $e) {
- $notifyErrors[] = $cname . ':' . $e->getMessage();
- }
- }
- } catch (\Throwable $e) {
- $this->error('通知发送失败:' . $e->getMessage());
- }
- if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
- $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
- }
- if ($this->isProcuremenNotifyDryRun()) {
- $this->success('【演练模式】已保存并生成通知预览', '', [
- 'notify_dry_run' => true,
- 'notify_preview' => $this->notifyDryRunPreview,
- ]);
- }
- $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「外发审批下发」确认供应商');
- }
- /**
- * 确认供应商弹窗
- */
- public function auditIssue()
- {
- $ids = $this->request->param('ids', $this->request->param('id', ''));
- if (is_array($ids)) {
- $ids = isset($ids[0]) ? $ids[0] : '';
- }
- $ids = trim((string)$ids);
- if ($ids === '') {
- $this->error(__('Invalid parameters'));
- }
- if ($this->request->isPost()) {
- $this->error('请使用弹窗内「确认」提交');
- }
- $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
- $pos = $bundle['pos'];
- if ($pos === []) {
- $this->error('该订单不在待确认供应商状态');
- }
- $po = $pos[0];
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无下发明细,请确认该订单已在「外发初选」完成下发');
- }
- $pickedName = '';
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $pn = trim((string)($poRow['pick_company_name'] ?? ''));
- if ($pn !== '') {
- $pickedName = $pn;
- break;
- }
- }
- $this->view->assign('po', $po);
- $this->view->assign('scydgyId', $ids);
- $this->view->assign('orderCcydh', $bundle['ccydh']);
- $mergeRows = $bundle['merge_rows'];
- $this->view->assign('processRows', $mergeRows);
- $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
- $this->view->assign('processCount', count($mergeRows));
- $this->view->assign('quoteGroups', $quoteGroups);
- $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
- $this->view->assign('pickedCompanyName', $pickedName);
- $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
- return $this->view->fetch('procuremen/audit_issue');
- }
- /**
- * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
- */
- public function auditSubmit()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- if ($scydgyId === '') {
- $this->error('参数无效');
- }
- $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
- $pos = $bundle['pos'];
- $mergeRows = $bundle['merge_rows'];
- if ($pos === [] || $mergeRows === []) {
- $this->error('该订单不在待确认供应商状态');
- }
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无供应商报价,请确认已完成外发初选通知');
- }
- $companyName = trim((string)$this->request->post('selected_company', ''));
- if ($companyName === '') {
- $this->error('请选择一家供应商');
- }
- $matched = null;
- foreach ($quoteGroups as $g) {
- if (!is_array($g)) {
- continue;
- }
- if (trim((string)($g['name'] ?? '')) === $companyName) {
- $matched = $g;
- break;
- }
- }
- if ($matched === null) {
- $this->error('所选供应商不在本单报价列表中');
- }
- $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
- $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
- $procCnt = count($mergeRows);
- $logMsg = '确认供应商(订单' . ($ccydhLog !== '' ? $ccydhLog : '')
- . ($procCnt > 1 ? ',' . $procCnt . ' 道工序' : '')
- . '),选定:' . $companyName;
- Db::startTrans();
- try {
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- Db::table('purchase_order')->where('scydgy_id', $sid)->update([
- 'wflow_status' => 2,
- 'status' => 0,
- 'pick_company_name' => $companyName,
- 'sys_rq' => $sysRqDb,
- ]);
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
- $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
- }
- $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
- }
- /**
- * 确认供应商 — 二次发送短信(可选单家/批量/全部)
- */
- public function auditResendSms()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- if ($scydgyId === '') {
- $this->error('参数无效');
- }
- $loaded = $this->loadAuditResendBundle($scydgyId);
- $mergeRows = $loaded['merge_rows'];
- $bundle = $loaded['bundle'];
- $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无可通知的供应商');
- }
- $selectedCompany = trim((string)$this->request->post('selected_company', ''));
- $companiesJson = (string)$this->request->post('companies_json', '');
- $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
- $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
- }
- /**
- * 确认供应商 — 二次发送邮件(可选单家/批量)
- */
- public function auditResendEmail()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- if ($scydgyId === '') {
- $this->error('参数无效');
- }
- $loaded = $this->loadAuditResendBundle($scydgyId);
- $mergeRows = $loaded['merge_rows'];
- $bundle = $loaded['bundle'];
- $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无可通知的供应商');
- }
- $companiesJson = (string)$this->request->post('companies_json', '');
- $selectedCompany = trim((string)$this->request->post('selected_company', ''));
- $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
- if ($companiesJson === '' && $selectedCompany === '') {
- $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
- }
- $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
- }
- /**
- * 废弃单个订单 bundle(退回外发初选,明细归档留痕)
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, true> 已处理的 scydgy_id 集合
- */
- protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回外发初选'): array
- {
- $pos = $bundle['pos'] ?? [];
- if (!is_array($pos) || $pos === []) {
- return [];
- }
- $sids = [];
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- }
- }
- if ($sids === []) {
- return [];
- }
- $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
- $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '') . $logSuffix;
- Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->update([
- 'wflow_status' => 0,
- 'status' => 0,
- 'pick_company_name' => '',
- 'pick_time' => null,
- 'sys_rq' => null,
- 'mod_rq' => null,
- ]);
- $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
- foreach (array_keys($sids) as $sid) {
- $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
- }
- return $sids;
- }
- /**
- * 废弃单个审批订单 bundle(退回外发初选,明细归档留痕)
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, true> 已处理的 scydgy_id 集合
- */
- protected function abandonAuditOrderBundle(array $bundle): array
- {
- return $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
- }
- /**
- * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
- *
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- if ($scydgyId === '') {
- return $empty;
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
- return $empty;
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- if ($ccydh === '') {
- return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
- }
- try {
- $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
- $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
- $pos = $query->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- protected function purchaseOrderRowIsCompleted(array $po): bool
- {
- $st = $po['status'] ?? null;
- if ($st === 1 || $st === '1') {
- return true;
- }
- if (is_string($st) && trim($st) === '1') {
- return true;
- }
- return is_numeric($st) && (int)$st === 1;
- }
- /**
- * 废弃订单 — 退回外发初选重新询价(支持单条或批量)
- */
- public function auditAbandon()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $anchorIds = [];
- $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
- if ($batchRaw !== '') {
- $decoded = json_decode($batchRaw, true);
- if (is_array($decoded)) {
- foreach ($decoded as $id) {
- $s = trim((string)$id);
- if ($s !== '') {
- $anchorIds[] = $s;
- }
- }
- }
- }
- if ($anchorIds === []) {
- $single = trim((string)$this->request->post('scydgy_id', ''));
- if ($single !== '') {
- $anchorIds[] = $single;
- }
- }
- if ($anchorIds === []) {
- $this->error('请至少选择一条订单');
- }
- $processedCcydh = [];
- $doneOrders = 0;
- $allSids = [];
- Db::startTrans();
- try {
- foreach ($anchorIds as $anchorId) {
- $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
- if (($bundle['pos'] ?? []) === []) {
- continue;
- }
- $ccydh = trim((string)($bundle['ccydh'] ?? ''));
- $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
- if (isset($processedCcydh[$dedupeKey])) {
- continue;
- }
- $processedCcydh[$dedupeKey] = true;
- $sids = $this->abandonAuditOrderBundle($bundle);
- if ($sids === []) {
- continue;
- }
- $doneOrders++;
- foreach (array_keys($sids) as $sid) {
- $allSids[(int)$sid] = true;
- }
- }
- if ($doneOrders < 1) {
- throw new \Exception('所选订单均不在待确认供应商状态');
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->pickHiddenScydgySetCache = null;
- $msg = $doneOrders > 1
- ? ('已重新下发 ' . $doneOrders . ' 个订单并退回外发初选,历史下发与操作记录已保留')
- : '已退回外发初选,请重新选择供应商下发(历史记录已保留)';
- $this->success($msg);
- }
- /**
- * 历史存证 — 已完结订单重新下发,退回外发初选(支持单条或批量)
- */
- public function archiveAbandon()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $anchorIds = [];
- $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
- if ($batchRaw !== '') {
- $decoded = json_decode($batchRaw, true);
- if (is_array($decoded)) {
- foreach ($decoded as $id) {
- $s = trim((string)$id);
- if ($s !== '') {
- $anchorIds[] = $s;
- }
- }
- }
- }
- if ($anchorIds === []) {
- $single = trim((string)$this->request->post('scydgy_id', ''));
- if ($single !== '') {
- $anchorIds[] = $single;
- }
- }
- if ($anchorIds === []) {
- $this->error('请至少选择一条订单');
- }
- $processedCcydh = [];
- $doneOrders = 0;
- Db::startTrans();
- try {
- foreach ($anchorIds as $anchorId) {
- $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
- if (($bundle['pos'] ?? []) === []) {
- continue;
- }
- $ccydh = trim((string)($bundle['ccydh'] ?? ''));
- $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
- if (isset($processedCcydh[$dedupeKey])) {
- continue;
- }
- $processedCcydh[$dedupeKey] = true;
- $sids = $this->abandonOrderBundleToPick(
- $bundle,
- 'archive_abandon',
- ',从历史存证退回外发初选'
- );
- if ($sids === []) {
- continue;
- }
- $doneOrders++;
- }
- if ($doneOrders < 1) {
- throw new \Exception('所选订单均不是已完结状态');
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->pickHiddenScydgySetCache = null;
- $msg = $doneOrders > 1
- ? ('已重新下发 ' . $doneOrders . ' 个订单并退回外发初选,历史记录已保留')
- : '已退回外发初选,请重新选择供应商下发(历史记录已保留)';
- $this->success($msg);
- }
- /**
- * 采购终审 — 审批驳回(退回外发审批下发,不发送短信)
- */
- public function purchaseApprovalReject()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
- $decoded = json_decode($batchRaw, true);
- if (!is_array($decoded) || $decoded === []) {
- $this->error('提交数据无效');
- }
- Db::startTrans();
- try {
- foreach ($decoded as $item) {
- if (!is_array($item)) {
- continue;
- }
- $sid = (int)($item['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $this->runPurchaseApprovalRejectForSid($sid);
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
- }
- $this->success('已驳回并退回「外发审批下发」');
- }
- /**
- * @throws \Exception
- */
- protected function runPurchaseApprovalRejectForSid(int $sid): void
- {
- $allIds = $this->purchaseOrderDetail($sid);
- if ($allIds === []) {
- throw new \Exception('未找到下发明细');
- }
- Db::table('purchase_order')->where('scydgy_id', $sid)->update([
- 'wflow_status' => 1,
- 'status' => 0,
- 'pick_company_name' => '',
- ]);
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
- $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
- $poId = 0;
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($po)) {
- $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- } catch (\Throwable $e) {
- }
- $this->addOrderLog($sid, 'purchase_reject', '采购终审驳回,退回外发审批下发', $poId > 0 ? $poId : null);
- }
- /**
- * 审核弹窗(旧入口,POST 已关闭)
- */
- public function review()
- {
- if ($this->request->isPost()) {
- $this->error('请使用第一步「外发下发」通知供应商,再在「确认供应商」中选定一家');
- }
- $this->view->assign('pickMode', 0);
- return $this->view->fetch('procuremen/review');
- }
- /**
- * 审核弹窗获取公司列表
- */
- public function reviewCompanies()
- {
- if (!$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $list = [];
- try {
- // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
- $rows = Db::table('customer')
- ->where(function ($q) {
- $q->where('status', 1)
- ->whereOr('status', '1')
- ->whereOr('status', '')
- ->whereNull('status');
- })
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e) {
- $this->success('', '', []);
- return;
- }
- if (!is_array($rows)) {
- $this->success('', '', []);
- return;
- }
- $detailColCandidates = [
- 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
- 'company_detail', 'company_desc', 'address',
- ];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $norm = [];
- foreach ($row as $k => $v) {
- $norm[is_string($k) ? strtolower($k) : $k] = $v;
- }
- $row = $norm;
- $st = $row['status'] ?? '';
- if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
- continue;
- }
- $id = isset($row['id']) ? (string)$row['id'] : '';
- $companyName = '';
- foreach (['company_name', 'name'] as $nk) {
- if (!empty($row[$nk])) {
- $companyName = trim((string)$row[$nk]);
- break;
- }
- }
- $username = '';
- foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
- if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
- $username = trim((string)$row[$uk]);
- break;
- }
- }
- $email = isset($row['email']) ? trim((string)$row['email']) : '';
- $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
- if ($phone === '' && isset($row['account'])) {
- $phone = trim((string)$row['account']);
- }
- if ($phone === '' && isset($row['mobile'])) {
- $phone = trim((string)$row['mobile']);
- }
- /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
- if ($email === '' && $phone === '') {
- continue;
- }
- $category = '';
- foreach (['company_type', 'category', 'type_name'] as $ck) {
- if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
- $category = trim((string)$row[$ck]);
- break;
- }
- }
- $detail = '';
- foreach ($detailColCandidates as $dk) {
- if (!isset($row[$dk])) {
- continue;
- }
- $dv = trim((string)$row[$dk]);
- if ($dv !== '') {
- $detail = $dv;
- break;
- }
- }
- $list[] = [
- 'id' => $id,
- 'name' => $companyName,
- 'company_name' => $companyName,
- 'username' => $username,
- 'email' => $email,
- 'phone' => $phone,
- 'category' => $category,
- 'company_type' => $category,
- 'detail' => $detail,
- ];
- }
- $this->success('', '', $list);
- }
- /**
- * 采购确认-下发明细弹窗:
- * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
- */
- public function outward_detail()
- {
- $ids = $this->request->param('ids', $this->request->param('id', ''));
- if (is_array($ids)) {
- $ids = isset($ids[0]) ? $ids[0] : '';
- }
- $ids = trim((string)$ids);
- if ($ids === '') {
- $this->error(__('Invalid parameters'));
- }
- $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
- if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
- $wffTab = 'all';
- }
- $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
- $purchaseOrderId = 0;
- $po = null;
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- if (is_array($po)) {
- $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- } catch (\Throwable $e) {
- $purchaseOrderId = 0;
- $po = null;
- }
- if (!$isPurchaseConfirm && is_array($po)) {
- $wf = (int)($po['wflow_status'] ?? 0);
- $st = trim((string)($po['status'] ?? ''));
- $isDone = ($st === '1' || $st === 1);
- if ($wf === 2 && !$isDone) {
- $isPurchaseConfirm = true;
- }
- }
- $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
- $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- $confirmProcessCount = 1;
- $confirmPickGroups = [];
- $processDisplayRows = [];
- $allDetailsBySid = [];
- $requiredSidList = [];
- $sidList = [$ids];
- if ($isPurchaseConfirm) {
- $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
- $mergeRows = $confirmBundle['merge_rows'] ?? [];
- if ($mergeRows !== []) {
- $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
- }
- $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
- if ($confirmBundle['pos'] !== []) {
- $sidList = [];
- foreach ($confirmBundle['pos'] as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $sidList[] = (string)$sid;
- $requiredSidList[] = $sid;
- }
- }
- if ($sidList === []) {
- $sidList = [$ids];
- $requiredSidList = [(int)$ids];
- }
- $confirmProcessCount = max(1, count($requiredSidList));
- if (is_array($po) && $purchaseOrderId <= 0) {
- $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- }
- $rows = [];
- try {
- if (count($sidList) === 1) {
- $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
- } else {
- $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
- }
- } catch (\Throwable $e) {
- $rows = [];
- }
- if ($isPurchaseConfirm) {
- $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
- }
- foreach ($rows as &$r) {
- if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
- $r['id'] = $r['ID'];
- }
- if (isset($r['createtime'])) {
- if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
- $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
- } else {
- $r['createtime_text'] = (string)$r['createtime'];
- }
- } else {
- $r['createtime_text'] = '';
- }
- }
- unset($r);
- $pickedCompanyName = '';
- if ($isPurchaseConfirm) {
- foreach ($confirmBundle['pos'] ?? [] as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $pn = trim((string)($poRow['pick_company_name'] ?? ''));
- if ($pn !== '') {
- $pickedCompanyName = $pn;
- break;
- }
- }
- }
- $this->view->assign('rows', $rows ?: []);
- $this->view->assign('rowCount', count($rows ?: []));
- $this->view->assign('scydgyId', $ids);
- $this->view->assign('purchaseOrderId', $purchaseOrderId);
- $this->view->assign('headTitle', $headTitle);
- $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
- $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
- $this->view->assign('confirmProcessCount', $confirmProcessCount);
- $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
- $this->view->assign('processDisplayRows', $processDisplayRows);
- $this->view->assign('confirmPickGroups', $confirmPickGroups);
- $this->view->assign('confirmPickCount', count($confirmPickGroups));
- $this->view->assign('pickedCompanyName', $pickedCompanyName);
- $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
- $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
- /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
- if ($isPurchaseConfirm) {
- return $this->view->fetch();
- }
- $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
- $this->view->engine->layout(false);
- try {
- $bodyHtml = $this->view->fetch('procuremen/outward_detail');
- $this->view->assign('dialogBody', $bodyHtml);
- return $this->view->fetch('procuremen/outward_detail_lite_shell');
- } finally {
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- }
- }
- /**
- * 月度导出记录表(不存在时自动创建)
- */
- protected function ensurePurchaseMonthExportLogTable(): void
- {
- try {
- Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
- } catch (\Throwable $e) {
- Db::execute(
- "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
- `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
- `admin_name` varchar(64) NOT NULL DEFAULT '',
- `row_count` int(10) unsigned NOT NULL DEFAULT 0,
- `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
- `createtime` int(10) unsigned DEFAULT NULL,
- PRIMARY KEY (`id`),
- KEY `idx_ym` (`ym`),
- KEY `idx_ct` (`createtime`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度外发明细导出记录'"
- );
- }
- }
- /**
- * 按月份导出:已完结且采购确认已选定供应商(明细 status=1),与列表「已完结」∩「已选中」一致。
- * 表头固定 8 列(与历史「外发明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
- */
- public function export_month_outward()
- {
- $this->request->filter(['strip_tags', 'trim']);
- $ym = trim((string)$this->request->get('ym', date('Y-m')));
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $ym = date('Y-m');
- }
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- $dbRows = [];
- try {
- $query = Db::table('purchase_order');
- $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
- $dbRows = $query->select();
- } catch (\Throwable $e) {
- $dbRows = [];
- }
- if (!is_array($dbRows)) {
- $dbRows = [];
- }
- $pickedSidSet = $this->loadScydgyIdsWithPickedSupplierDetail();
- $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($pickedSidSet) {
- if (!is_array($dbRow)) {
- return false;
- }
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- if ($sid <= 0 && isset($dbRow['SCYDGY_ID'])) {
- $sid = (int)$dbRow['SCYDGY_ID'];
- }
- return $sid > 0 && isset($pickedSidSet[$sid]);
- }));
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
- $filtered = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], 'pick_time');
- $mainBySid = [];
- foreach ($filtered as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($rid > 0) {
- $mainBySid[$rid] = $rw;
- }
- }
- if ($mainBySid === []) {
- $detailRows = [];
- } else {
- try {
- $detailRows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($mainBySid))
- ->where('status', 1)
- ->order('CCYDH', 'asc')
- ->order('company_name', 'asc')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $detailRows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($mainBySid))
- ->where('status', 1)
- ->order('CCYDH', 'asc')
- ->order('company_name', 'asc')
- ->order('ID', 'asc')
- ->select();
- } catch (\Throwable $e2) {
- $detailRows = [];
- }
- }
- }
- if (!is_array($detailRows)) {
- $detailRows = [];
- }
- $exportLines = [];
- foreach ($detailRows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
- if ($sid <= 0 || !isset($mainBySid[$sid])) {
- continue;
- }
- $m = $mainBySid[$sid];
- $exportLines[] = [
- 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
- 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
- 'company_name' => (string)($dr['company_name'] ?? ''),
- 'CDF' => (string)($m['CDF'] ?? ''),
- 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
- 'gx' => $this->procuremenExportGxText($m),
- 'detail' => $dr,
- ];
- }
- $groups = [];
- foreach ($exportLines as $line) {
- $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
- if (!isset($groups[$k])) {
- $groups[$k] = [];
- }
- $groups[$k][] = $line;
- }
- ksort($groups, SORT_STRING);
- $spreadsheet = new Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
- $sheet->setTitle('外发明细');
- $mon = (int)substr($ym, 5, 2);
- $sheet->mergeCells('A1:H1');
- $sheet->setCellValue('A1', $mon . '月外发明细');
- $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
- $sheet->getStyle('A1')->getAlignment()
- ->setHorizontal(Alignment::HORIZONTAL_CENTER)
- ->setVertical(Alignment::VERTICAL_CENTER);
- $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
- $col = 'A';
- foreach ($headers as $h) {
- $sheet->setCellValue($col . '2', $h);
- $col++;
- }
- $sheet->getStyle('A2:H2')->getFont()->setBold(true);
- $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $rowNum = 3;
- $sumSubtotalCounts = 0;
- $grandAmount = 0.0;
- if ($groups === []) {
- $sheet->mergeCells('A3:H3');
- $sheet->setCellValue('A3', '(当月暂无符合条件的外发明细)');
- $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $rowNum = 4;
- } else {
- foreach ($groups as $items) {
- if ($items === []) {
- continue;
- }
- $groupLineCount = count($items);
- $subAmount = 0.0;
- $i = 0;
- foreach ($items as $line) {
- $i++;
- $dr = $line['detail'];
- $amt = $this->procuremenExportAmount($dr);
- $subAmount += $amt;
- $sheet->setCellValue('A' . $rowNum, $i);
- $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
- $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
- $sheet->setCellValue('D' . $rowNum, $line['company_name']);
- $sheet->setCellValue('E' . $rowNum, $line['CDF']);
- $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
- $sheet->setCellValue('G' . $rowNum, $line['gx']);
- $sheet->setCellValue('H' . $rowNum, $amt);
- $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
- $rowNum++;
- }
- $sumSubtotalCounts += $groupLineCount;
- $grandAmount += $subAmount;
- $sheet->setCellValue('A' . $rowNum, $groupLineCount);
- $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
- $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
- $sheet->getStyle('G' . $rowNum)->getAlignment()
- ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
- ->setVertical(Alignment::VERTICAL_CENTER);
- $rowNum++;
- }
- }
- $sheet->setCellValue('A' . $rowNum, '总计');
- $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
- $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
- $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
- $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
- $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
- $lastRow = $rowNum;
- $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
- 'borders' => [
- 'allBorders' => [
- 'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
- ],
- ],
- ]);
- $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
- if ($lastRow >= 3) {
- $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- }
- $sheet->getColumnDimension('A')->setWidth(7);
- $sheet->getColumnDimension('B')->setWidth(16);
- $sheet->getColumnDimension('C')->setWidth(52);
- $sheet->getColumnDimension('D')->setWidth(32);
- $sheet->getColumnDimension('E')->setWidth(12);
- $sheet->getColumnDimension('F')->setWidth(44);
- $sheet->getColumnDimension('G')->setWidth(26);
- $sheet->getColumnDimension('H')->setWidth(13);
- $sheet->getRowDimension(1)->setRowHeight(28);
- $fileBase = '外发明细_' . str_replace('-', '', $ym);
- $filename = $fileBase . '.xlsx';
- try {
- $this->ensurePurchaseMonthExportLogTable();
- list($adminId, $adminName) = $this->GetUseName();
- Db::table('purchase_month_export_log')->insert([
- 'ym' => $ym,
- 'admin_id' => (int)$adminId,
- 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
- 'row_count' => count($exportLines),
- 'total_amount' => round($grandAmount, 2),
- 'createtime' => time(),
- ]);
- } catch (\Throwable $e) {
- Log::write('month export log: ' . $e->getMessage(), 'error');
- }
- if (ob_get_length()) {
- ob_end_clean();
- }
- $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
- header('Cache-Control: max-age=0');
- $writer = new Xlsx($spreadsheet);
- $writer->save('php://output');
- $spreadsheet->disconnectWorksheets();
- unset($spreadsheet);
- exit;
- }
- /**
- * 导出用:工序列文案
- */
- protected function procuremenExportGxText(array $r)
- {
- $a = trim((string)($r['CDXMC'] ?? ''));
- $b = trim((string)($r['CGYMC'] ?? ''));
- if ($a !== '' && $b !== '') {
- return $a . ':' . $b;
- }
- return $a !== '' ? $a : $b;
- }
- /**
- * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
- */
- protected function procuremenExportAmount(array $r)
- {
- foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
- if (!array_key_exists($k, $r)) {
- continue;
- }
- $v = $r[$k];
- if ($v === null || $v === '') {
- continue;
- }
- if (is_numeric($v)) {
- return (float)$v;
- }
- $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
- if ($v !== '' && is_numeric($v)) {
- return (float)$v;
- }
- }
- return 0.0;
- }
- /**
- * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
- */
- protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
- {
- $s = trim($ccydh);
- if ($s === '') {
- return 'ORDER';
- }
- $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
- $s = trim($s, '._-');
- if ($s === '') {
- return 'ORDER';
- }
- if (function_exists('mb_substr')) {
- return mb_substr($s, 0, 80, 'UTF-8');
- }
- return strlen($s) <= 80 ? $s : substr($s, 0, 80);
- }
- /**
- * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
- * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
- *
- * @return array{objectKey: string, webPath: string}
- */
- protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
- {
- $sid = (int)$scydgyId;
- $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
- $y = date('Y');
- $m = date('m');
- $d = date('d');
- $basename = $safeOrder . '_' . $sid . '.pdf';
- $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
- return [
- 'objectKey' => $objectKey,
- 'webPath' => '/' . $objectKey,
- ];
- }
- /**
- * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
- * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
- * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
- *
- * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
- */
- protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
- {
- if (!$this->isValidScydgyRowId($scydgyId)) {
- return '';
- }
- $ids = trim((string)$scydgyId);
- $prep = $this->prepareProcuremenDetailsView($ids);
- if (!$prep['ok']) {
- return '';
- }
- $ccydh = $prep['ccydh'];
- $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
- $objectKey = $paths['objectKey'];
- $webPath = $paths['webPath'];
- $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
- $this->view->assign([
- 'pdf_export' => 1,
- 'pdfMetaLine' => $meta,
- ]);
- // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
- $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
- $this->view->engine->layout(false);
- try {
- $html = $this->view->fetch('procuremen/details_pdf_shell');
- } catch (\Throwable $e) {
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
- $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
- return '';
- }
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
- $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
- if (!is_dir($tempDir)) {
- @mkdir($tempDir, 0755, true);
- }
- $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
- try {
- $mpdf = new \Mpdf\Mpdf([
- 'mode' => 'utf-8',
- 'format' => 'A4',
- 'margin_left' => 12,
- 'margin_right' => 12,
- 'margin_top' => 14,
- 'margin_bottom' => 14,
- 'tempDir' => $tempDir,
- 'autoScriptToLang' => true,
- 'autoLangToFont' => true,
- ]);
- // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
- // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
- $mpdf->SetBasePath('http://127.0.0.1/');
- $mpdf->WriteHTML($html);
- $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
- } catch (\Throwable $e) {
- Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
- if (is_file($tempPdf)) {
- @unlink($tempPdf);
- }
- return '';
- }
- $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
- if ($ossUrl !== '') {
- @unlink($tempPdf);
- $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
- return $ossUrl;
- }
- $pi = pathinfo($objectKey);
- $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
- $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
- if ($baseFile === '') {
- @unlink($tempPdf);
- return '';
- }
- $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
- if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
- Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
- @unlink($tempPdf);
- return '';
- }
- $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
- if (!@copy($tempPdf, $fullPath)) {
- Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
- @unlink($tempPdf);
- return '';
- }
- @unlink($tempPdf);
- $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
- return $webPath;
- }
- /**
- * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
- */
- protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
- {
- if ($scydgyId <= 0 || $webPath === '') {
- return;
- }
- try {
- Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
- } catch (\Throwable $e) {
- Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
- }
- }
- /**
- * 整理短信变量:去空格;联系人姓名为空时用公司名称
- *
- * @param array<string, string> $vars
- * @return array<string, string>
- */
- protected function normalizeSmsTemplateVars(array $vars): array
- {
- $out = [];
- foreach ($vars as $k => $v) {
- $out[(string)$k] = trim((string)$v);
- }
- if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
- $out['contact_name'] = $out['company_name'];
- }
- return $out;
- }
- /**
- * 按手机号或公司名称查 customer 表联系人姓名
- */
- protected function resolveCustomerContactName(string $phone, string $companyName): string
- {
- $phone = trim($phone);
- $companyName = trim($companyName);
- try {
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- $row = Db::table('customer')
- ->where(function ($q) use ($phone) {
- $q->where('phone', $phone)->whereOr('account', $phone);
- })
- ->order('id', 'asc')
- ->find();
- if (is_array($row)) {
- $nm = trim((string)($row['username'] ?? ''));
- if ($nm !== '') {
- return $nm;
- }
- }
- }
- if ($companyName !== '') {
- $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
- if (is_array($row)) {
- return trim((string)($row['username'] ?? ''));
- }
- }
- } catch (\Throwable $e) {
- }
- return '';
- }
- /**
- * 模版纯文本转邮件 HTML:换行转 <br>,保留已替换进的 <a> 等标签
- */
- protected function plainTextToHtmlEmailBody(string $text): string
- {
- $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
- $parts = explode("\n", $text);
- $out = [];
- foreach ($parts as $line) {
- if (preg_match('/<a\s+[^>]*href=/i', $line)) {
- $out[] = $line;
- } else {
- $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
- }
- }
- return implode("<br>\n", $out);
- }
- /**
- * 短信场景:去掉链接类变量,避免误填 URL
- *
- * @param array<string, string> $vars
- * @return array<string, string>
- */
- protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
- {
- if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
- return $vars;
- }
- foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
- $vars[$k] = '';
- }
- return $vars;
- }
- /**
- * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
- *
- * @param array<string, string> $vars
- */
- protected function renderNotifyTemplate(string $scene, array $vars): string
- {
- $vars = $this->normalizeSmsTemplateVars($vars);
- $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
- $row = $this->loadNotifyTemplateRow($scene);
- if ($row === null) {
- throw new \Exception($this->notifyTemplateMissingMessage($scene));
- }
- $tpl = trim((string)($row['content'] ?? ''));
- if ($tpl === '') {
- throw new \Exception($this->notifyTemplateMissingMessage($scene));
- }
- foreach ($vars as $k => $v) {
- $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
- }
- // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
- $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
- return $tpl;
- }
- protected function resolveProcuremenEmailSubject(string $scene): string
- {
- $map = [
- 'review_email' => '您有新的外发加工订单',
- ];
- $subject = trim((string)($map[$scene] ?? ''));
- if ($subject === '') {
- $this->error('未配置邮件主题:' . $scene);
- }
- return $subject;
- }
- protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
- {
- $map = [
- 'review_email' => '外发下发-邮箱',
- 'review_sms' => '外发下发-短信',
- 'confirm_ok' => '采购确认-通过',
- 'confirm_fail' => '采购确认-未通过',
- ];
- $label = $map[$scene] ?? $scene;
- if ($titleRequired) {
- return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
- }
- return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
- }
- /** @deprecated 使用 renderNotifyTemplate */
- protected function renderSmsTemplate(string $scene, array $vars): string
- {
- return $this->renderNotifyTemplate($scene, $vars);
- }
- /**
- * 是否开启外发通知演练(不发真实短信/邮件)
- */
- protected function isProcuremenNotifyDryRun(): bool
- {
- return (bool)Config::get('procuremen_notify_dry_run');
- }
- /**
- * @param array<string, mixed> $payload
- */
- protected function recordNotifyDryRunPreview(array $payload): void
- {
- $this->notifyDryRunPreview[] = $payload;
- Log::write('[外发通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
- }
- /**
- * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
- * @throws \Exception
- */
- protected function smsbao($phone, $content)
- {
- if ($this->isProcuremenNotifyDryRun()) {
- $this->recordNotifyDryRunPreview([
- 'scene' => 'sms_only',
- 'phone' => $phone,
- 'sms_content' => $content,
- ]);
- return;
- }
- $statusStr = [
- '0' => '短信发送成功',
- '-1' => '参数不全',
- '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
- '30' => '密码错误',
- '40' => '账号不存在',
- '41' => '余额不足',
- '42' => '帐户已过期',
- '43' => 'IP地址限制',
- '50' => '内容含有敏感词',
- ];
- $smsapi = 'http://api.smsbao.com/';
- $user = 'zhuwei123';
- $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
- $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
- $result = @file_get_contents($sendurl);
- if ($result === false) {
- \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
- throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
- }
- $result = trim((string)$result);
- if ($result !== '0') {
- $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
- \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
- throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
- }
- }
- }
|