Procuremen.php 222 KB

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