Index.php 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742
  1. <?php
  2. namespace app\index\controller;
  3. use app\common\controller\Frontend;
  4. use app\common\library\ProcuremenSchema;
  5. use app\common\library\ProcuremenStatus;
  6. use think\Cache;
  7. use think\captcha\Captcha;
  8. use think\Config;
  9. use think\Cookie;
  10. use think\Db;
  11. use think\Log;
  12. use think\Session;
  13. use think\Validate;
  14. /**
  15. * 手机端:协助明细(purchase_order_detail)验证码 / 账号密码登录 + 列表
  16. * 普通用户(customer):登录后进报价列表,可填单价/交期
  17. * 质检中心:登录后进「质量评分」(合格/投诉/中断)
  18. * 生产部(生产员):登录后进「交货情况」(准时/滞后)
  19. * 业务员:登录后进「新增订单询价」
  20. */
  21. class Index extends Frontend
  22. {
  23. protected $noNeedLogin = ['*'];
  24. protected $noNeedRight = ['*'];
  25. protected $layout = '';
  26. /** @var int 登录态有效天数 */
  27. protected $mprocTtlSeconds = 0;
  28. /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
  29. protected static $mprocProcuremenColumns = null;
  30. public function _initialize()
  31. {
  32. parent::_initialize();
  33. if (is_file(APP_PATH . 'extra/mproc.php')) {
  34. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  35. }
  36. $hours = (int)Config::get('mproc.session_hours');
  37. if ($hours > 0) {
  38. $this->mprocTtlSeconds = max(1, min(720, $hours)) * 3600;
  39. } else {
  40. $days = (int)(Config::get('mproc.session_days') ?: 3);
  41. $days = max(1, min(30, $days));
  42. $this->mprocTtlSeconds = $days * 86400;
  43. }
  44. if (PHP_VERSION_ID >= 70300) {
  45. ini_set('session.cookie_lifetime', (string)$this->mprocTtlSeconds);
  46. ini_set('session.gc_maxlifetime', (string)$this->mprocTtlSeconds);
  47. }
  48. try {
  49. ProcuremenSchema::ensureAll();
  50. } catch (\Throwable $e) {
  51. }
  52. }
  53. /** 登录有效小时数(用于前端 localStorage 过期时间) */
  54. protected function mprocKeepHours(): int
  55. {
  56. return max(1, (int)round($this->mprocTtlSeconds / 3600));
  57. }
  58. /**
  59. * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
  60. */
  61. protected function mprocGetUser()
  62. {
  63. $token = $this->mprocReadTokenFromRequest();
  64. if ($token !== '') {
  65. $user = $this->mprocLoadUserByToken($token);
  66. if ($user) {
  67. $token = $this->mprocTouchLoginState($user, $token);
  68. $user['token'] = $token;
  69. return $user;
  70. }
  71. }
  72. $user = $this->mprocUserFromRememberCookie();
  73. if (!$user) {
  74. return null;
  75. }
  76. $token = $this->mprocPackSignedAuthToken($user);
  77. $token = $this->mprocTouchLoginState($user, $token);
  78. $user['token'] = $token;
  79. return $user;
  80. }
  81. protected function mprocReadTokenFromRequest(): string
  82. {
  83. $token = Session::get('mproc_token');
  84. if ($token === null || $token === '') {
  85. $token = Cookie::get('mproc_token');
  86. }
  87. if ($token === null || $token === '') {
  88. $token = $this->request->header('X-Mproc-Token');
  89. }
  90. if ($token === null || $token === '') {
  91. $token = $this->request->request('mproc_token', '');
  92. }
  93. $token = trim((string)$token);
  94. if ($token === '') {
  95. return '';
  96. }
  97. if ($this->mprocIsSignedAuthToken($token)) {
  98. return $token;
  99. }
  100. $token = preg_replace('/[^a-f0-9]/i', '', $token);
  101. return strlen($token) >= 16 ? $token : '';
  102. }
  103. protected function mprocIsSignedAuthToken(string $token): bool
  104. {
  105. return strpos($token, '.') !== false
  106. && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
  107. }
  108. protected function mprocAuthCacheKey(string $token): string
  109. {
  110. return 'mproc_u_' . md5($token);
  111. }
  112. /**
  113. * @return array<string, mixed>|null
  114. */
  115. protected function mprocLoadUserByToken(string $token): ?array
  116. {
  117. if ($this->mprocIsSignedAuthToken($token)) {
  118. if ($this->mprocIsAuthTokenRevoked($token)) {
  119. return null;
  120. }
  121. $user = $this->mprocUserFromSignedToken($token);
  122. if (!$user) {
  123. return null;
  124. }
  125. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  126. $this->mprocClearLogin($token);
  127. return null;
  128. }
  129. $user['token'] = $token;
  130. return $user;
  131. }
  132. $user = Cache::get('mproc_u_' . $token);
  133. if (!is_array($user)) {
  134. $user = $this->mprocUserFromRememberCookie();
  135. if (!$user) {
  136. return null;
  137. }
  138. }
  139. if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
  140. return null;
  141. }
  142. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  143. $this->mprocClearLogin($token);
  144. return null;
  145. }
  146. $user['token'] = $token;
  147. return $user;
  148. }
  149. /**
  150. * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
  151. *
  152. * @param array<string, mixed> $user
  153. */
  154. protected function mprocTouchLoginState(array $user, string $token): string
  155. {
  156. $user['login_time'] = time();
  157. if ($this->mprocIsSignedAuthToken($token)) {
  158. $token = $this->mprocPackSignedAuthToken($user);
  159. }
  160. Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
  161. if (!$this->mprocIsSignedAuthToken($token)) {
  162. Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
  163. }
  164. Session::set('mproc_token', $token);
  165. $this->mprocSetTokenCookie($token);
  166. $this->mprocSetRememberCookie($user, $token);
  167. return $token;
  168. }
  169. /**
  170. * @return array<string, mixed>
  171. */
  172. protected function mprocCookieOptions(): array
  173. {
  174. $opts = [
  175. 'expire' => $this->mprocTtlSeconds,
  176. 'path' => '/',
  177. 'httponly' => true,
  178. ];
  179. if ($this->request->isSsl()) {
  180. $opts['secure'] = true;
  181. }
  182. if (PHP_VERSION_ID >= 70300) {
  183. $opts['samesite'] = 'Lax';
  184. }
  185. return $opts;
  186. }
  187. protected function mprocSetTokenCookie(string $token): void
  188. {
  189. Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
  190. }
  191. /**
  192. * @param array<string, mixed> $user
  193. */
  194. protected function mprocSetRememberCookie(array $user, ?string $token = null): void
  195. {
  196. $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
  197. Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
  198. }
  199. protected function mprocAuthSignSecret(): string
  200. {
  201. $key = trim((string)Config::get('mproc.auth_sign_key'));
  202. if ($key === '') {
  203. $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
  204. }
  205. return hash('sha256', $key);
  206. }
  207. /**
  208. * @param array<string, mixed> $user
  209. */
  210. protected function mprocPackSignedAuthToken(array $user): string
  211. {
  212. $payload = [
  213. 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
  214. 'phone' => trim((string)($user['phone'] ?? '')),
  215. 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
  216. 'admin' => !empty($user['is_admin']) ? 1 : 0,
  217. 'lt' => time(),
  218. ];
  219. $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
  220. $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
  221. return $b64 . '.' . $sig;
  222. }
  223. /** @deprecated 使用 mprocPackSignedAuthToken */
  224. protected function mprocPackRememberCookie(array $user): string
  225. {
  226. return $this->mprocPackSignedAuthToken($user);
  227. }
  228. /**
  229. * @return array<string, mixed>|null
  230. */
  231. protected function mprocUserFromSignedToken(string $raw): ?array
  232. {
  233. $parts = explode('.', trim($raw), 2);
  234. if (count($parts) !== 2) {
  235. return null;
  236. }
  237. $b64 = $parts[0];
  238. $sig = $parts[1];
  239. if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
  240. return null;
  241. }
  242. $pad = strlen($b64) % 4;
  243. if ($pad > 0) {
  244. $b64 .= str_repeat('=', 4 - $pad);
  245. }
  246. $json = base64_decode(strtr($b64, '-_', '+/'), true);
  247. if ($json === false || $json === '') {
  248. return null;
  249. }
  250. $payload = json_decode($json, true);
  251. if (!is_array($payload)) {
  252. return null;
  253. }
  254. $lt = (int)($payload['lt'] ?? 0);
  255. if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
  256. return null;
  257. }
  258. return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
  259. }
  260. /**
  261. * @return array<string, mixed>|null
  262. */
  263. protected function mprocUserFromRememberCookie(): ?array
  264. {
  265. $raw = Cookie::get('mproc_remember');
  266. if ($raw === null || $raw === '') {
  267. $raw = Cookie::get('mproc_token');
  268. }
  269. if ($raw === null || $raw === '') {
  270. return null;
  271. }
  272. $raw = (string)$raw;
  273. if ($this->mprocIsAuthTokenRevoked($raw)) {
  274. return null;
  275. }
  276. return $this->mprocUserFromSignedToken($raw);
  277. }
  278. /**
  279. * @param array<string, mixed> $payload
  280. * @return array<string, mixed>|null
  281. */
  282. protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
  283. {
  284. if (!empty($payload['admin'])) {
  285. $uname = trim((string)($payload['uname'] ?? ''));
  286. if ($uname === '') {
  287. return null;
  288. }
  289. try {
  290. $row = Db::name('admin')->where('username', $uname)->find();
  291. } catch (\Throwable $e) {
  292. $row = null;
  293. }
  294. if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
  295. return null;
  296. }
  297. return [
  298. 'phone' => trim((string)($row['mobile'] ?? '')),
  299. 'company_name' => '',
  300. 'username' => $uname,
  301. 'customer_user_id' => 0,
  302. 'admin_id' => (int)($row['id'] ?? 0),
  303. 'login_type' => 'remember',
  304. 'is_admin' => 1,
  305. 'login_time' => $loginTime,
  306. ];
  307. }
  308. $cid = (int)($payload['uid'] ?? 0);
  309. if ($cid > 0) {
  310. try {
  311. $cu = Db::table('customer')->where('id', $cid)->find();
  312. } catch (\Throwable $e) {
  313. $cu = null;
  314. }
  315. if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
  316. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  317. $user['login_time'] = $loginTime;
  318. return $user;
  319. }
  320. }
  321. $phone = trim((string)($payload['phone'] ?? ''));
  322. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  323. $cu = $this->mprocFindCustomerUserByMobile($phone);
  324. if ($cu) {
  325. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  326. $user['login_time'] = $loginTime;
  327. return $user;
  328. }
  329. }
  330. return null;
  331. }
  332. protected function mprocAuthRevokeCacheKey(string $token): string
  333. {
  334. return 'mproc_revoked_' . md5($token);
  335. }
  336. protected function mprocRevokeAuthToken(string $token): void
  337. {
  338. $token = trim($token);
  339. if ($token === '') {
  340. return;
  341. }
  342. try {
  343. Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
  344. } catch (\Throwable $e) {
  345. }
  346. }
  347. protected function mprocIsAuthTokenRevoked(string $token): bool
  348. {
  349. $token = trim($token);
  350. if ($token === '') {
  351. return false;
  352. }
  353. try {
  354. return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
  355. } catch (\Throwable $e) {
  356. return false;
  357. }
  358. }
  359. /**
  360. * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
  361. */
  362. protected function mprocExpireAuthCookies(): void
  363. {
  364. $opts = $this->mprocCookieOptions();
  365. $opts['expire'] = -3600;
  366. try {
  367. Cookie::set('mproc_token', '', $opts);
  368. Cookie::set('mproc_remember', '', $opts);
  369. } catch (\Throwable $e) {
  370. }
  371. try {
  372. Cookie::delete('mproc_token');
  373. Cookie::delete('mproc_remember');
  374. } catch (\Throwable $e) {
  375. }
  376. unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
  377. $prefix = (string)Config::get('cookie.prefix');
  378. if ($prefix !== '') {
  379. unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
  380. }
  381. }
  382. protected function mprocClearLogin($token)
  383. {
  384. $token = trim((string)($token ?? ''));
  385. if ($token !== '') {
  386. $this->mprocRevokeAuthToken($token);
  387. try {
  388. Cache::rm($this->mprocAuthCacheKey($token));
  389. } catch (\Throwable $e) {
  390. }
  391. if (!$this->mprocIsSignedAuthToken($token)) {
  392. try {
  393. Cache::rm('mproc_u_' . $token);
  394. } catch (\Throwable $e) {
  395. }
  396. }
  397. }
  398. // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
  399. foreach (['mproc_token', 'mproc_remember'] as $ck) {
  400. $raw = Cookie::get($ck);
  401. if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
  402. $this->mprocRevokeAuthToken((string)$raw);
  403. }
  404. }
  405. Session::delete('mproc_token');
  406. $this->mprocExpireAuthCookies();
  407. }
  408. /**
  409. * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
  410. *
  411. * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
  412. */
  413. protected function mprocSanitizeRedirectUrl($raw)
  414. {
  415. $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
  416. if ($s === '') {
  417. return '';
  418. }
  419. if (preg_match('#^https?://#i', $s)) {
  420. $h = parse_url($s, PHP_URL_HOST);
  421. if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
  422. return '';
  423. }
  424. $path = parse_url($s, PHP_URL_PATH);
  425. $query = parse_url($s, PHP_URL_QUERY);
  426. $s = (is_string($path) && $path !== '' ? $path : '/');
  427. if (is_string($query) && $query !== '') {
  428. $s .= '?' . $query;
  429. }
  430. }
  431. if (strpos($s, '://') !== false) {
  432. return '';
  433. }
  434. if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
  435. return '';
  436. }
  437. if ($s[0] !== '/') {
  438. $s = '/' . ltrim($s, '/');
  439. }
  440. if (strpos($s, '//') === 0) {
  441. return '';
  442. }
  443. $okHome = stripos($s, 'index/index/index') !== false;
  444. $okInbound = stripos($s, 'index/index/inboundscore') !== false;
  445. $okDelivery = stripos($s, 'index/index/deliveryscore') !== false;
  446. if (!$okHome && !$okInbound && !$okDelivery) {
  447. return '';
  448. }
  449. if (stripos($s, 'index/index/login') !== false) {
  450. return '';
  451. }
  452. return $s;
  453. }
  454. protected function mprocRememberFocusEid(int $focusEid): void
  455. {
  456. if ($focusEid > 0) {
  457. Session::set('mproc_focus_eid', $focusEid);
  458. }
  459. }
  460. protected function mprocPullSessionFocusEid(): int
  461. {
  462. $fe = (int)Session::get('mproc_focus_eid', 0);
  463. if ($fe > 0) {
  464. Session::delete('mproc_focus_eid');
  465. }
  466. return $fe;
  467. }
  468. /**
  469. * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &amp;focus_eid 拼进上一参数值的情况)
  470. */
  471. protected function mprocParseFocusEidFromUriString(string $uri): int
  472. {
  473. if ($uri === '' || stripos($uri, 'focus_eid') === false) {
  474. return 0;
  475. }
  476. if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
  477. return (int)$m[1];
  478. }
  479. $query = parse_url($uri, PHP_URL_QUERY);
  480. if (!is_string($query) || $query === '') {
  481. return 0;
  482. }
  483. $q = [];
  484. parse_str($query, $q);
  485. if (!is_array($q)) {
  486. return 0;
  487. }
  488. if (isset($q['focus_eid'])) {
  489. $fe = (int)$q['focus_eid'];
  490. if ($fe > 0) {
  491. return $fe;
  492. }
  493. }
  494. foreach ($q as $k => $v) {
  495. $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
  496. if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
  497. return (int)$m2[1];
  498. }
  499. }
  500. return 0;
  501. }
  502. /**
  503. * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
  504. */
  505. protected function mprocReadFocusEidFromRequest(): int
  506. {
  507. $fe = (int)$this->request->param('focus_eid', 0);
  508. if ($fe > 0) {
  509. $this->mprocRememberFocusEid($fe);
  510. return $fe;
  511. }
  512. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  513. $fe = $this->mprocParseFocusEidFromUriString($uri);
  514. if ($fe > 0) {
  515. $this->mprocRememberFocusEid($fe);
  516. return $fe;
  517. }
  518. $fe = (int)Session::get('mproc_focus_eid', 0);
  519. if ($fe > 0) {
  520. return $fe;
  521. }
  522. return 0;
  523. }
  524. /**
  525. * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
  526. *
  527. * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
  528. */
  529. protected function mprocBuildLoginUrl($redirectPath = '')
  530. {
  531. $root = rtrim($this->request->root(), '/');
  532. $path = '/index/index/login';
  533. $rp = trim((string)$redirectPath);
  534. if ($rp === '') {
  535. return $root . $path;
  536. }
  537. return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
  538. }
  539. /**
  540. * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
  541. *
  542. * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
  543. */
  544. protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
  545. {
  546. $raw = trim((string)$redirectPathOrUrl);
  547. if ($raw === '') {
  548. return url('index/index/index', '', '', true);
  549. }
  550. $queryStr = '';
  551. if (preg_match('#^https?://#i', $raw)) {
  552. $pq = parse_url($raw);
  553. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  554. } elseif (isset($raw[0]) && $raw[0] === '/') {
  555. $pq = parse_url('http://127.0.0.1' . $raw);
  556. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  557. } else {
  558. $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
  559. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  560. }
  561. $q = [];
  562. if ($queryStr !== '') {
  563. parse_str($queryStr, $q);
  564. if (!is_array($q)) {
  565. $q = [];
  566. }
  567. }
  568. $allowed = [];
  569. $fe = 0;
  570. if (isset($q['focus_eid'])) {
  571. $fe = (int)$q['focus_eid'];
  572. }
  573. if ($fe <= 0) {
  574. $fe = $this->mprocParseFocusEidFromUriString($raw);
  575. }
  576. if ($fe <= 0) {
  577. $fe = (int)Session::get('mproc_focus_eid', 0);
  578. }
  579. if ($fe > 0) {
  580. $allowed['focus_eid'] = $fe;
  581. $this->mprocRememberFocusEid($fe);
  582. }
  583. $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
  584. if ($mt === 'me' || $mt === 'orders') {
  585. $allowed['main_tab'] = $mt;
  586. }
  587. $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
  588. if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
  589. $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
  590. }
  591. if (isset($q['q']) && trim((string)$q['q']) !== '') {
  592. $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
  593. }
  594. if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
  595. $allowed['main_tab'] = 'orders';
  596. }
  597. $base = rtrim($this->request->root(true), '/');
  598. $path = '/index/index/index';
  599. if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
  600. $fe = (int)$allowed['focus_eid'];
  601. if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
  602. return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
  603. }
  604. $ordered = ['focus_eid' => $fe];
  605. if (isset($allowed['tab'])) {
  606. $ordered['tab'] = $allowed['tab'];
  607. }
  608. if (isset($allowed['main_tab'])) {
  609. $ordered['main_tab'] = $allowed['main_tab'];
  610. }
  611. return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
  612. }
  613. $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
  614. return $base . $path . $qs;
  615. }
  616. /**
  617. * 按登录身份决定首页:供应商→报价;质检→质量评分;生产→交货情况
  618. * 后台账号无手机端角色时返回空串(勿回登录页,避免 302 死循环)
  619. *
  620. * @param array<string, mixed> $user
  621. * @param string $redirectPathOrUrl
  622. */
  623. protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
  624. {
  625. if (!empty($user['is_admin'])) {
  626. $canQuality = $this->mprocAdminHasMobileRole($user, 'quality');
  627. $canDelivery = $this->mprocAdminHasMobileRole($user, 'delivery');
  628. $canRfq = $this->mprocAdminHasMobileRole($user, 'rfq');
  629. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  630. if ($raw !== '') {
  631. if ($canDelivery && stripos($raw, 'deliveryscore') !== false) {
  632. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliveryscore');
  633. }
  634. if ($canQuality && stripos($raw, 'inboundscore') !== false) {
  635. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/inboundscore');
  636. }
  637. if ($canRfq && stripos($raw, 'rfqadd') !== false) {
  638. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/rfqadd');
  639. }
  640. }
  641. if ($canQuality) {
  642. return url('index/index/inboundscore', '', '', true);
  643. }
  644. if ($canDelivery) {
  645. return url('index/index/deliveryscore', '', '', true);
  646. }
  647. if ($canRfq) {
  648. return url('index/index/rfqadd', '', '', true);
  649. }
  650. return '';
  651. }
  652. return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
  653. }
  654. /**
  655. * 操作人员是否具备手机端任一业务角色(质检 / 生产 / 业务员询价,含超管)
  656. *
  657. * @param array<string, mixed> $user
  658. */
  659. protected function mprocAdminHasAnyMobileAccess(array $user): bool
  660. {
  661. return $this->mprocAdminHasMobileRole($user, 'quality')
  662. || $this->mprocAdminHasMobileRole($user, 'delivery')
  663. || $this->mprocAdminHasMobileRole($user, 'rfq');
  664. }
  665. /**
  666. * @param array<string, mixed> $row admin 表行
  667. * @return array<string, mixed>
  668. */
  669. protected function mprocLoginPayloadFromAdmin(array $row, string $loginType): array
  670. {
  671. return [
  672. 'phone' => trim((string)($row['mobile'] ?? '')),
  673. 'company_name' => '',
  674. 'username' => trim((string)($row['username'] ?? '')),
  675. 'account' => trim((string)($row['username'] ?? '')),
  676. 'customer_user_id' => 0,
  677. 'customer_id' => 0,
  678. 'admin_id' => (int)($row['id'] ?? 0),
  679. 'login_type' => $loginType,
  680. 'is_admin' => 1,
  681. ];
  682. }
  683. /** 清除当前请求中的手机端登录态(解决无权限账号卡在登录跳转) */
  684. protected function mprocDropCurrentLogin(): void
  685. {
  686. $token = $this->mprocReadTokenFromRequest();
  687. $this->mprocClearLogin($token);
  688. }
  689. /**
  690. * @param string $rawSanitized
  691. * @param string $fallbackRoute
  692. */
  693. protected function mprocAbsoluteFromSanitizedPath($rawSanitized, $fallbackRoute)
  694. {
  695. $base = rtrim($this->request->root(true), '/');
  696. $path = parse_url($rawSanitized, PHP_URL_PATH);
  697. $query = parse_url($rawSanitized, PHP_URL_QUERY);
  698. if (!is_string($path) || $path === '') {
  699. return url($fallbackRoute, '', '', true);
  700. }
  701. return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
  702. }
  703. /**
  704. * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
  705. *
  706. * @param string[] $candidatesLower 如 ['status','istatus']
  707. * @return string|null
  708. */
  709. protected function mprocResolveProcuremenColumn(array $candidatesLower)
  710. {
  711. if (self::$mprocProcuremenColumns === null) {
  712. self::$mprocProcuremenColumns = [];
  713. try {
  714. $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
  715. if (is_array($rows)) {
  716. foreach ($rows as $c) {
  717. $name = isset($c['Field']) ? (string)$c['Field'] : '';
  718. if ($name !== '') {
  719. self::$mprocProcuremenColumns[strtolower($name)] = $name;
  720. }
  721. }
  722. }
  723. } catch (\Throwable $e) {
  724. self::$mprocProcuremenColumns = [];
  725. }
  726. }
  727. foreach ($candidatesLower as $low) {
  728. $k = strtolower((string)$low);
  729. if (isset(self::$mprocProcuremenColumns[$k])) {
  730. return self::$mprocProcuremenColumns[$k];
  731. }
  732. }
  733. return null;
  734. }
  735. /**
  736. * 供应商整单备注(purchase_order_detail.remark)
  737. *
  738. * @param array<string, mixed> $row
  739. */
  740. protected function mprocResolveDetailRemark(array $row): string
  741. {
  742. $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  743. if ($col === null) {
  744. return '';
  745. }
  746. foreach ($row as $k => $v) {
  747. if (strcasecmp((string)$k, $col) === 0) {
  748. return trim((string)$v);
  749. }
  750. }
  751. return '';
  752. }
  753. /**
  754. * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
  755. *
  756. * @return array|callable 可直接 $query->where(...);空数组表示不加条件
  757. */
  758. protected function mprocListWhereForLoginUser(array $user)
  759. {
  760. if (!empty($user['is_admin'])) {
  761. return [];
  762. }
  763. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  764. $pCol = $this->mprocResolveProcuremenColumn(['phone']);
  765. if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
  766. return ['id' => 0];
  767. }
  768. $cn = trim((string)($user['company_name'] ?? ''));
  769. $phone = trim((string)($user['phone'] ?? ''));
  770. if ($cn === '' && $phone !== '') {
  771. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  772. }
  773. if ($cn === '' && $phone === '') {
  774. return ['id' => 0];
  775. }
  776. return function ($q) use ($cCol, $pCol, $cn, $phone) {
  777. $first = true;
  778. if ($cCol !== null && $cCol !== '' && $cn !== '') {
  779. $q->where($cCol, $cn);
  780. $first = false;
  781. }
  782. if ($pCol !== null && $pCol !== '' && $phone !== '') {
  783. if ($first) {
  784. $q->where($pCol, $phone);
  785. } else {
  786. $q->whereOr($pCol, $phone);
  787. }
  788. }
  789. if ($first) {
  790. $q->where('id', 0);
  791. }
  792. };
  793. }
  794. /**
  795. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  796. */
  797. protected function mprocCustomerUserActive(array $row): bool
  798. {
  799. $st = $row['status'] ?? '';
  800. if ($st === '' || $st === null) {
  801. return true;
  802. }
  803. return $st === 1 || $st === '1';
  804. }
  805. /**
  806. * @return array<string, mixed>|null
  807. */
  808. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  809. {
  810. return $this->mprocFindCustomerRowByPhone($phone);
  811. }
  812. /**
  813. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  814. *
  815. * @return array<string, mixed>|null
  816. */
  817. protected function mprocFindCustomerUserByUsername(string $username): ?array
  818. {
  819. $username = trim($username);
  820. if ($username === '') {
  821. return null;
  822. }
  823. try {
  824. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  825. } catch (\Throwable $e) {
  826. $row = null;
  827. }
  828. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  829. $row = $this->mprocFindCustomerRowByPhone($username);
  830. }
  831. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  832. return null;
  833. }
  834. return $row;
  835. }
  836. /**
  837. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  838. */
  839. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  840. {
  841. $stored = (string)($row['password'] ?? '');
  842. if ($stored === '' || $password === '') {
  843. return false;
  844. }
  845. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  846. return password_verify($password, $stored);
  847. }
  848. return hash_equals($stored, md5(md5($password)));
  849. }
  850. /**
  851. * 生成 customer 登录密码密文
  852. */
  853. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  854. {
  855. unset($existingSalt);
  856. return md5(md5($password));
  857. }
  858. /**
  859. * 手机端强密码校验:通过返回空字符串,否则返回错误提示
  860. */
  861. protected function mprocValidateStrongPassword(string $password): string
  862. {
  863. $len = strlen($password);
  864. if ($len < 8 || $len > 20) {
  865. return '密码长度须为8~20位';
  866. }
  867. if (preg_match('/\s/', $password)) {
  868. return '密码不能包含空格';
  869. }
  870. if (preg_match('/^\d+$/', $password)) {
  871. return '密码不能为纯数字,请同时包含字母';
  872. }
  873. if (preg_match('/^[a-zA-Z]+$/', $password)) {
  874. return '密码不能为纯字母,请同时包含数字';
  875. }
  876. if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
  877. return '密码须同时包含字母和数字';
  878. }
  879. if (preg_match('/(.)\1{3,}/', $password)) {
  880. return '密码不能包含过多重复字符(如1111、aaaa)';
  881. }
  882. if ($this->mprocPasswordHasSequentialRun($password, 4)) {
  883. return '密码不能包含连续字符(如1234、abcd)';
  884. }
  885. $weak = [
  886. '12345678', '123456789', '1234567890', '87654321', '01234567',
  887. 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
  888. 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
  889. '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
  890. ];
  891. if (in_array(strtolower($password), $weak, true)) {
  892. return '密码过于简单,请重新设置';
  893. }
  894. return '';
  895. }
  896. /**
  897. * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
  898. */
  899. protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
  900. {
  901. $runLen = max(3, $runLen);
  902. $lower = strtolower($password);
  903. $n = strlen($lower);
  904. if ($n < $runLen) {
  905. return false;
  906. }
  907. for ($i = 0; $i <= $n - $runLen; $i++) {
  908. $asc = true;
  909. $desc = true;
  910. for ($j = 1; $j < $runLen; $j++) {
  911. $prev = ord($lower[$i + $j - 1]);
  912. $cur = ord($lower[$i + $j]);
  913. if ($cur !== $prev + 1) {
  914. $asc = false;
  915. }
  916. if ($cur !== $prev - 1) {
  917. $desc = false;
  918. }
  919. if (!$asc && !$desc) {
  920. break;
  921. }
  922. }
  923. if ($asc || $desc) {
  924. return true;
  925. }
  926. }
  927. return false;
  928. }
  929. /**
  930. * @param array<string, mixed> $cu
  931. * @return array<string, mixed>
  932. */
  933. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  934. {
  935. $phone = trim((string)($cu['phone'] ?? ''));
  936. $account = trim((string)($cu['account'] ?? ''));
  937. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  938. $phone = $account;
  939. }
  940. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  941. $account = $phone;
  942. }
  943. $companyName = trim((string)($cu['company_name'] ?? ''));
  944. if ($companyName === '' && $phone !== '') {
  945. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  946. }
  947. $id = (int)($cu['id'] ?? 0);
  948. return [
  949. 'phone' => $phone,
  950. 'account' => $account,
  951. 'company_name' => $companyName,
  952. 'username' => trim((string)($cu['username'] ?? '')),
  953. 'customer_id' => $id,
  954. 'customer_user_id' => $id,
  955. 'login_type' => $loginType,
  956. 'is_admin' => 0,
  957. ];
  958. }
  959. /**
  960. * 写入手机端登录态并返回跳转 URL
  961. *
  962. * @param array<string, mixed> $userData
  963. */
  964. protected function mprocFinishLogin(array $userData): void
  965. {
  966. $old = Session::get('mproc_token');
  967. if ($old) {
  968. $this->mprocClearLogin((string)$old);
  969. }
  970. $userData['login_time'] = time();
  971. $token = $this->mprocPackSignedAuthToken($userData);
  972. $token = $this->mprocTouchLoginState($userData, $token);
  973. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  974. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  975. Session::delete('mproc_intended_url');
  976. $raw = $postR !== '' ? $postR : $sessR;
  977. $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
  978. if ($jump === '') {
  979. $this->mprocClearLogin($token);
  980. $this->error('账号或密码错误');
  981. }
  982. $this->success('登录成功', $jump, [
  983. 'mproc_token' => $token,
  984. 'keep_hours' => $this->mprocKeepHours(),
  985. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  986. ]);
  987. }
  988. /**
  989. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  990. */
  991. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  992. {
  993. $phone = trim($phone);
  994. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  995. return '';
  996. }
  997. $cust = $this->mprocFindCustomerRowByPhone($phone);
  998. if (is_array($cust) && $cust !== []) {
  999. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  1000. if ($co !== '') {
  1001. return $co;
  1002. }
  1003. }
  1004. try {
  1005. $one = Db::table('purchase_order_detail')
  1006. ->where('phone', $phone)
  1007. ->order('id', 'desc')
  1008. ->find();
  1009. if (is_array($one)) {
  1010. $n = trim((string)($one['company_name'] ?? ''));
  1011. if ($n !== '') {
  1012. return $n;
  1013. }
  1014. }
  1015. } catch (\Throwable $e) {
  1016. }
  1017. return '';
  1018. }
  1019. /**
  1020. * 按手机号匹配 customer(phone 或 account 单值相等)
  1021. *
  1022. * @return array<string, mixed>|null
  1023. */
  1024. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  1025. {
  1026. $phone = trim($phone);
  1027. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1028. return null;
  1029. }
  1030. try {
  1031. $row = Db::table('customer')
  1032. ->where(function ($q) use ($phone) {
  1033. $q->where('phone', $phone)->whereOr('account', $phone);
  1034. })
  1035. ->order('id', 'asc')
  1036. ->find();
  1037. } catch (\Throwable $e) {
  1038. return null;
  1039. }
  1040. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  1041. return null;
  1042. }
  1043. return $row;
  1044. }
  1045. /**
  1046. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  1047. *
  1048. * @return array<string, mixed>|null
  1049. */
  1050. protected function mprocAdminRowByMobile(string $phone): ?array
  1051. {
  1052. $phone = trim($phone);
  1053. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1054. return null;
  1055. }
  1056. try {
  1057. $row = Db::name('admin')
  1058. ->where('mobile', $phone)
  1059. ->where('status', '<>', 'hidden')
  1060. ->order('id', 'asc')
  1061. ->find();
  1062. } catch (\Throwable $e) {
  1063. return null;
  1064. }
  1065. return is_array($row) && $row !== [] ? $row : null;
  1066. }
  1067. /**
  1068. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  1069. *
  1070. * @return array<string, mixed>|null
  1071. */
  1072. protected function mprocFindCustomerRowForUser(array $user): ?array
  1073. {
  1074. $phone = trim((string)($user['phone'] ?? ''));
  1075. if ($phone === '') {
  1076. $phone = trim((string)($user['account'] ?? ''));
  1077. }
  1078. $cn = trim((string)($user['company_name'] ?? ''));
  1079. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1080. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  1081. if ($byPhone !== null) {
  1082. return $byPhone;
  1083. }
  1084. }
  1085. if ($cn !== '') {
  1086. try {
  1087. // customer 表无 name 列,勿用 whereOr('name')
  1088. $hit = Db::table('customer')
  1089. ->where('company_name', $cn)
  1090. ->order('id', 'desc')
  1091. ->find();
  1092. } catch (\Throwable $e) {
  1093. $hit = null;
  1094. }
  1095. if (is_array($hit) && $hit !== []) {
  1096. return $hit;
  1097. }
  1098. }
  1099. return null;
  1100. }
  1101. /**
  1102. * 从 customer 行取字段(兼容列名大小写)
  1103. *
  1104. * @param string[] $candidates
  1105. */
  1106. protected function mprocCustomerPickField(array $row, array $candidates): string
  1107. {
  1108. foreach ($candidates as $want) {
  1109. $lw = strtolower($want);
  1110. foreach ($row as $k => $v) {
  1111. if (!is_string($k)) {
  1112. continue;
  1113. }
  1114. if (strtolower($k) !== $lw) {
  1115. continue;
  1116. }
  1117. $s = trim((string)$v);
  1118. if ($s !== '') {
  1119. return $s;
  1120. }
  1121. }
  1122. }
  1123. return '';
  1124. }
  1125. /**
  1126. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  1127. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  1128. *
  1129. * @param \think\db\Query $query
  1130. */
  1131. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  1132. {
  1133. $kw = trim((string)$search);
  1134. if ($kw === '') {
  1135. return;
  1136. }
  1137. $map = self::$mprocProcuremenColumns;
  1138. if (!is_array($map) || $map === []) {
  1139. return;
  1140. }
  1141. $like = '%' . addcslashes($kw, '%_\\') . '%';
  1142. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  1143. $detailCols = [];
  1144. foreach ($wantLower as $low) {
  1145. if (isset($map[$low])) {
  1146. $detailCols[] = $map[$low];
  1147. }
  1148. }
  1149. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  1150. $idCol = isset($map['id']) ? $map['id'] : 'id';
  1151. $poSidList = [];
  1152. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  1153. try {
  1154. $col = Db::table('purchase_order')
  1155. ->where(function ($sub) use ($like, $poWant) {
  1156. $firstPo = true;
  1157. foreach ($poWant as $pf) {
  1158. if ($firstPo) {
  1159. $sub->where($pf, 'like', $like);
  1160. $firstPo = false;
  1161. } else {
  1162. $sub->whereOr($pf, 'like', $like);
  1163. }
  1164. }
  1165. })
  1166. ->column('scydgy_id');
  1167. if (is_array($col)) {
  1168. foreach ($col as $v) {
  1169. $id = (int)$v;
  1170. if ($this->mprocIsValidScydgyRowId($id)) {
  1171. $poSidList[$id] = true;
  1172. }
  1173. }
  1174. }
  1175. $poSidList = array_keys($poSidList);
  1176. } catch (\Throwable $e) {
  1177. $poSidList = [];
  1178. }
  1179. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  1180. $first = true;
  1181. foreach ($detailCols as $col) {
  1182. if ($first) {
  1183. $q2->where($col, 'like', $like);
  1184. $first = false;
  1185. } else {
  1186. $q2->whereOr($col, 'like', $like);
  1187. }
  1188. }
  1189. if ($poSidList !== []) {
  1190. if ($first) {
  1191. $q2->where($scydgyCol, 'in', $poSidList);
  1192. $first = false;
  1193. } else {
  1194. $q2->whereOr($scydgyCol, 'in', $poSidList);
  1195. }
  1196. }
  1197. if ($first) {
  1198. $q2->where($idCol, '=', 0);
  1199. }
  1200. });
  1201. }
  1202. /**
  1203. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  1204. * - draft:status_name = 未提交
  1205. * - submitted:status_name = 已提交
  1206. * - done:status_name = 已完成
  1207. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  1208. *
  1209. * @param mixed $query
  1210. * @param string $tab draft|submitted|done
  1211. * @param string|null $statusNameCol 真实列名,如 status_name
  1212. */
  1213. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  1214. {
  1215. if ($statusNameCol === null) {
  1216. return;
  1217. }
  1218. $map = [
  1219. 'draft' => '未提交',
  1220. 'submitted' => '已提交',
  1221. 'done' => '已完成',
  1222. ];
  1223. $label = $map[$tab] ?? '未提交';
  1224. $query->where($statusNameCol, '=', $label);
  1225. }
  1226. /**
  1227. * 按登录态解析 customer 行
  1228. *
  1229. * @return array<string, mixed>|null
  1230. */
  1231. protected function mprocResolveCustomerUserForSession(array $user): ?array
  1232. {
  1233. if (!empty($user['is_admin'])) {
  1234. return null;
  1235. }
  1236. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1237. if ($cuId > 0) {
  1238. try {
  1239. $row = Db::table('customer')->where('id', $cuId)->find();
  1240. } catch (\Throwable $e) {
  1241. $row = null;
  1242. }
  1243. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  1244. return $row;
  1245. }
  1246. }
  1247. $account = trim((string)($user['account'] ?? ''));
  1248. if ($account !== '') {
  1249. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  1250. if ($byAcc !== null) {
  1251. return $byAcc;
  1252. }
  1253. }
  1254. $phone = trim((string)($user['phone'] ?? ''));
  1255. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1256. return $this->mprocFindCustomerUserByMobile($phone);
  1257. }
  1258. $uname = trim((string)($user['username'] ?? ''));
  1259. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1260. return $this->mprocFindCustomerUserByMobile($uname);
  1261. }
  1262. return null;
  1263. }
  1264. /**
  1265. * customer 表字段 →「我的」展示结构
  1266. *
  1267. * @param array<string, mixed> $cu
  1268. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1269. */
  1270. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1271. {
  1272. $nm = trim((string)($cu['username'] ?? ''));
  1273. $account = trim((string)($cu['account'] ?? ''));
  1274. $phone = trim((string)($cu['phone'] ?? ''));
  1275. if ($phone === '') {
  1276. $phone = $account;
  1277. }
  1278. $company = trim((string)($cu['company_name'] ?? ''));
  1279. return [
  1280. 'account' => $account !== '' ? $account : $phone,
  1281. 'contact_name' => $nm,
  1282. 'department' => $company,
  1283. 'phone' => $phone,
  1284. 'email' => trim((string)($cu['email'] ?? '')),
  1285. 'company_name' => $company,
  1286. ];
  1287. }
  1288. /**
  1289. * 管理员「我的」:账号、姓名、部门(角色组)、手机、邮箱
  1290. *
  1291. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1292. */
  1293. protected function mprocProfileForAdmin(array $user): array
  1294. {
  1295. $uname = trim((string)($user['username'] ?? ''));
  1296. $out = [
  1297. 'account' => $uname,
  1298. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1299. 'department' => '',
  1300. 'phone' => trim((string)($user['phone'] ?? '')),
  1301. 'email' => '',
  1302. 'company_name' => '',
  1303. ];
  1304. if ($uname === '') {
  1305. return $out;
  1306. }
  1307. try {
  1308. $row = Db::name('admin')->where('username', $uname)->find();
  1309. } catch (\Throwable $e) {
  1310. $row = null;
  1311. }
  1312. if (!is_array($row) || $row === []) {
  1313. return $out;
  1314. }
  1315. $out['account'] = trim((string)($row['username'] ?? $uname));
  1316. $nick = trim((string)($row['nickname'] ?? ''));
  1317. if ($nick !== '') {
  1318. $out['contact_name'] = $nick;
  1319. }
  1320. $mob = trim((string)($row['mobile'] ?? ''));
  1321. if ($mob !== '') {
  1322. $out['phone'] = $mob;
  1323. }
  1324. $em = trim((string)($row['email'] ?? ''));
  1325. if ($em !== '') {
  1326. $out['email'] = $em;
  1327. }
  1328. $dept = $this->mprocAdminDepartmentLabel((int)($row['id'] ?? 0));
  1329. $out['department'] = $dept;
  1330. $out['company_name'] = $dept;
  1331. return $out;
  1332. }
  1333. /**
  1334. * 管理员部门展示:优先质检中心/生产部,否则拼接所属角色组名
  1335. */
  1336. protected function mprocAdminDepartmentLabel(int $adminId): string
  1337. {
  1338. if ($adminId <= 0) {
  1339. return '';
  1340. }
  1341. $names = [];
  1342. try {
  1343. $rows = Db::name('auth_group_access')
  1344. ->alias('aga')
  1345. ->join('auth_group ag', 'aga.group_id = ag.id')
  1346. ->where('aga.uid', $adminId)
  1347. ->where('ag.status', 'normal')
  1348. ->field('ag.id,ag.name')
  1349. ->order('ag.id', 'asc')
  1350. ->select();
  1351. } catch (\Throwable $e) {
  1352. $rows = [];
  1353. }
  1354. if (!is_array($rows)) {
  1355. return '';
  1356. }
  1357. $qualityId = $this->mprocResolveMobileQualityGroupId();
  1358. $deliveryId = $this->mprocResolveMobileDeliveryGroupId();
  1359. $deliveryLabel = trim((string)Config::get('mproc.mobile_delivery_dept_name'));
  1360. if ($deliveryLabel === '') {
  1361. $deliveryLabel = '生产部';
  1362. }
  1363. foreach ($rows as $r) {
  1364. if (!is_array($r)) {
  1365. continue;
  1366. }
  1367. $gid = (int)($r['id'] ?? 0);
  1368. $name = trim((string)($r['name'] ?? ''));
  1369. if ($gid === $qualityId) {
  1370. $names[] = '质检中心';
  1371. continue;
  1372. }
  1373. if ($gid === $deliveryId) {
  1374. $names[] = $deliveryLabel;
  1375. continue;
  1376. }
  1377. if ($name !== '') {
  1378. $names[] = $name;
  1379. }
  1380. }
  1381. $names = array_values(array_unique($names));
  1382. return $names !== [] ? implode('、', $names) : '';
  1383. }
  1384. /**
  1385. * 旧会话补全 customer_id 等字段
  1386. */
  1387. protected function mprocSyncSessionCustomerUser(array $user): array
  1388. {
  1389. if (!empty($user['is_admin'])) {
  1390. return $user;
  1391. }
  1392. $cu = $this->mprocResolveCustomerUserForSession($user);
  1393. if (!$cu) {
  1394. return $user;
  1395. }
  1396. $id = (int)($cu['id'] ?? 0);
  1397. $user['customer_id'] = $id;
  1398. $user['customer_user_id'] = $id;
  1399. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1400. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1401. $user['account'] = trim((string)($cu['account'] ?? ''));
  1402. $mob = trim((string)($cu['phone'] ?? ''));
  1403. if ($mob === '') {
  1404. $mob = trim((string)($cu['account'] ?? ''));
  1405. }
  1406. if ($mob !== '') {
  1407. $user['phone'] = $mob;
  1408. }
  1409. $token = Session::get('mproc_token');
  1410. if ($token) {
  1411. $user['login_time'] = (int)($user['login_time'] ?? time());
  1412. $tok = trim((string)$token);
  1413. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1414. if (!$this->mprocIsSignedAuthToken($tok)) {
  1415. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1416. }
  1417. }
  1418. return $user;
  1419. }
  1420. /**
  1421. * 「我的」:普通用户 customer;管理员 admin
  1422. */
  1423. protected function mprocProfileForUser(array $user)
  1424. {
  1425. if (!empty($user['is_admin'])) {
  1426. return $this->mprocProfileForAdmin($user);
  1427. }
  1428. $cu = $this->mprocResolveCustomerUserForSession($user);
  1429. if (is_array($cu) && $cu !== []) {
  1430. return $this->mprocProfileFromCustomerUserRow($cu);
  1431. }
  1432. $phone = trim((string)($user['phone'] ?? ''));
  1433. if ($phone === '') {
  1434. $phone = trim((string)($user['account'] ?? ''));
  1435. }
  1436. return [
  1437. 'account' => $phone !== '' ? $phone : trim((string)($user['account'] ?? '')),
  1438. 'contact_name' => trim((string)($user['username'] ?? '')),
  1439. 'department' => trim((string)($user['company_name'] ?? '')),
  1440. 'phone' => $phone,
  1441. 'email' => '',
  1442. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1443. ];
  1444. }
  1445. protected function mprocIsValidScydgyRowId($id): bool
  1446. {
  1447. return (int)$id !== 0;
  1448. }
  1449. /**
  1450. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1451. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1452. *
  1453. * @param array $row 引用:明细行
  1454. * @param array $poRow purchase_order 一行
  1455. */
  1456. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1457. {
  1458. $pl = array_change_key_case($poRow, CASE_LOWER);
  1459. $hdr = [
  1460. 'ccydh' => 'CCYDH',
  1461. 'cyjmc' => 'CYJMC',
  1462. 'cdf' => 'CDF',
  1463. 'cgzzxmc' => 'cGzzxMc',
  1464. 'cgymc' => 'CGYMC',
  1465. 'cdxmc' => 'CDXMC',
  1466. 'ngzl' => 'NGZL',
  1467. 'cdw' => 'CDW',
  1468. 'cgybh' => 'CGYBH',
  1469. ];
  1470. foreach ($hdr as $lk => $out) {
  1471. if (!array_key_exists($lk, $pl)) {
  1472. continue;
  1473. }
  1474. $v = $pl[$lk];
  1475. if ($v !== null && $v !== '') {
  1476. $row[$out] = $v;
  1477. }
  1478. }
  1479. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1480. $qtyRaw = '';
  1481. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1482. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1483. $qtyRaw = trim((string)$pl[$qk]);
  1484. break;
  1485. }
  1486. }
  1487. if ($qtyRaw === '') {
  1488. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1489. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1490. $qtyRaw = trim((string)$poRow[$qk]);
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. if ($qtyRaw !== '') {
  1496. $row['This_quantity'] = $qtyRaw;
  1497. }
  1498. $ceilRaw = '';
  1499. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1500. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1501. $ceilRaw = trim((string)$pl[$ck]);
  1502. break;
  1503. }
  1504. }
  1505. if ($ceilRaw === '') {
  1506. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1507. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1508. $ceilRaw = trim((string)$poRow[$ck]);
  1509. break;
  1510. }
  1511. }
  1512. }
  1513. if ($ceilRaw !== '') {
  1514. $row['ceilingPrice'] = $ceilRaw;
  1515. }
  1516. $sysRq = '';
  1517. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1518. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1519. $sysRq = trim((string)$pl[$sk]);
  1520. break;
  1521. }
  1522. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1523. $sysRq = trim((string)$poRow[$sk]);
  1524. break;
  1525. }
  1526. }
  1527. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1528. $row['sys_rq'] = $sysRq;
  1529. }
  1530. $deliveryDeadline = '';
  1531. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1532. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1533. $deliveryDeadline = trim((string)$pl[$dk]);
  1534. break;
  1535. }
  1536. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1537. $deliveryDeadline = trim((string)$poRow[$dk]);
  1538. break;
  1539. }
  1540. }
  1541. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1542. $row['delivery_deadline'] = $deliveryDeadline;
  1543. }
  1544. }
  1545. /**
  1546. * 统一取年月日(无效则空串)
  1547. */
  1548. protected function mprocFormatYmdValue($raw): string
  1549. {
  1550. $s = trim((string)$raw);
  1551. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1552. return '';
  1553. }
  1554. $s = str_replace(['/', '.'], '-', $s);
  1555. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1556. return $m[1];
  1557. }
  1558. $ts = strtotime(str_replace('T', ' ', $s));
  1559. if ($ts === false || $ts <= 0) {
  1560. return '';
  1561. }
  1562. return date('Y-m-d', $ts);
  1563. }
  1564. /**
  1565. * 列表展示:招标截止 / 交货截止
  1566. *
  1567. * @param array<string, mixed> $row
  1568. */
  1569. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1570. {
  1571. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1572. $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
  1573. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1574. $row['mproc_bid_deadline_display'] = $bid;
  1575. // 完整截止时间供前端保存前校验(含时分秒)
  1576. $row['mproc_bid_deadline'] = $sysRqRaw;
  1577. $row['mproc_delivery_deadline_display'] = $del;
  1578. $row['mproc_delivery_deadline'] = $del;
  1579. }
  1580. /**
  1581. * 明细对应主表的交货截止日期 Y-m-d
  1582. *
  1583. * @param array<string, mixed> $row
  1584. */
  1585. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1586. {
  1587. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1588. if ($fromRow !== '') {
  1589. return $fromRow;
  1590. }
  1591. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1592. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1593. return '';
  1594. }
  1595. try {
  1596. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1597. } catch (\Throwable $e) {
  1598. $po = null;
  1599. }
  1600. if (!is_array($po)) {
  1601. return '';
  1602. }
  1603. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1604. }
  1605. /**
  1606. * 主表报价截止时间(未设置则视为未截止)
  1607. *
  1608. * @param array<string, mixed>|null $po
  1609. */
  1610. protected function mprocResolveSysRqFromPo(?array $po): string
  1611. {
  1612. if (!is_array($po)) {
  1613. return '';
  1614. }
  1615. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1616. if ($sr === '') {
  1617. $pl = array_change_key_case($po, CASE_LOWER);
  1618. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1619. }
  1620. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1621. }
  1622. /**
  1623. * 从主表/明细解析订单号
  1624. *
  1625. * @param array<string, mixed>|null $po
  1626. * @param array<string, mixed>|null $row
  1627. */
  1628. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1629. {
  1630. foreach ([$po, $row] as $src) {
  1631. if (!is_array($src)) {
  1632. continue;
  1633. }
  1634. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1635. if ($c !== '') {
  1636. return $c;
  1637. }
  1638. }
  1639. return '';
  1640. }
  1641. /**
  1642. * 批量:已开标验证的订单号集合(本请求内可复用)
  1643. *
  1644. * @var array<string, bool>|null
  1645. */
  1646. protected $mprocBidOpenVerifiedSet = null;
  1647. /**
  1648. * @param array<int, string> $ccydhs
  1649. * @return array<string, bool>
  1650. */
  1651. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1652. {
  1653. $set = [];
  1654. $list = [];
  1655. foreach ($ccydhs as $c) {
  1656. $c = trim((string)$c);
  1657. if ($c !== '') {
  1658. $list[$c] = true;
  1659. }
  1660. }
  1661. if ($list === []) {
  1662. return $set;
  1663. }
  1664. try {
  1665. $rows = Db::table('purchase_order_bid_open')
  1666. ->where('ccydh', 'in', array_keys($list))
  1667. ->field('ccydh')
  1668. ->select();
  1669. if (!is_array($rows)) {
  1670. return $set;
  1671. }
  1672. foreach ($rows as $row) {
  1673. if (!is_array($row)) {
  1674. continue;
  1675. }
  1676. $c = trim((string)($row['ccydh'] ?? ''));
  1677. if ($c !== '') {
  1678. $set[$c] = true;
  1679. }
  1680. }
  1681. } catch (\Throwable $e) {
  1682. return [];
  1683. }
  1684. return $set;
  1685. }
  1686. /**
  1687. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1688. */
  1689. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1690. {
  1691. $ccydh = trim($ccydh);
  1692. if ($ccydh === '') {
  1693. return false;
  1694. }
  1695. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1696. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1697. }
  1698. try {
  1699. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1700. return is_array($row);
  1701. } catch (\Throwable $e) {
  1702. return false;
  1703. }
  1704. }
  1705. /**
  1706. * @param array<string, mixed>|null $po
  1707. * @param array<string, mixed>|null $row
  1708. */
  1709. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1710. {
  1711. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1712. }
  1713. /**
  1714. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1715. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1716. *
  1717. * @param array<string, mixed>|null $po
  1718. */
  1719. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1720. {
  1721. $raw = $this->mprocResolveSysRqFromPo($po);
  1722. if ($raw === '') {
  1723. return false;
  1724. }
  1725. $ts = strtotime(str_replace('T', ' ', $raw));
  1726. if ($ts === false || $ts <= 0) {
  1727. return false;
  1728. }
  1729. return time() >= $ts;
  1730. }
  1731. /**
  1732. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1733. *
  1734. * @param array<string, mixed>|null $po
  1735. */
  1736. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1737. {
  1738. // 以库中最新主表为准,避免内存中旧快照
  1739. $freshPo = null;
  1740. if (is_array($po)) {
  1741. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1742. if ($this->mprocIsValidScydgyRowId($sid)) {
  1743. try {
  1744. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1745. } catch (\Throwable $e) {
  1746. $freshPo = null;
  1747. }
  1748. }
  1749. }
  1750. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1751. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1752. throw new \InvalidArgumentException(
  1753. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1754. );
  1755. }
  1756. }
  1757. /**
  1758. * 保存前:截止时间 + 已开标均不可再改
  1759. *
  1760. * @param array<string, mixed>|null $po
  1761. * @param array<string, mixed>|null $row
  1762. */
  1763. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1764. {
  1765. $sid = 0;
  1766. if (is_array($row)) {
  1767. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1768. }
  1769. if ($sid === 0 && is_array($po)) {
  1770. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1771. }
  1772. // 手工询价无招标截止、不开标
  1773. if ($sid < 0) {
  1774. return;
  1775. }
  1776. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1777. $freshPo = is_array($po) ? $po : null;
  1778. if (is_array($po)) {
  1779. if ($this->mprocIsValidScydgyRowId($sid)) {
  1780. try {
  1781. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1782. if (is_array($got)) {
  1783. $freshPo = $got;
  1784. }
  1785. } catch (\Throwable $e) {
  1786. }
  1787. }
  1788. }
  1789. // 保存场景不走列表缓存,直接查库
  1790. $prev = $this->mprocBidOpenVerifiedSet;
  1791. $this->mprocBidOpenVerifiedSet = null;
  1792. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1793. $this->mprocBidOpenVerifiedSet = $prev;
  1794. if ($opened) {
  1795. throw new \InvalidArgumentException(
  1796. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1797. );
  1798. }
  1799. }
  1800. /**
  1801. * 主单已完结后:中标 / 未中标
  1802. *
  1803. * @param array<string, mixed> $row
  1804. * @param array<string, mixed>|null $po
  1805. */
  1806. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1807. {
  1808. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1809. return '';
  1810. }
  1811. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1812. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1813. }
  1814. /**
  1815. * 手机端左侧 Tab:
  1816. * 询价:rfq / rfq_submitted(手工单 scydgy_id&lt;0,仅未提交/已提交)
  1817. * 报价:draft / submitted / done(协助下发)
  1818. *
  1819. * @param array<string, mixed> $row
  1820. * @param array<string, mixed>|null $po
  1821. */
  1822. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1823. {
  1824. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1825. // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
  1826. if ($sid < 0) {
  1827. if ($effectiveSn === '已提交'
  1828. || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1829. return 'rfq_submitted';
  1830. }
  1831. return 'rfq';
  1832. }
  1833. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1834. return 'done';
  1835. }
  1836. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
  1837. || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1838. // 已开标或已过招标截止 →「已完成」
  1839. return 'done';
  1840. }
  1841. if ($effectiveSn === '已提交') {
  1842. return 'submitted';
  1843. }
  1844. return 'draft';
  1845. }
  1846. /**
  1847. * @return string[]
  1848. */
  1849. protected function mprocListTabWhitelist(): array
  1850. {
  1851. return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
  1852. }
  1853. /**
  1854. * 兼容旧地址 tab=rfq_done → 询价已提交
  1855. */
  1856. protected function mprocNormalizeListTab(string $tab): string
  1857. {
  1858. if ($tab === 'rfq_done') {
  1859. return 'rfq_submitted';
  1860. }
  1861. if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
  1862. return 'draft';
  1863. }
  1864. return $tab;
  1865. }
  1866. protected function mprocIsDoneListTab(string $tab): bool
  1867. {
  1868. return $tab === 'done';
  1869. }
  1870. protected function mprocIsRfqListTab(string $tab): bool
  1871. {
  1872. return $tab === 'rfq' || $tab === 'rfq_submitted';
  1873. }
  1874. /**
  1875. * 复合 Tab → 状态维度:draft|submitted|done
  1876. */
  1877. protected function mprocStatusFromListTab(string $tab): string
  1878. {
  1879. if ($tab === 'rfq' || $tab === 'draft') {
  1880. return 'draft';
  1881. }
  1882. if ($tab === 'rfq_submitted' || $tab === 'submitted') {
  1883. return 'submitted';
  1884. }
  1885. if ($this->mprocIsDoneListTab($tab)) {
  1886. return 'done';
  1887. }
  1888. return 'draft';
  1889. }
  1890. /**
  1891. * 同一订单号 + 供应商合并为一张卡片
  1892. *
  1893. * @param array<int, array<string, mixed>> $rows
  1894. * @return array<int, array<string, mixed>>
  1895. */
  1896. protected function mprocGroupRowsByOrder(array $rows): array
  1897. {
  1898. $groups = [];
  1899. $order = [];
  1900. foreach ($rows as $row) {
  1901. if (!is_array($row)) {
  1902. continue;
  1903. }
  1904. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1905. $cname = trim((string)($row['company_name'] ?? ''));
  1906. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1907. if (!isset($groups[$key])) {
  1908. $groups[$key] = [
  1909. 'group_key' => $key,
  1910. 'CCYDH' => $ccydh,
  1911. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1912. 'company_name' => $cname,
  1913. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  1914. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  1915. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  1916. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  1917. 'lines' => [],
  1918. ];
  1919. $order[] = $key;
  1920. } else {
  1921. if ($groups[$key]['mproc_delivery_deadline'] === ''
  1922. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  1923. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  1924. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  1925. }
  1926. if ($groups[$key]['mproc_bid_deadline'] === ''
  1927. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  1928. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  1929. }
  1930. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  1931. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  1932. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  1933. }
  1934. }
  1935. $groups[$key]['lines'][] = $row;
  1936. }
  1937. $out = [];
  1938. foreach ($order as $key) {
  1939. $g = $groups[$key];
  1940. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1941. usort($lines, function ($a, $b) {
  1942. $sa = (int)($a['scydgy_id'] ?? 0);
  1943. $sb = (int)($b['scydgy_id'] ?? 0);
  1944. if ($sa !== $sb) {
  1945. return $sa <=> $sb;
  1946. }
  1947. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1948. });
  1949. $g['lines'] = $lines;
  1950. $g['line_count'] = count($lines);
  1951. $canEdit = false;
  1952. $bidOpen = false;
  1953. foreach ($lines as $ln) {
  1954. if (!is_array($ln)) {
  1955. continue;
  1956. }
  1957. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1958. $canEdit = true;
  1959. }
  1960. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  1961. $bidOpen = true;
  1962. }
  1963. }
  1964. $g['can_edit'] = $canEdit ? 1 : 0;
  1965. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  1966. $remark = '';
  1967. $doneLabel = '';
  1968. $pickResult = '';
  1969. $hasWin = false;
  1970. $hasLose = false;
  1971. $hasExpired = false;
  1972. foreach ($lines as $ln) {
  1973. if (!is_array($ln)) {
  1974. continue;
  1975. }
  1976. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1977. if ($rm !== '' && $remark === '') {
  1978. $remark = $rm;
  1979. }
  1980. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1981. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1982. if ($pr === '中标' || $dl === '中标') {
  1983. $hasWin = true;
  1984. } elseif ($pr === '未中标' || $dl === '未中标') {
  1985. $hasLose = true;
  1986. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  1987. $hasExpired = true;
  1988. }
  1989. }
  1990. if ($hasWin) {
  1991. $doneLabel = '中标';
  1992. $pickResult = '中标';
  1993. } elseif ($hasLose) {
  1994. $doneLabel = '未中标';
  1995. $pickResult = '未中标';
  1996. } elseif ($hasExpired) {
  1997. $doneLabel = '已截止';
  1998. $pickResult = '';
  1999. }
  2000. $g['remark'] = $remark;
  2001. $g['mproc_done_label'] = $doneLabel;
  2002. $g['mproc_pick_result'] = $pickResult;
  2003. $out[] = $g;
  2004. }
  2005. return $out;
  2006. }
  2007. /**
  2008. * 查询 purchase_order_detail 列表(订单页)
  2009. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  2010. * 有搜索词时:在当前 Tab 内做关键字匹配
  2011. *
  2012. * @param string $tab draft|submitted|done
  2013. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  2014. * @return array{rows: array, done_no_status: int}
  2015. */
  2016. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  2017. {
  2018. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  2019. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  2020. $userWhere = $this->mprocListWhereForLoginUser($user);
  2021. if ($userWhere !== []) {
  2022. $query->where($userWhere);
  2023. }
  2024. if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
  2025. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  2026. }
  2027. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  2028. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  2029. try {
  2030. $rows = $query->limit(500)->select();
  2031. } catch (\Throwable $e) {
  2032. $rows = [];
  2033. }
  2034. if (!is_array($rows)) {
  2035. $rows = [];
  2036. }
  2037. $poBySid = [];
  2038. $sidList = [];
  2039. foreach ($rows as $r0) {
  2040. if (!is_array($r0)) {
  2041. continue;
  2042. }
  2043. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  2044. if ($this->mprocIsValidScydgyRowId($sid0)) {
  2045. $sidList[$sid0] = true;
  2046. }
  2047. }
  2048. if ($sidList !== []) {
  2049. try {
  2050. $poRows = Db::table('purchase_order')
  2051. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  2052. ->select();
  2053. if (is_array($poRows)) {
  2054. foreach ($poRows as $pr) {
  2055. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2056. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2057. $poBySid[$sidk] = $pr;
  2058. }
  2059. }
  2060. }
  2061. } catch (\Throwable $e) {
  2062. }
  2063. }
  2064. $ccydhForBid = [];
  2065. foreach ($poBySid as $pr) {
  2066. if (!is_array($pr)) {
  2067. continue;
  2068. }
  2069. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  2070. if ($c !== '') {
  2071. $ccydhForBid[$c] = true;
  2072. }
  2073. }
  2074. foreach ($rows as $r0) {
  2075. if (!is_array($r0)) {
  2076. continue;
  2077. }
  2078. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  2079. if ($c !== '') {
  2080. $ccydhForBid[$c] = true;
  2081. }
  2082. }
  2083. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  2084. foreach ($rows as &$row) {
  2085. if (!is_array($row)) {
  2086. continue;
  2087. }
  2088. // 废弃明细不在手机端展示
  2089. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
  2090. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
  2091. $row = null;
  2092. continue;
  2093. }
  2094. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  2095. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2096. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  2097. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  2098. }
  2099. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  2100. $oldSn = trim((string)($row['status_name'] ?? ''));
  2101. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  2102. $row['status_name'] = $effectiveSn;
  2103. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  2104. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  2105. }
  2106. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  2107. $row['mproc_list_tab'] = $listTab;
  2108. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2109. if ((int)$row['mproc_is_rfq'] === 1) {
  2110. // 手工询价不展示招标/交货截止,也不走开标截止逻辑
  2111. $row['mproc_bid_deadline'] = '';
  2112. $row['mproc_bid_deadline_display'] = '';
  2113. $row['mproc_delivery_deadline'] = '';
  2114. $row['mproc_delivery_deadline_display'] = '';
  2115. $row['mproc_deadline_reached'] = 0;
  2116. $row['mproc_bid_open_verified'] = 0;
  2117. $row['mproc_pick_result'] = '';
  2118. } else {
  2119. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2120. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2121. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  2122. }
  2123. if ($row['mproc_pick_result'] !== '') {
  2124. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2125. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2126. (int)$row['mproc_deadline_reached'] === 1
  2127. || (int)$row['mproc_bid_open_verified'] === 1
  2128. )) {
  2129. $row['mproc_done_label'] = '已截止';
  2130. } else {
  2131. $row['mproc_done_label'] = '';
  2132. }
  2133. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  2134. if (!isset($row['status_name']) || $row['status_name'] === null) {
  2135. $row['status_name'] = '';
  2136. } else {
  2137. $row['status_name'] = trim((string)$row['status_name']);
  2138. }
  2139. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2140. $am = $row['amount'] ?? null;
  2141. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  2142. $row['amount_display'] = '';
  2143. } else {
  2144. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  2145. }
  2146. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2147. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2148. $row['delivery_display'] = $m[1];
  2149. } elseif ($dv !== '') {
  2150. $row['delivery_display'] = $dv;
  2151. } else {
  2152. $row['delivery_display'] = '';
  2153. }
  2154. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2155. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2156. $this->mprocEnrichLeadDaysDisplay($row);
  2157. if ((int)$row['mproc_is_rfq'] === 1) {
  2158. $row['mproc_bid_deadline'] = '';
  2159. $row['mproc_bid_deadline_display'] = '';
  2160. $row['mproc_delivery_deadline'] = '';
  2161. $row['mproc_delivery_deadline_display'] = '';
  2162. } else {
  2163. $this->mprocEnrichOrderDeadlineDisplay($row);
  2164. }
  2165. $row['mproc_fill_hint'] = '';
  2166. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2167. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  2168. }
  2169. unset($row);
  2170. $rows = array_values(array_filter($rows, function ($r) {
  2171. return is_array($r);
  2172. }));
  2173. // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
  2174. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  2175. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  2176. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  2177. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  2178. }));
  2179. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  2180. if ($this->mprocIsDoneListTab((string)$tab)) {
  2181. $rows = array_values(array_filter($rows, function ($r) {
  2182. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  2183. }));
  2184. }
  2185. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  2186. $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
  2187. $groups = $this->mprocGroupRowsByOrder($rows);
  2188. return [
  2189. 'rows' => $rows ?: [],
  2190. 'groups' => $groups ?: [],
  2191. 'done_no_status' => (int)($statusNameCol === null),
  2192. ];
  2193. }
  2194. /**
  2195. * 按招标截止时间排序(无截止时间的排最后)
  2196. *
  2197. * @param array<int, array<string, mixed>> $rows
  2198. * @param string $dir asc|desc
  2199. * @return array<int, array<string, mixed>>
  2200. */
  2201. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  2202. {
  2203. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  2204. usort($rows, function ($a, $b) use ($dir) {
  2205. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  2206. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  2207. $ha = $ta > 0;
  2208. $hb = $tb > 0;
  2209. if ($ha !== $hb) {
  2210. return $ha ? -1 : 1;
  2211. }
  2212. if ($ha && $ta !== $tb) {
  2213. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  2214. }
  2215. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  2216. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  2217. return $idb <=> $ida;
  2218. });
  2219. return array_values($rows);
  2220. }
  2221. /**
  2222. * @param array<string, mixed> $row
  2223. */
  2224. protected function mprocBidDeadlineSortTs(array $row): int
  2225. {
  2226. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  2227. if ($raw === '') {
  2228. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  2229. }
  2230. if ($raw === '') {
  2231. return 0;
  2232. }
  2233. $ts = strtotime(str_replace('T', ' ', $raw));
  2234. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  2235. }
  2236. /**
  2237. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  2238. *
  2239. * @param array<string, mixed> $row
  2240. */
  2241. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  2242. {
  2243. $months = max(1, $months);
  2244. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  2245. if ($since === false) {
  2246. return true;
  2247. }
  2248. $candidates = [
  2249. $row['mproc_bid_deadline'] ?? '',
  2250. $row['sys_rq'] ?? '',
  2251. $row['SYS_RQ'] ?? '',
  2252. $row['mproc_bid_deadline_display'] ?? '',
  2253. $row['mproc_delivery_deadline'] ?? '',
  2254. $row['delivery_deadline'] ?? '',
  2255. $row['mproc_delivery_deadline_display'] ?? '',
  2256. $row['createtime'] ?? '',
  2257. $row['updatetime'] ?? '',
  2258. ];
  2259. foreach ($candidates as $raw) {
  2260. $raw = trim((string)$raw);
  2261. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  2262. continue;
  2263. }
  2264. $ts = strtotime(str_replace('T', ' ', $raw));
  2265. if ($ts === false || $ts <= 0) {
  2266. continue;
  2267. }
  2268. return $ts >= $since;
  2269. }
  2270. return false;
  2271. }
  2272. /**
  2273. * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
  2274. *
  2275. * @param array<int, array<string, mixed>> $rows
  2276. * @return array<int, array<string, mixed>>
  2277. */
  2278. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  2279. {
  2280. $best = [];
  2281. $orderKeys = [];
  2282. foreach ($rows as $row) {
  2283. if (!is_array($row)) {
  2284. continue;
  2285. }
  2286. $cn = trim((string)($row['company_name'] ?? ''));
  2287. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2288. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  2289. if ($this->mprocIsValidScydgyRowId($sid)) {
  2290. $key = $cn . '|sid:' . $sid;
  2291. } else {
  2292. $key = $cn . '|eid:' . $eid;
  2293. }
  2294. if (!isset($best[$key])) {
  2295. $best[$key] = $row;
  2296. $orderKeys[] = $key;
  2297. continue;
  2298. }
  2299. $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
  2300. if ($eid > $prevEid) {
  2301. $best[$key] = $row;
  2302. }
  2303. }
  2304. $out = [];
  2305. foreach ($orderKeys as $key) {
  2306. if (isset($best[$key])) {
  2307. $out[] = $best[$key];
  2308. }
  2309. }
  2310. return $out;
  2311. }
  2312. /**
  2313. * status_name → 手机端左侧 Tab
  2314. */
  2315. protected function mprocStatusNameToListTab(string $statusName): string
  2316. {
  2317. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2318. $sn = trim($statusName);
  2319. return isset($map[$sn]) ? $map[$sn] : '';
  2320. }
  2321. /**
  2322. * 短信/邮件 focus_eid 应落在的列表 Tab
  2323. */
  2324. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2325. {
  2326. if ($focusEid <= 0) {
  2327. return '';
  2328. }
  2329. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2330. if ($idCol === null) {
  2331. return '';
  2332. }
  2333. try {
  2334. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2335. $qw = $this->mprocListWhereForLoginUser($user);
  2336. if ($qw !== []) {
  2337. $qrow->where($qw);
  2338. }
  2339. $dr = $qrow->find();
  2340. } catch (\Throwable $e) {
  2341. $dr = null;
  2342. }
  2343. if (!is_array($dr) || $dr === []) {
  2344. return '';
  2345. }
  2346. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2347. $po = null;
  2348. if ($this->mprocIsValidScydgyRowId($sid)) {
  2349. try {
  2350. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2351. } catch (\Throwable $e) {
  2352. $po = null;
  2353. }
  2354. }
  2355. return $this->mprocResolveListTabForRow(
  2356. $dr,
  2357. is_array($po) ? $po : null,
  2358. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2359. );
  2360. }
  2361. /**
  2362. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2363. *
  2364. * @param array<string, mixed> $bundle
  2365. * @param array<string, mixed> $user
  2366. * @return array<string, mixed>
  2367. */
  2368. protected function mprocEnsureFocusRowInList(
  2369. array $bundle,
  2370. int $focusEid,
  2371. array $user,
  2372. $statusNameCol,
  2373. string $tab = 'draft',
  2374. string $q = ''
  2375. ): array {
  2376. if ($focusEid <= 0) {
  2377. return $bundle;
  2378. }
  2379. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2380. $foundIdx = -1;
  2381. foreach ($rows as $idx => $r) {
  2382. if (!is_array($r)) {
  2383. continue;
  2384. }
  2385. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2386. $foundIdx = (int)$idx;
  2387. break;
  2388. }
  2389. }
  2390. if ($foundIdx > 0) {
  2391. $hit = $rows[$foundIdx];
  2392. array_splice($rows, $foundIdx, 1);
  2393. array_unshift($rows, $hit);
  2394. $bundle['rows'] = $rows;
  2395. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2396. return $bundle;
  2397. }
  2398. if ($foundIdx === 0) {
  2399. return $bundle;
  2400. }
  2401. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2402. if ($idCol === null) {
  2403. return $bundle;
  2404. }
  2405. try {
  2406. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2407. $qw = $this->mprocListWhereForLoginUser($user);
  2408. if ($qw !== []) {
  2409. $qrow->where($qw);
  2410. }
  2411. $dr = $qrow->find();
  2412. } catch (\Throwable $e) {
  2413. $dr = null;
  2414. }
  2415. if (!is_array($dr) || $dr === []) {
  2416. return $bundle;
  2417. }
  2418. $row = $dr;
  2419. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2420. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2421. $poRow = null;
  2422. if ($this->mprocIsValidScydgyRowId($sid)) {
  2423. try {
  2424. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2425. } catch (\Throwable $e) {
  2426. $poRow = null;
  2427. }
  2428. if (is_array($poRow)) {
  2429. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2430. }
  2431. }
  2432. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2433. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2434. if ($rowTab !== '' && $rowTab !== $tab) {
  2435. return $bundle;
  2436. }
  2437. $row['status_name'] = $effectiveSn;
  2438. $listTab = $rowTab;
  2439. $row['mproc_list_tab'] = $listTab;
  2440. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2441. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2442. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2443. if ($row['mproc_pick_result'] !== '') {
  2444. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2445. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2446. (int)$row['mproc_deadline_reached'] === 1
  2447. || (int)$row['mproc_bid_open_verified'] === 1
  2448. )) {
  2449. $row['mproc_done_label'] = '已截止';
  2450. } else {
  2451. $row['mproc_done_label'] = '';
  2452. }
  2453. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2454. $am = $row['amount'] ?? null;
  2455. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2456. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2457. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2458. $row['delivery_display'] = $m[1];
  2459. } elseif ($dv !== '') {
  2460. $row['delivery_display'] = $dv;
  2461. } else {
  2462. $row['delivery_display'] = '';
  2463. }
  2464. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2465. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2466. $this->mprocEnrichLeadDaysDisplay($row);
  2467. $this->mprocEnrichOrderDeadlineDisplay($row);
  2468. $row['mproc_fill_hint'] = '';
  2469. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2470. array_unshift($rows, $row);
  2471. $bundle['rows'] = $rows;
  2472. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2473. return $bundle;
  2474. }
  2475. /**
  2476. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2477. *
  2478. * @param array<string, mixed> $row
  2479. */
  2480. protected function mprocResolveDisplayThisQuantity(array $row): string
  2481. {
  2482. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2483. if ($qty !== '') {
  2484. return $qty;
  2485. }
  2486. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2487. if ($gzl === null || $gzl === '') {
  2488. return '';
  2489. }
  2490. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2491. }
  2492. /**
  2493. * 明细是否已填写单价或交货日期
  2494. *
  2495. * @param array<string, mixed> $row
  2496. */
  2497. protected function mprocDetailQuoteSubmitted(array $row): bool
  2498. {
  2499. $am = $row['amount'] ?? null;
  2500. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2501. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2502. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2503. return $amountFilled || $deliveryFilled;
  2504. }
  2505. /**
  2506. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2507. *
  2508. * @param array<string, mixed> $row
  2509. * @param array<string, mixed>|null $po
  2510. */
  2511. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2512. {
  2513. $sn = trim((string)($row['status_name'] ?? ''));
  2514. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2515. return $sn;
  2516. }
  2517. if (!is_array($po)) {
  2518. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2519. return '已提交';
  2520. }
  2521. if ($sn !== '') {
  2522. return $sn;
  2523. }
  2524. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2525. }
  2526. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2527. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2528. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2529. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2530. return '已提交';
  2531. }
  2532. if ($sn !== '') {
  2533. return $sn;
  2534. }
  2535. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2536. }
  2537. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2538. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2539. return '已完成';
  2540. }
  2541. if ($sn === '已提交') {
  2542. return '未通过';
  2543. }
  2544. return $sn !== '' ? $sn : '未提交';
  2545. }
  2546. /**
  2547. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2548. */
  2549. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2550. {
  2551. if ($detailId <= 0 || $statusNameCol === '') {
  2552. return;
  2553. }
  2554. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2555. if ($idCol === null || $idCol === '') {
  2556. return;
  2557. }
  2558. try {
  2559. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2560. } catch (\Throwable $e) {
  2561. }
  2562. }
  2563. /**
  2564. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2565. *
  2566. * @param array<string, mixed> $user
  2567. */
  2568. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2569. {
  2570. $userWhere = $this->mprocListWhereForLoginUser($user);
  2571. try {
  2572. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2573. if ($userWhere !== []) {
  2574. $query->where($userWhere);
  2575. }
  2576. $candidates = $query->limit(200)->select();
  2577. } catch (\Throwable $e) {
  2578. return;
  2579. }
  2580. if (!is_array($candidates) || $candidates === []) {
  2581. return;
  2582. }
  2583. $sidList = [];
  2584. foreach ($candidates as $cr) {
  2585. if (!is_array($cr)) {
  2586. continue;
  2587. }
  2588. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2589. if ($this->mprocIsValidScydgyRowId($sid)) {
  2590. $sidList[$sid] = true;
  2591. }
  2592. }
  2593. if ($sidList === []) {
  2594. return;
  2595. }
  2596. $poBySid = [];
  2597. try {
  2598. $poRows = Db::table('purchase_order')
  2599. ->where('scydgy_id', 'in', array_keys($sidList))
  2600. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2601. ->select();
  2602. if (is_array($poRows)) {
  2603. foreach ($poRows as $pr) {
  2604. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2605. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2606. $poBySid[$sidk] = $pr;
  2607. }
  2608. }
  2609. }
  2610. } catch (\Throwable $e) {
  2611. return;
  2612. }
  2613. if ($poBySid === []) {
  2614. return;
  2615. }
  2616. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2617. if ($idCol === null || $idCol === '') {
  2618. return;
  2619. }
  2620. foreach ($candidates as $cr) {
  2621. if (!is_array($cr)) {
  2622. continue;
  2623. }
  2624. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2625. if (!isset($poBySid[$sid])) {
  2626. continue;
  2627. }
  2628. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2629. if ($detailId <= 0) {
  2630. continue;
  2631. }
  2632. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2633. if ($targetSn === '已提交') {
  2634. continue;
  2635. }
  2636. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2637. }
  2638. }
  2639. /**
  2640. * 协助明细首页(需登录)
  2641. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2642. */
  2643. public function index()
  2644. {
  2645. $user = $this->mprocGetUser();
  2646. if (!$user) {
  2647. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2648. if ($pendingFocus > 0) {
  2649. $this->mprocRememberFocusEid($pendingFocus);
  2650. }
  2651. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2652. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2653. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2654. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2655. }
  2656. if ($safe !== '') {
  2657. Session::set('mproc_intended_url', $safe);
  2658. }
  2659. $this->redirect($this->mprocBuildLoginUrl($safe));
  2660. return;
  2661. }
  2662. // 管理员进对应业务页,不进供应商报价列表
  2663. if (!empty($user['is_admin'])) {
  2664. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  2665. if ($jump === '') {
  2666. $this->mprocDropCurrentLogin();
  2667. $this->redirect(url('index/index/login'));
  2668. return;
  2669. }
  2670. $this->redirect($jump);
  2671. return;
  2672. }
  2673. $user = $this->mprocSyncSessionCustomerUser($user);
  2674. $tabParamRaw = $this->request->get('tab', null);
  2675. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2676. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2677. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2678. // 旧地址 ?tab=me 表示「我的」
  2679. if ($tabParam === 'me') {
  2680. $mainTab = 'me';
  2681. }
  2682. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2683. $mainTab = 'orders';
  2684. }
  2685. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2686. $q = trim((string)$this->request->get('q', ''));
  2687. $mprocFocusEid = 0;
  2688. $focusEid = $this->mprocReadFocusEidFromRequest();
  2689. if ($focusEid > 0 && $mainTab === 'orders') {
  2690. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2691. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2692. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2693. Session::delete('mproc_focus_eid');
  2694. $focusEid = 0;
  2695. } else {
  2696. $mprocFocusEid = $focusEid;
  2697. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2698. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2699. if (!$focusFromUrl) {
  2700. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2701. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2702. }
  2703. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2704. if ($resolvedTab !== '') {
  2705. $tab = $resolvedTab;
  2706. }
  2707. }
  2708. }
  2709. }
  2710. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2711. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2712. $profile = $this->mprocProfileForUser($user);
  2713. $this->view->assign('mprocMainTab', $mainTab);
  2714. $this->view->assign('mprocTab', $tab);
  2715. $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
  2716. $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
  2717. $this->view->assign('mprocSearchQ', $q);
  2718. $this->view->assign('mprocProfile', $profile);
  2719. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2720. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2721. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2722. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2723. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2724. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2725. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2726. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2727. if ($mainTab === 'me') {
  2728. $this->view->assign('rows', []);
  2729. return $this->view->fetch();
  2730. }
  2731. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2732. if ($mprocFocusEid > 0) {
  2733. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2734. }
  2735. $this->view->assign('rows', $bundle['rows']);
  2736. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2737. return $this->view->fetch();
  2738. }
  2739. /**
  2740. * 协助明细列表 JSON(需登录)
  2741. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2742. */
  2743. public function mprocList()
  2744. {
  2745. $user = $this->mprocGetUser();
  2746. if (!$user) {
  2747. $this->error('请先登录', url('index/index/login'));
  2748. }
  2749. $user = $this->mprocSyncSessionCustomerUser($user);
  2750. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  2751. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  2752. if ($tabParam === 'me') {
  2753. $mainTab = 'me';
  2754. }
  2755. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2756. $mainTab = 'orders';
  2757. }
  2758. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2759. $q = trim((string)$this->request->request('q', ''));
  2760. if ($mainTab === 'me') {
  2761. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  2762. $this->success('ok', '', [
  2763. 'main_tab' => 'me',
  2764. 'tab' => $tab,
  2765. 'rows' => [],
  2766. 'profile' => $this->mprocProfileForUser($user),
  2767. 'done_no_status' => 0,
  2768. ]);
  2769. }
  2770. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2771. if ((int)$this->request->request('clear_focus', 0) === 1) {
  2772. Session::delete('mproc_focus_eid');
  2773. $focusEid = 0;
  2774. $focusTab = '';
  2775. } else {
  2776. $focusEid = $this->mprocReadFocusEidFromRequest();
  2777. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  2778. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  2779. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  2780. Session::delete('mproc_focus_eid');
  2781. $focusEid = 0;
  2782. $focusTab = '';
  2783. }
  2784. }
  2785. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2786. if ($focusEid > 0) {
  2787. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  2788. }
  2789. $this->success('ok', '', array_merge([
  2790. 'main_tab' => 'orders',
  2791. 'tab' => $tab,
  2792. 'focus_tab' => $focusTab,
  2793. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  2794. 'focus_eid' => $focusEid,
  2795. ], $bundle));
  2796. }
  2797. /**
  2798. * 登录页(手机号验证码 / 账号密码)
  2799. */
  2800. public function login()
  2801. {
  2802. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  2803. $user = $this->mprocGetUser();
  2804. if ($user) {
  2805. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2806. if ($jump !== '') {
  2807. $this->redirect($jump);
  2808. return;
  2809. }
  2810. // 已登录但无手机端权限(其它后台账号):清会话,避免登录页↔自身 302 死循环
  2811. $this->mprocDropCurrentLogin();
  2812. }
  2813. if ($redirect !== '') {
  2814. Session::set('mproc_intended_url', $redirect);
  2815. }
  2816. $this->view->assign('mprocLoginRedirect', $redirect);
  2817. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  2818. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  2819. return $this->view->fetch();
  2820. }
  2821. /**
  2822. * 图形验证码(手机号登录用)
  2823. */
  2824. public function captcha($id = '')
  2825. {
  2826. $captcha = new Captcha((array)Config::get('captcha'));
  2827. return $captcha->entry($id);
  2828. }
  2829. /**
  2830. * 发送登录验证码(POST:phone、captcha)
  2831. */
  2832. public function sendSms()
  2833. {
  2834. if (!$this->request->isPost()) {
  2835. $this->error('请使用 POST');
  2836. }
  2837. $phone = trim((string)$this->request->post('phone', ''));
  2838. $captcha = trim((string)$this->request->post('captcha', ''));
  2839. if (!preg_match('/^1\d{10}$/', $phone)) {
  2840. $this->error('请输入正确的11位手机号');
  2841. }
  2842. if ($captcha === '') {
  2843. $this->error('请输入图形验证码');
  2844. }
  2845. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2846. $adminRow = $cu ? null : $this->mprocAdminRowByMobile($phone);
  2847. if (!$cu && !$adminRow) {
  2848. $this->error('账号或密码错误');
  2849. }
  2850. if ($adminRow) {
  2851. $probe = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  2852. if (!$this->mprocAdminHasAnyMobileAccess($probe)) {
  2853. $this->error('账号或密码错误');
  2854. }
  2855. }
  2856. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  2857. if (Cache::get('mproc_sms_wait_' . $phone)) {
  2858. $this->error('发送过于频繁,请稍后再试');
  2859. }
  2860. if (!Validate::is($captcha, 'captcha')) {
  2861. $this->error('图形验证码不正确');
  2862. }
  2863. $code = (string)random_int(100000, 999999);
  2864. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  2865. $ttl = max(60, min(600, $ttl));
  2866. Cache::set('mproc_code_' . $phone, $code, $ttl);
  2867. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  2868. try {
  2869. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  2870. if ($tpl === '') {
  2871. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  2872. }
  2873. $content = str_replace('{code}', $code, $tpl);
  2874. $this->mprocSmsSend($phone, $content);
  2875. } catch (\Exception $e) {
  2876. Cache::rm('mproc_code_' . $phone);
  2877. Cache::rm('mproc_sms_wait_' . $phone);
  2878. $this->error($e->getMessage());
  2879. }
  2880. $this->success('验证码已发送');
  2881. }
  2882. /**
  2883. * 验证码登录(POST:phone、code)
  2884. */
  2885. public function doLogin()
  2886. {
  2887. if (!$this->request->isPost()) {
  2888. $this->error('请使用 POST');
  2889. }
  2890. $phone = trim((string)$this->request->post('phone', ''));
  2891. $code = trim((string)$this->request->post('code', ''));
  2892. if (!preg_match('/^1\d{10}$/', $phone)) {
  2893. $this->error('手机号格式不正确');
  2894. }
  2895. if (!preg_match('/^\d{6}$/', $code)) {
  2896. $this->error('请输入6位验证码');
  2897. }
  2898. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2899. $mock = Config::get('mproc.mock_sms_code');
  2900. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2901. Cache::rm('mproc_code_' . $phone);
  2902. } else {
  2903. $cached = Cache::get('mproc_code_' . $phone);
  2904. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2905. $this->error('验证码错误或已过期');
  2906. }
  2907. Cache::rm('mproc_code_' . $phone);
  2908. }
  2909. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2910. if ($cu) {
  2911. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2912. return;
  2913. }
  2914. $adminRow = $this->mprocAdminRowByMobile($phone);
  2915. if ($adminRow) {
  2916. $payload = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  2917. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  2918. $this->error('账号或密码错误');
  2919. }
  2920. $this->mprocFinishLogin($payload);
  2921. return;
  2922. }
  2923. $this->error('账号或密码错误');
  2924. }
  2925. /**
  2926. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2927. */
  2928. public function mprocRestore()
  2929. {
  2930. if (!$this->request->isPost()) {
  2931. $this->error('请使用 POST');
  2932. }
  2933. $token = $this->mprocReadTokenFromRequest();
  2934. $user = null;
  2935. if ($token !== '') {
  2936. $user = $this->mprocLoadUserByToken($token);
  2937. }
  2938. if (!$user) {
  2939. $user = $this->mprocUserFromRememberCookie();
  2940. if ($user) {
  2941. $token = $this->mprocPackSignedAuthToken($user);
  2942. }
  2943. }
  2944. if (!$user) {
  2945. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2946. }
  2947. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2948. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2949. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2950. if ($jump === '') {
  2951. $this->mprocClearLogin($token);
  2952. $this->error('账号或密码错误', url('index/index/login'));
  2953. }
  2954. $this->success('ok', $jump, [
  2955. 'mproc_token' => $token,
  2956. 'keep_hours' => $this->mprocKeepHours(),
  2957. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2958. ]);
  2959. }
  2960. /**
  2961. * 账号密码登录(POST:username、password)
  2962. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2963. */
  2964. public function doLoginPwd()
  2965. {
  2966. if (!$this->request->isPost()) {
  2967. $this->error('请使用 POST');
  2968. }
  2969. $username = trim((string)$this->request->post('username', ''));
  2970. $password = (string)$this->request->post('password', '');
  2971. if ($username === '' || $password === '') {
  2972. $this->error('请输入账号和密码');
  2973. }
  2974. $cu = $this->mprocFindCustomerUserByUsername($username);
  2975. if ($cu) {
  2976. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2977. $this->error('账号或密码错误');
  2978. }
  2979. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2980. }
  2981. // 管理员:表 admin
  2982. $row = null;
  2983. try {
  2984. $row = Db::name('admin')
  2985. ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
  2986. ->where('username', $username)
  2987. ->find();
  2988. } catch (\Throwable $e) {
  2989. $row = null;
  2990. }
  2991. if (!$row || !is_array($row)) {
  2992. $this->error('账号或密码错误');
  2993. }
  2994. $id = (int)($row['id'] ?? 0);
  2995. if (($row['status'] ?? '') == 'hidden') {
  2996. $this->error('该账号已禁用');
  2997. }
  2998. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  2999. $this->error('登录失败次数过多,请24小时后再试');
  3000. }
  3001. $salt = (string)($row['salt'] ?? '');
  3002. $hashStored = (string)($row['password'] ?? '');
  3003. $hashInput = md5(md5($password) . $salt);
  3004. if ($hashStored === '' || $hashInput !== $hashStored) {
  3005. if ($id > 0) {
  3006. try {
  3007. Db::name('admin')->where('id', $id)->update([
  3008. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  3009. 'updatetime' => time(),
  3010. ]);
  3011. } catch (\Throwable $e) {
  3012. }
  3013. }
  3014. $this->error('账号或密码错误');
  3015. }
  3016. if ($id > 0) {
  3017. try {
  3018. Db::name('admin')->where('id', $id)->update([
  3019. 'loginfailure' => 0,
  3020. 'updatetime' => time(),
  3021. ]);
  3022. } catch (\Throwable $e) {
  3023. }
  3024. }
  3025. $payload = $this->mprocLoginPayloadFromAdmin($row, 'pwd');
  3026. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3027. $this->error('账号或密码错误');
  3028. }
  3029. $this->mprocFinishLogin($payload);
  3030. }
  3031. /**
  3032. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  3033. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  3034. */
  3035. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  3036. {
  3037. if (!empty($user['is_admin'])) {
  3038. return false;
  3039. }
  3040. $sn = trim((string)($row['status_name'] ?? ''));
  3041. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  3042. return false;
  3043. }
  3044. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3045. // 手工询价无招标截止/开标限制
  3046. if ($sid >= 0) {
  3047. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  3048. return false;
  3049. }
  3050. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  3051. return false;
  3052. }
  3053. }
  3054. $uCo = trim((string)($user['company_name'] ?? ''));
  3055. if ($uCo === '') {
  3056. $uPhone = trim((string)($user['phone'] ?? ''));
  3057. if ($uPhone !== '') {
  3058. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  3059. }
  3060. }
  3061. $rCo = trim((string)($row['company_name'] ?? ''));
  3062. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  3063. return true;
  3064. }
  3065. $uPhone = trim((string)($user['phone'] ?? ''));
  3066. $rPhone = trim((string)($row['phone'] ?? ''));
  3067. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  3068. }
  3069. /**
  3070. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  3071. *
  3072. * @param array<string, mixed> $detailRow
  3073. */
  3074. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  3075. {
  3076. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  3077. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  3078. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  3079. try {
  3080. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3081. } catch (\Throwable $e) {
  3082. $po = null;
  3083. }
  3084. if (is_array($po)) {
  3085. $pl = array_change_key_case($po, CASE_LOWER);
  3086. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  3087. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  3088. $raw = trim((string)$pl[$ck]);
  3089. break;
  3090. }
  3091. }
  3092. if ($raw === '') {
  3093. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  3094. }
  3095. }
  3096. }
  3097. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  3098. return null;
  3099. }
  3100. return (float)$raw;
  3101. }
  3102. protected function mprocFormatCeilingPriceDisplay(float $n): string
  3103. {
  3104. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  3105. return $s === '' ? '0' : $s;
  3106. }
  3107. /**
  3108. * 确保 purchase_order_detail.lead_days 字段存在
  3109. */
  3110. protected function mprocEnsureLeadDaysColumn(): void
  3111. {
  3112. static $done = false;
  3113. if ($done) {
  3114. return;
  3115. }
  3116. $done = true;
  3117. try {
  3118. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  3119. if (empty($cols)) {
  3120. Db::execute(
  3121. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  3122. );
  3123. }
  3124. } catch (\Throwable $e) {
  3125. // 忽略:保存时再按列是否存在处理
  3126. }
  3127. }
  3128. /**
  3129. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  3130. */
  3131. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  3132. {
  3133. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  3134. return null;
  3135. }
  3136. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  3137. $t2 = strtotime($m[1] . ' 00:00:00');
  3138. if ($t1 === false || $t2 === false) {
  3139. return null;
  3140. }
  3141. return (int)round(($t2 - $t1) / 86400);
  3142. }
  3143. protected function mprocAddDaysToToday(int $days): string
  3144. {
  3145. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  3146. if ($base === false) {
  3147. $base = time();
  3148. }
  3149. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  3150. }
  3151. /**
  3152. * @param array<string, mixed> $row
  3153. */
  3154. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  3155. {
  3156. $days = null;
  3157. $raw = $row['lead_days'] ?? null;
  3158. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  3159. $days = max(0, (int)$raw);
  3160. } else {
  3161. $dd = trim((string)($row['delivery_display'] ?? ''));
  3162. if ($dd === '') {
  3163. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3164. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  3165. $dd = $m[1];
  3166. }
  3167. }
  3168. if ($dd !== '') {
  3169. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  3170. if ($calc !== null) {
  3171. $days = max(0, $calc);
  3172. }
  3173. }
  3174. }
  3175. if ($days !== null) {
  3176. $row['lead_days'] = $days;
  3177. $row['lead_days_display'] = (string)$days;
  3178. $row['lead_days_missing'] = 0;
  3179. } else {
  3180. $row['lead_days'] = '';
  3181. $row['lead_days_display'] = '';
  3182. $row['lead_days_missing'] = 1;
  3183. }
  3184. }
  3185. /**
  3186. * 保存单条协助明细的金额、交期、工期(内部)
  3187. *
  3188. * @param array<string, mixed> $user
  3189. * @param int $id
  3190. * @param string $amountRaw
  3191. * @param string $deliveryRaw
  3192. * @param string|int|null $leadDaysRaw
  3193. * @return string 工序名(用于批量错误提示)
  3194. */
  3195. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  3196. {
  3197. if ($id <= 0) {
  3198. throw new \InvalidArgumentException('参数错误');
  3199. }
  3200. $row = null;
  3201. try {
  3202. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  3203. if (!$row) {
  3204. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  3205. }
  3206. } catch (\Throwable $e) {
  3207. $row = null;
  3208. }
  3209. if (!$row || !is_array($row)) {
  3210. throw new \InvalidArgumentException('记录不存在');
  3211. }
  3212. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  3213. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3214. $po = null;
  3215. if ($this->mprocIsValidScydgyRowId($sid)) {
  3216. try {
  3217. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3218. } catch (\Throwable $e) {
  3219. $po = null;
  3220. }
  3221. if (is_array($po)) {
  3222. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3223. if ($gymc === '') {
  3224. $gymc = trim((string)($row['CGYMC'] ?? ''));
  3225. }
  3226. }
  3227. }
  3228. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  3229. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3230. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3231. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  3232. }
  3233. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  3234. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3235. if (!empty($user['is_admin'])) {
  3236. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  3237. }
  3238. // 截止后 / 已开标 canEdit=false,统一给明确文案
  3239. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3240. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  3241. }
  3242. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3243. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  3244. }
  3245. throw new \InvalidArgumentException($label . '无权修改');
  3246. }
  3247. $this->mprocEnsureLeadDaysColumn();
  3248. $amountRaw = trim($amountRaw);
  3249. $deliveryRaw = trim($deliveryRaw);
  3250. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  3251. $hasAmt = $amountRaw !== '';
  3252. $hasLead = $leadRaw !== '';
  3253. $hasDel = $deliveryRaw !== '';
  3254. $isManualRfq = ($sid < 0);
  3255. if ($isManualRfq) {
  3256. // 手工询价:只需填写单价
  3257. if (!$hasAmt) {
  3258. throw new \InvalidArgumentException($label . '请填写单价');
  3259. }
  3260. } else {
  3261. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  3262. if ($filledCount === 0) {
  3263. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  3264. }
  3265. if ($filledCount < 3) {
  3266. if (!$hasAmt) {
  3267. throw new \InvalidArgumentException($label . '请填写单价');
  3268. }
  3269. if (!$hasLead) {
  3270. throw new \InvalidArgumentException($label . '请填写工期');
  3271. }
  3272. throw new \InvalidArgumentException($label . '请填写交期');
  3273. }
  3274. }
  3275. $leadDays = null;
  3276. if ($leadRaw !== '') {
  3277. if (!preg_match('/^\d+$/', $leadRaw)) {
  3278. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  3279. }
  3280. $leadDays = (int)$leadRaw;
  3281. }
  3282. $data = [];
  3283. if ($amountRaw === '') {
  3284. $data['amount'] = null;
  3285. } else {
  3286. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  3287. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  3288. }
  3289. if ((float)$amountRaw <= 0) {
  3290. throw new \InvalidArgumentException($label . '单价必须大于0');
  3291. }
  3292. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  3293. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  3294. throw new \InvalidArgumentException(
  3295. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  3296. );
  3297. }
  3298. $data['amount'] = $amountRaw;
  3299. }
  3300. if ($deliveryRaw === '') {
  3301. $data['delivery'] = null;
  3302. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  3303. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3304. $timePart = date('H:i:s');
  3305. if ($existingDel !== '') {
  3306. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  3307. if ($tsEx !== false) {
  3308. $hms = date('H:i:s', $tsEx);
  3309. if ($hms !== '00:00:00') {
  3310. $timePart = $hms;
  3311. }
  3312. }
  3313. }
  3314. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  3315. } else {
  3316. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  3317. $ts = strtotime($deliveryRaw);
  3318. if ($ts === false) {
  3319. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  3320. }
  3321. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  3322. }
  3323. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  3324. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  3325. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  3326. }
  3327. if ($leadDays === null && !empty($data['delivery'])) {
  3328. $ymd = substr((string)$data['delivery'], 0, 10);
  3329. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  3330. if ($calc !== null) {
  3331. $leadDays = max(0, $calc);
  3332. }
  3333. }
  3334. $data['lead_days'] = $leadDays;
  3335. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  3336. if ($dcCol !== null) {
  3337. $shouldStampQuoteTime = false;
  3338. if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  3339. $shouldStampQuoteTime = true;
  3340. }
  3341. // 手工询价只填单价:有单价也记报价时间
  3342. if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
  3343. $shouldStampQuoteTime = true;
  3344. }
  3345. if ($shouldStampQuoteTime) {
  3346. $data[$dcCol] = date('Y-m-d H:i:s');
  3347. }
  3348. }
  3349. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3350. if ($upCol !== null) {
  3351. $data[$upCol] = date('Y-m-d H:i:s');
  3352. }
  3353. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3354. if ($statusNameCol !== null) {
  3355. $curSn = '';
  3356. foreach ($row as $k => $v) {
  3357. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  3358. $curSn = trim((string)$v);
  3359. break;
  3360. }
  3361. }
  3362. if ($curSn !== '已完成') {
  3363. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  3364. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  3365. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  3366. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  3367. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3368. }
  3369. }
  3370. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3371. $pkVal = (int)($row[$pkField] ?? $id);
  3372. try {
  3373. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3374. } catch (\Throwable $e) {
  3375. $msg = $e->getMessage();
  3376. if (stripos($msg, 'Unknown column') !== false) {
  3377. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3378. }
  3379. throw new \RuntimeException('保存失败:' . $msg);
  3380. }
  3381. if ($aff === false) {
  3382. throw new \RuntimeException($label . '保存失败');
  3383. }
  3384. return $gymc;
  3385. }
  3386. /**
  3387. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3388. *
  3389. * @param array<string, mixed> $user
  3390. * @param int[] $detailIds 本次保存涉及的明细 ID
  3391. * @param string $remarkRaw
  3392. */
  3393. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3394. {
  3395. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3396. if ($remarkCol === null) {
  3397. return;
  3398. }
  3399. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3400. if ($detailIds === []) {
  3401. return;
  3402. }
  3403. $anchorId = $detailIds[0];
  3404. $row = null;
  3405. try {
  3406. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3407. if (!$row) {
  3408. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3409. }
  3410. } catch (\Throwable $e) {
  3411. $row = null;
  3412. }
  3413. if (!$row || !is_array($row)) {
  3414. throw new \InvalidArgumentException('记录不存在');
  3415. }
  3416. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3417. $po = null;
  3418. if ($this->mprocIsValidScydgyRowId($sid)) {
  3419. try {
  3420. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3421. } catch (\Throwable $e) {
  3422. $po = null;
  3423. }
  3424. if (is_array($po)) {
  3425. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3426. }
  3427. }
  3428. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3429. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3430. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3431. }
  3432. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3433. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3434. if (!empty($user['is_admin'])) {
  3435. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3436. }
  3437. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3438. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3439. }
  3440. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3441. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3442. }
  3443. throw new \InvalidArgumentException('无权修改备注');
  3444. }
  3445. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3446. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3447. if ($ccydhCol === null || $companyCol === null) {
  3448. return;
  3449. }
  3450. $ccydh = '';
  3451. $company = '';
  3452. foreach ($row as $k => $v) {
  3453. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3454. $ccydh = trim((string)$v);
  3455. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3456. $company = trim((string)$v);
  3457. }
  3458. }
  3459. if ($ccydh === '' || $company === '') {
  3460. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3461. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3462. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3463. if ($upCol !== null) {
  3464. $data[$upCol] = date('Y-m-d H:i:s');
  3465. }
  3466. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3467. return;
  3468. }
  3469. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3470. $data = [$remarkCol => $remarkVal];
  3471. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3472. if ($upCol !== null) {
  3473. $data[$upCol] = date('Y-m-d H:i:s');
  3474. }
  3475. $query = Db::table('purchase_order_detail')
  3476. ->where($ccydhCol, $ccydh)
  3477. ->where($companyCol, $company);
  3478. $userWhere = $this->mprocListWhereForLoginUser($user);
  3479. if ($userWhere !== []) {
  3480. $query->where($userWhere);
  3481. }
  3482. try {
  3483. $query->update($data);
  3484. } catch (\Throwable $e) {
  3485. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3486. }
  3487. }
  3488. /**
  3489. * 保存协助明细金额、交期、工期
  3490. * 单条:POST id、amount、delivery、lead_days
  3491. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3492. */
  3493. public function mprocSave()
  3494. {
  3495. if (!$this->request->isPost()) {
  3496. $this->error('请使用 POST');
  3497. }
  3498. $user = $this->mprocGetUser();
  3499. if (!$user) {
  3500. $this->error('请先登录', url('index/index/login'));
  3501. }
  3502. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3503. $itemsRaw = $this->request->post('items', '', null);
  3504. if ($itemsRaw === '' || $itemsRaw === null) {
  3505. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3506. }
  3507. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3508. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3509. }
  3510. $items = [];
  3511. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3512. $decoded = json_decode($itemsRaw, true);
  3513. if (!is_array($decoded)) {
  3514. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3515. }
  3516. if (is_array($decoded)) {
  3517. $items = $decoded;
  3518. }
  3519. } elseif (is_array($itemsRaw)) {
  3520. $items = $itemsRaw;
  3521. }
  3522. if ($items === []) {
  3523. $id = (int)$this->request->post('id', 0, null);
  3524. if ($id <= 0) {
  3525. $this->error('保存失败,请关闭弹窗后重试');
  3526. }
  3527. $items = [[
  3528. 'id' => $id,
  3529. 'amount' => (string)$this->request->post('amount', '', null),
  3530. 'delivery' => (string)$this->request->post('delivery', '', null),
  3531. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3532. ]];
  3533. }
  3534. $saved = 0;
  3535. $savedIds = [];
  3536. $remarkRaw = $this->request->post('remark', '', null);
  3537. if ($remarkRaw === '' || $remarkRaw === null) {
  3538. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3539. }
  3540. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3541. Db::startTrans();
  3542. try {
  3543. foreach ($items as $it) {
  3544. if (!is_array($it)) {
  3545. continue;
  3546. }
  3547. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3548. if ($id <= 0) {
  3549. continue;
  3550. }
  3551. $delivery = (string)($it['delivery'] ?? '');
  3552. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3553. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3554. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3555. }
  3556. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3557. $amount = trim((string)($it['amount'] ?? ''));
  3558. $leadDays = trim($leadDays);
  3559. $delivery = trim($delivery);
  3560. // 全空工序跳过:多工序时允许只保存已填全的
  3561. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3562. continue;
  3563. }
  3564. $this->mprocSaveDetailQuote(
  3565. $user,
  3566. $id,
  3567. $amount,
  3568. $delivery,
  3569. $leadDays
  3570. );
  3571. $saved++;
  3572. $savedIds[] = $id;
  3573. }
  3574. if ($saved < 1) {
  3575. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3576. }
  3577. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3578. Db::commit();
  3579. } catch (\InvalidArgumentException $e) {
  3580. Db::rollback();
  3581. $this->error($e->getMessage());
  3582. } catch (\Throwable $e) {
  3583. Db::rollback();
  3584. $this->error($e->getMessage());
  3585. }
  3586. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3587. }
  3588. /**
  3589. * 修改密码(POST:old_password、new_password、renew_password)
  3590. * 支持供应商 customer 与手机端管理员 admin
  3591. */
  3592. public function mprocChangePwd()
  3593. {
  3594. if (!$this->request->isPost()) {
  3595. $this->error('请使用 POST');
  3596. }
  3597. $user = $this->mprocGetUser();
  3598. if (!$user) {
  3599. $this->error('请先登录', url('index/index/login'));
  3600. }
  3601. $oldPwd = (string)$this->request->post('old_password', '');
  3602. $newPwd = (string)$this->request->post('new_password', '');
  3603. $renewPwd = (string)$this->request->post('renew_password', '');
  3604. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3605. $this->error('请填写完整');
  3606. }
  3607. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3608. if ($pwdErr !== '') {
  3609. $this->error($pwdErr);
  3610. }
  3611. if ($newPwd !== $renewPwd) {
  3612. $this->error('两次输入的新密码不一致');
  3613. }
  3614. if ($oldPwd === $newPwd) {
  3615. $this->error('新密码不能与旧密码相同');
  3616. }
  3617. if (!empty($user['is_admin'])) {
  3618. $adminId = (int)($user['admin_id'] ?? 0);
  3619. if ($adminId <= 0) {
  3620. $this->error('账号不存在或已禁用');
  3621. }
  3622. $row = null;
  3623. try {
  3624. $row = Db::name('admin')
  3625. ->field('id,username,password,salt,status')
  3626. ->where('id', $adminId)
  3627. ->find();
  3628. } catch (\Throwable $e) {
  3629. $row = null;
  3630. }
  3631. if (!$row || !is_array($row) || (($row['status'] ?? '') === 'hidden')) {
  3632. $this->error('账号不存在或已禁用');
  3633. }
  3634. $salt = (string)($row['salt'] ?? '');
  3635. $hashStored = (string)($row['password'] ?? '');
  3636. $hashOld = md5(md5($oldPwd) . $salt);
  3637. if ($hashStored === '' || $hashOld !== $hashStored) {
  3638. $this->error('原密码不正确');
  3639. }
  3640. $hashNew = md5(md5($newPwd) . $salt);
  3641. try {
  3642. Db::name('admin')->where('id', $adminId)->update([
  3643. 'password' => $hashNew,
  3644. 'updatetime' => time(),
  3645. ]);
  3646. } catch (\Throwable $e) {
  3647. $this->error('修改失败:' . $e->getMessage());
  3648. }
  3649. } else {
  3650. $user = $this->mprocSyncSessionCustomerUser($user);
  3651. $cu = $this->mprocResolveCustomerUserForSession($user);
  3652. if (!$cu) {
  3653. $this->error('账号不存在或已禁用');
  3654. }
  3655. $cuId = (int)($cu['id'] ?? 0);
  3656. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3657. $this->error('原密码不正确');
  3658. }
  3659. $data = [
  3660. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3661. 'updatetime' => date('Y-m-d H:i:s'),
  3662. ];
  3663. try {
  3664. Db::table('customer')->where('id', $cuId)->update($data);
  3665. } catch (\Throwable $e) {
  3666. $this->error('修改失败:' . $e->getMessage());
  3667. }
  3668. }
  3669. // 改密后强制重新登录
  3670. $token = Session::get('mproc_token');
  3671. if ($token === null || $token === '') {
  3672. $token = Cookie::get('mproc_token');
  3673. }
  3674. if ($token === null || $token === '') {
  3675. $token = Cookie::get('mproc_remember');
  3676. }
  3677. $this->mprocClearLogin((string)$token);
  3678. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3679. }
  3680. /**
  3681. * 退出登录
  3682. */
  3683. public function logout()
  3684. {
  3685. $token = Session::get('mproc_token');
  3686. if ($token === null || $token === '') {
  3687. $token = Cookie::get('mproc_token');
  3688. }
  3689. if ($token === null || $token === '') {
  3690. $token = Cookie::get('mproc_remember');
  3691. }
  3692. // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
  3693. $this->mprocClearLogin((string)$token);
  3694. $this->redirect(url('index/index/login'));
  3695. }
  3696. /**
  3697. * 短信宝(与后台协助审核一致,便于复用账号)
  3698. *
  3699. * @throws \Exception
  3700. */
  3701. protected function mprocSmsSend($phone, $content)
  3702. {
  3703. $statusStr = [
  3704. '0' => '短信发送成功',
  3705. '-1' => '参数不全',
  3706. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3707. '30' => '密码错误',
  3708. '40' => '账号不存在',
  3709. '41' => '余额不足',
  3710. '42' => '帐户已过期',
  3711. '43' => 'IP地址限制',
  3712. '50' => '内容含有敏感词',
  3713. ];
  3714. $smsapi = 'http://api.smsbao.com/';
  3715. $user = trim((string)Config::get('mproc.smsbao_user'));
  3716. if ($user === '') {
  3717. $user = 'zhuwei123';
  3718. }
  3719. $passPlain = Config::get('mproc.smsbao_pass');
  3720. $pass = ($passPlain !== null && $passPlain !== '')
  3721. ? md5((string)$passPlain)
  3722. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3723. $phone = trim((string)$phone);
  3724. $content = trim((string)$content);
  3725. if ($phone === '' || $content === '') {
  3726. throw new \Exception('短信发送失败:参数不全');
  3727. }
  3728. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3729. $result = @file_get_contents($sendurl);
  3730. if ($result === false) {
  3731. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3732. throw new \Exception('短信发送失败:网络异常');
  3733. }
  3734. $result = trim((string)$result);
  3735. if ($result !== '0') {
  3736. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3737. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3738. throw new \Exception('短信发送失败:' . $msg);
  3739. }
  3740. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3741. }
  3742. /**
  3743. * 质量评分页(质检中心:合格/投诉/中断)
  3744. */
  3745. public function inboundscore()
  3746. {
  3747. $user = $this->mprocGetUser();
  3748. if (!$user) {
  3749. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3750. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3751. if ($safe !== '') {
  3752. Session::set('mproc_intended_url', $safe);
  3753. }
  3754. $this->redirect($this->mprocBuildLoginUrl($safe));
  3755. return;
  3756. }
  3757. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'quality')) {
  3758. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  3759. if ($jump === '') {
  3760. $this->mprocDropCurrentLogin();
  3761. $this->redirect(url('index/index/login'));
  3762. return;
  3763. }
  3764. $this->redirect($jump);
  3765. return;
  3766. }
  3767. $this->mprocEnsureInboundScoreTable();
  3768. $q = trim((string)$this->request->get('q', ''));
  3769. $profile = $this->mprocProfileForUser($user);
  3770. $this->view->assign('mprocSearchQ', $q);
  3771. $this->view->assign('mprocProfile', $profile);
  3772. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3773. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3774. $this->view->assign('mprocScoreScope', 'quality');
  3775. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'quality'));
  3776. return $this->view->fetch();
  3777. }
  3778. /**
  3779. * 交货情况页(生产部:准时/滞后)
  3780. */
  3781. public function deliveryscore()
  3782. {
  3783. $user = $this->mprocGetUser();
  3784. if (!$user) {
  3785. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3786. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3787. if ($safe !== '') {
  3788. Session::set('mproc_intended_url', $safe);
  3789. }
  3790. $this->redirect($this->mprocBuildLoginUrl($safe));
  3791. return;
  3792. }
  3793. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'delivery')) {
  3794. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  3795. if ($jump === '') {
  3796. $this->mprocDropCurrentLogin();
  3797. $this->redirect(url('index/index/login'));
  3798. return;
  3799. }
  3800. $this->redirect($jump);
  3801. return;
  3802. }
  3803. $this->mprocEnsureInboundScoreTable();
  3804. $q = trim((string)$this->request->get('q', ''));
  3805. $profile = $this->mprocProfileForUser($user);
  3806. $this->view->assign('mprocSearchQ', $q);
  3807. $this->view->assign('mprocProfile', $profile);
  3808. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3809. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3810. $this->view->assign('mprocScoreScope', 'delivery');
  3811. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'delivery'));
  3812. return $this->view->fetch();
  3813. }
  3814. /**
  3815. * 质量评分列表 JSON(质检;tab=pending|scored)
  3816. */
  3817. public function inboundscorelist()
  3818. {
  3819. $user = $this->mprocRequireQualityUser();
  3820. $this->mprocEnsureInboundScoreTable();
  3821. $q = trim((string)$this->request->request('q', ''));
  3822. $tab = trim((string)$this->request->request('tab', 'pending'));
  3823. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  3824. $tab = 'pending';
  3825. }
  3826. if ($tab === 'pass' || $tab === 'fail') {
  3827. $tab = 'scored';
  3828. }
  3829. $adminId = (int)($user['admin_id'] ?? 0);
  3830. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'quality');
  3831. $this->success('ok', '', [
  3832. 'tab' => $tab,
  3833. 'q' => $q,
  3834. 'scope' => 'quality',
  3835. 'rows' => $rows,
  3836. 'count' => count($rows),
  3837. ]);
  3838. }
  3839. /**
  3840. * 交货情况列表 JSON(生产部;tab=pending|scored)
  3841. */
  3842. public function deliveryscorelist()
  3843. {
  3844. $user = $this->mprocRequireDeliveryUser();
  3845. $this->mprocEnsureInboundScoreTable();
  3846. $q = trim((string)$this->request->request('q', ''));
  3847. $tab = trim((string)$this->request->request('tab', 'pending'));
  3848. if (!in_array($tab, ['pending', 'scored'], true)) {
  3849. $tab = 'pending';
  3850. }
  3851. $adminId = (int)($user['admin_id'] ?? 0);
  3852. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'delivery');
  3853. $this->success('ok', '', [
  3854. 'tab' => $tab,
  3855. 'q' => $q,
  3856. 'scope' => 'delivery',
  3857. 'rows' => $rows,
  3858. 'count' => count($rows),
  3859. ]);
  3860. }
  3861. /**
  3862. * 保存质量评分(质检中心)
  3863. * POST:ccydh、result、order_interrupt、remark
  3864. * 客诉事后由 inboundscorecomplaint 补登,首次默认否
  3865. */
  3866. public function inboundscoresave()
  3867. {
  3868. $user = $this->mprocRequireQualityUser();
  3869. if (!$this->request->isPost()) {
  3870. $this->error('请使用 POST');
  3871. }
  3872. $this->mprocEnsureInboundScoreTable();
  3873. $ccydh = trim((string)$this->request->post('ccydh', ''));
  3874. $sid = (int)$this->request->post('scydgy_id', 0);
  3875. $result = trim((string)$this->request->post('result', ''));
  3876. if ($result !== '合格' && $result !== '不合格') {
  3877. $this->error('请选择生产是否合格');
  3878. }
  3879. $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
  3880. if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
  3881. $this->error('请选择生产是否中断');
  3882. }
  3883. $remark = trim((string)$this->request->post('remark', ''));
  3884. if ($result === '不合格' && $remark === '') {
  3885. $this->error('请填写不合格原因');
  3886. }
  3887. if (mb_strlen($remark) > 500) {
  3888. $remark = mb_substr($remark, 0, 500);
  3889. }
  3890. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  3891. $now = date('Y-m-d H:i:s');
  3892. $adminId = (int)($user['admin_id'] ?? 0);
  3893. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  3894. $saved = 0;
  3895. $firstSid = 0;
  3896. $firstPoId = 0;
  3897. $deliveryReady = true;
  3898. try {
  3899. Db::startTrans();
  3900. foreach ($poRows as $po) {
  3901. if (!is_array($po)) {
  3902. continue;
  3903. }
  3904. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3905. if ($rowSid <= 0) {
  3906. continue;
  3907. }
  3908. if ($firstSid <= 0) {
  3909. $firstSid = $rowSid;
  3910. $firstPoId = (int)($po['id'] ?? 0);
  3911. }
  3912. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  3913. $existDs = is_array($exist) ? trim((string)($exist['delivery_status'] ?? '')) : '';
  3914. if ($existDs !== '准时' && $existDs !== '滞后') {
  3915. $deliveryReady = false;
  3916. }
  3917. $data = [
  3918. 'scydgy_id' => $rowSid,
  3919. 'purchase_order_id' => (int)($po['id'] ?? 0),
  3920. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  3921. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  3922. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  3923. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3924. 'result' => $result,
  3925. 'order_interrupt' => $orderInterrupt,
  3926. 'remark' => $remark,
  3927. 'admin_id' => $adminId,
  3928. 'admin_name' => $adminName,
  3929. 'updatetime' => $now,
  3930. ];
  3931. if (is_array($exist) && $exist !== []) {
  3932. // 客诉事后补登,首次评分不覆盖已有客诉
  3933. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  3934. } else {
  3935. $data['customer_complaint'] = 0;
  3936. $data['complaint_remark'] = '';
  3937. $data['delivery_status'] = '';
  3938. $data['createtime'] = $now;
  3939. Db::table('purchase_order_inbound_score')->insert($data);
  3940. $deliveryReady = false;
  3941. }
  3942. $saved++;
  3943. }
  3944. if ($saved < 1) {
  3945. throw new \RuntimeException('没有可保存的工序');
  3946. }
  3947. if ($deliveryReady) {
  3948. foreach ($poRows as $po) {
  3949. if (!is_array($po)) {
  3950. continue;
  3951. }
  3952. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3953. if ($rowSid > 0) {
  3954. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  3955. 'status' => ProcuremenStatus::PO_COMPLETED,
  3956. ]);
  3957. }
  3958. }
  3959. }
  3960. Db::commit();
  3961. } catch (\Throwable $e) {
  3962. try {
  3963. Db::rollback();
  3964. } catch (\Throwable $e2) {
  3965. }
  3966. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  3967. $this->error('保存失败,请稍后重试');
  3968. }
  3969. $logDetail = '质量评分:生产是否合格=' . $result
  3970. . ';生产是否中断:' . ($orderInterrupt === 1 ? '是' : '否');
  3971. if ($remark !== '') {
  3972. $logDetail .= ';备注:' . $remark;
  3973. }
  3974. \app\common\library\ProcuremenOperLog::write(
  3975. $firstSid,
  3976. 'inbound_score',
  3977. $logDetail,
  3978. $firstPoId > 0 ? $firstPoId : null,
  3979. [$adminId, $adminName]
  3980. );
  3981. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  3982. $this->success('操作成功', '', [
  3983. 'ccydh' => $ccydh,
  3984. 'result' => $result,
  3985. 'order_interrupt' => $orderInterrupt,
  3986. 'remark' => $remark,
  3987. 'count' => $saved,
  3988. 'completed' => $deliveryReady ? 1 : 0,
  3989. ]);
  3990. }
  3991. /**
  3992. * 事后投诉反馈(质检中心,仅已质量评分订单)
  3993. * POST:ccydh、customer_complaint=0|1、complaint_remark(投诉为是时必填)
  3994. */
  3995. public function inboundscorecomplaint()
  3996. {
  3997. $user = $this->mprocRequireQualityUser();
  3998. if (!$this->request->isPost()) {
  3999. $this->error('请使用 POST');
  4000. }
  4001. $this->mprocEnsureInboundScoreTable();
  4002. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4003. $sid = (int)$this->request->post('scydgy_id', 0);
  4004. $customerComplaint = (int)$this->request->post('customer_complaint', -1);
  4005. if ($customerComplaint !== 0 && $customerComplaint !== 1) {
  4006. $this->error('请选择客户是否投诉');
  4007. }
  4008. $complaintRemark = trim((string)$this->request->post('complaint_remark', ''));
  4009. if ($customerComplaint === 1 && $complaintRemark === '') {
  4010. $this->error('请填写投诉说明');
  4011. }
  4012. if ($customerComplaint !== 1) {
  4013. $complaintRemark = '';
  4014. }
  4015. if (mb_strlen($complaintRemark) > 500) {
  4016. $complaintRemark = mb_substr($complaintRemark, 0, 500);
  4017. }
  4018. if ($ccydh === '' && $sid > 0) {
  4019. try {
  4020. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4021. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4022. } catch (\Throwable $e) {
  4023. $ccydh = '';
  4024. }
  4025. }
  4026. if ($ccydh === '') {
  4027. $this->error('缺少订单号');
  4028. }
  4029. try {
  4030. $scoreRows = Db::table('purchase_order_inbound_score')
  4031. ->where('ccydh', $ccydh)
  4032. ->field('id,scydgy_id,purchase_order_id,result,company_name')
  4033. ->select();
  4034. } catch (\Throwable $e) {
  4035. $scoreRows = [];
  4036. }
  4037. if (!is_array($scoreRows) || $scoreRows === []) {
  4038. $this->error('请先完成质量评分后再投诉反馈');
  4039. }
  4040. $hasQuality = false;
  4041. foreach ($scoreRows as $sc) {
  4042. if (!is_array($sc)) {
  4043. continue;
  4044. }
  4045. $res = trim((string)($sc['result'] ?? ''));
  4046. if ($res === '合格' || $res === '不合格') {
  4047. $hasQuality = true;
  4048. break;
  4049. }
  4050. }
  4051. if (!$hasQuality) {
  4052. $this->error('请先完成质量评分后再投诉反馈');
  4053. }
  4054. $now = date('Y-m-d H:i:s');
  4055. $adminId = (int)($user['admin_id'] ?? 0);
  4056. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4057. $firstSid = 0;
  4058. $firstPoId = 0;
  4059. $companyName = '';
  4060. $updated = 0;
  4061. try {
  4062. Db::startTrans();
  4063. foreach ($scoreRows as $sc) {
  4064. if (!is_array($sc)) {
  4065. continue;
  4066. }
  4067. $rowSid = (int)($sc['scydgy_id'] ?? 0);
  4068. $id = (int)($sc['id'] ?? 0);
  4069. if ($id <= 0) {
  4070. continue;
  4071. }
  4072. if ($firstSid <= 0 && $rowSid > 0) {
  4073. $firstSid = $rowSid;
  4074. $firstPoId = (int)($sc['purchase_order_id'] ?? 0);
  4075. }
  4076. if ($companyName === '') {
  4077. $companyName = trim((string)($sc['company_name'] ?? ''));
  4078. }
  4079. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  4080. 'customer_complaint' => $customerComplaint,
  4081. 'complaint_remark' => $complaintRemark,
  4082. 'updatetime' => $now,
  4083. ]);
  4084. $updated++;
  4085. }
  4086. if ($updated < 1) {
  4087. throw new \RuntimeException('没有可更新的记录');
  4088. }
  4089. Db::commit();
  4090. } catch (\Throwable $e) {
  4091. try {
  4092. Db::rollback();
  4093. } catch (\Throwable $e2) {
  4094. }
  4095. Log::record('inboundscorecomplaint fail: ' . $e->getMessage(), 'error');
  4096. $this->error('保存失败,请稍后重试');
  4097. }
  4098. if ($firstSid > 0) {
  4099. $logDetail = '投诉反馈:客户投诉=' . ($customerComplaint === 1 ? '是' : '否');
  4100. if ($complaintRemark !== '') {
  4101. $logDetail .= ';投诉说明:' . $complaintRemark;
  4102. }
  4103. \app\common\library\ProcuremenOperLog::write(
  4104. $firstSid,
  4105. 'inbound_score',
  4106. $logDetail,
  4107. $firstPoId > 0 ? $firstPoId : null,
  4108. [$adminId, $adminName]
  4109. );
  4110. }
  4111. if ($companyName !== '') {
  4112. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4113. try {
  4114. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4115. } catch (\Throwable $e) {
  4116. Log::record('inboundscorecomplaint quality sync: ' . $e->getMessage(), 'error');
  4117. }
  4118. }
  4119. $this->success('操作成功', '', [
  4120. 'ccydh' => $ccydh,
  4121. 'customer_complaint' => $customerComplaint,
  4122. 'complaint_remark' => $complaintRemark,
  4123. 'count' => $updated,
  4124. ]);
  4125. }
  4126. /**
  4127. * 保存交货情况(生产部)
  4128. * POST:ccydh、delivery_status=准时|滞后、delivery_date=YYYY-MM-DD
  4129. */
  4130. public function deliveryscoresave()
  4131. {
  4132. $user = $this->mprocRequireDeliveryUser();
  4133. if (!$this->request->isPost()) {
  4134. $this->error('请使用 POST');
  4135. }
  4136. $this->mprocEnsureInboundScoreTable();
  4137. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4138. $sid = (int)$this->request->post('scydgy_id', 0);
  4139. $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
  4140. if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
  4141. $this->error('请选择交货情况');
  4142. }
  4143. $deliveryDate = trim((string)$this->request->post('delivery_date', ''));
  4144. if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) {
  4145. $this->error('请选择交货日期');
  4146. }
  4147. $ts = strtotime($deliveryDate . ' 00:00:00');
  4148. if ($ts === false) {
  4149. $this->error('交货日期格式不正确');
  4150. }
  4151. $deliveryDate = date('Y-m-d', $ts);
  4152. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  4153. $now = date('Y-m-d H:i:s');
  4154. $adminId = (int)($user['admin_id'] ?? 0);
  4155. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4156. $saved = 0;
  4157. $firstSid = 0;
  4158. $firstPoId = 0;
  4159. $qualityReady = true;
  4160. try {
  4161. Db::startTrans();
  4162. foreach ($poRows as $po) {
  4163. if (!is_array($po)) {
  4164. continue;
  4165. }
  4166. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4167. if ($rowSid <= 0) {
  4168. continue;
  4169. }
  4170. if ($firstSid <= 0) {
  4171. $firstSid = $rowSid;
  4172. $firstPoId = (int)($po['id'] ?? 0);
  4173. }
  4174. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4175. $existResult = is_array($exist) ? trim((string)($exist['result'] ?? '')) : '';
  4176. if ($existResult !== '合格' && $existResult !== '不合格') {
  4177. $qualityReady = false;
  4178. }
  4179. $data = [
  4180. 'scydgy_id' => $rowSid,
  4181. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4182. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4183. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4184. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4185. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4186. 'delivery_status' => $deliveryStatus,
  4187. 'delivery_date' => $deliveryDate,
  4188. 'updatetime' => $now,
  4189. ];
  4190. if (is_array($exist) && $exist !== []) {
  4191. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4192. } else {
  4193. $data['result'] = '';
  4194. $data['customer_complaint'] = 0;
  4195. $data['complaint_remark'] = '';
  4196. $data['order_interrupt'] = 0;
  4197. $data['remark'] = '';
  4198. $data['admin_id'] = $adminId;
  4199. $data['admin_name'] = $adminName;
  4200. $data['createtime'] = $now;
  4201. Db::table('purchase_order_inbound_score')->insert($data);
  4202. $qualityReady = false;
  4203. }
  4204. $saved++;
  4205. }
  4206. if ($saved < 1) {
  4207. throw new \RuntimeException('没有可保存的工序');
  4208. }
  4209. if ($qualityReady) {
  4210. foreach ($poRows as $po) {
  4211. if (!is_array($po)) {
  4212. continue;
  4213. }
  4214. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4215. if ($rowSid > 0) {
  4216. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4217. 'status' => ProcuremenStatus::PO_COMPLETED,
  4218. ]);
  4219. }
  4220. }
  4221. }
  4222. Db::commit();
  4223. } catch (\Throwable $e) {
  4224. try {
  4225. Db::rollback();
  4226. } catch (\Throwable $e2) {
  4227. }
  4228. Log::record('deliveryscoresave fail: ' . $e->getMessage(), 'error');
  4229. $this->error('保存失败,请稍后重试');
  4230. }
  4231. \app\common\library\ProcuremenOperLog::write(
  4232. $firstSid,
  4233. 'inbound_score',
  4234. '交货情况:' . $deliveryStatus . ';交货日期:' . $deliveryDate,
  4235. $firstPoId > 0 ? $firstPoId : null,
  4236. [$adminId, $adminName]
  4237. );
  4238. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4239. $this->success('操作成功', '', [
  4240. 'ccydh' => $ccydh,
  4241. 'delivery_status' => $deliveryStatus,
  4242. 'delivery_date' => $deliveryDate,
  4243. 'count' => $saved,
  4244. 'completed' => $qualityReady ? 1 : 0,
  4245. ]);
  4246. }
  4247. /**
  4248. * @return array<int, array<string, mixed>>
  4249. */
  4250. protected function mprocLoadApprovedPoRowsForScore(string $ccydh, int $sid): array
  4251. {
  4252. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  4253. $approvedIn = implode(',', array_map(static function ($v) {
  4254. return "'" . str_replace("'", "''", (string)$v) . "'";
  4255. }, $approvedVals));
  4256. try {
  4257. $q = Db::table('purchase_order')
  4258. ->where('scydgy_id', '>', 0)
  4259. ->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%\')')
  4260. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  4261. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  4262. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  4263. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name,pick_time,wflow_status,status');
  4264. if ($ccydh !== '') {
  4265. $q->where('CCYDH', $ccydh);
  4266. } elseif ($sid > 0) {
  4267. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4268. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4269. if ($ccydh === '') {
  4270. $this->error('缺少订单号');
  4271. }
  4272. $q->where('CCYDH', $ccydh);
  4273. } else {
  4274. $this->error('缺少订单号');
  4275. }
  4276. $poRows = $q->order('id', 'asc')->select();
  4277. } catch (\Throwable $e) {
  4278. $poRows = [];
  4279. }
  4280. if (!is_array($poRows) || $poRows === []) {
  4281. $this->error('未找到可评分的已审核订单');
  4282. }
  4283. return $poRows;
  4284. }
  4285. /**
  4286. * @param array<string, mixed> $user
  4287. */
  4288. protected function mprocResolveAdminDisplayName(array $user, int $adminId): string
  4289. {
  4290. $adminName = '';
  4291. if ($adminId > 0) {
  4292. try {
  4293. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  4294. if (is_array($adminRow)) {
  4295. $adminName = trim((string)($adminRow['nickname'] ?? ''));
  4296. if ($adminName === '') {
  4297. $adminName = trim((string)($adminRow['username'] ?? ''));
  4298. }
  4299. }
  4300. } catch (\Throwable $e) {
  4301. }
  4302. }
  4303. if ($adminName === '') {
  4304. $adminName = trim((string)($user['username'] ?? ''));
  4305. }
  4306. return $adminName !== '' ? $adminName : '管理员';
  4307. }
  4308. /**
  4309. * @param array<int, mixed> $poRows
  4310. */
  4311. protected function mprocSyncMonthlyAfterInboundScore(array $poRows, string $now): void
  4312. {
  4313. $companyName = '';
  4314. foreach ($poRows as $po) {
  4315. if (!is_array($po)) {
  4316. continue;
  4317. }
  4318. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  4319. if ($companyName !== '') {
  4320. break;
  4321. }
  4322. }
  4323. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4324. if ($companyName === '') {
  4325. return;
  4326. }
  4327. try {
  4328. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4329. } catch (\Throwable $e) {
  4330. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  4331. }
  4332. }
  4333. /**
  4334. * @return array<string, mixed>
  4335. */
  4336. protected function mprocRequireAdminUser(): array
  4337. {
  4338. $user = $this->mprocGetUser();
  4339. if (!$user) {
  4340. $this->error('请先登录', url('index/index/login'));
  4341. }
  4342. if (empty($user['is_admin'])) {
  4343. $this->error('仅系统管理员可操作');
  4344. }
  4345. return $user;
  4346. }
  4347. /** 质检中心角色组 id */
  4348. protected function mprocResolveMobileQualityGroupId(): int
  4349. {
  4350. $id = (int)Config::get('mproc.mobile_quality_group_id');
  4351. if ($id > 0) {
  4352. return $id;
  4353. }
  4354. try {
  4355. $found = Db::name('auth_group')
  4356. ->where('name', '质检中心')
  4357. ->where('status', 'normal')
  4358. ->order('id', 'asc')
  4359. ->value('id');
  4360. $id = (int)$found;
  4361. } catch (\Throwable $e) {
  4362. $id = 0;
  4363. }
  4364. return $id > 0 ? $id : 16;
  4365. }
  4366. /** 生产部/生产员角色组 id */
  4367. protected function mprocResolveMobileDeliveryGroupId(): int
  4368. {
  4369. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  4370. if ($id > 0) {
  4371. return $id;
  4372. }
  4373. try {
  4374. $found = Db::name('auth_group')
  4375. ->where('name', 'in', ['生产部', '生产员'])
  4376. ->where('status', 'normal')
  4377. ->order('id', 'asc')
  4378. ->value('id');
  4379. $id = (int)$found;
  4380. } catch (\Throwable $e) {
  4381. $id = 0;
  4382. }
  4383. return $id > 0 ? $id : 15;
  4384. }
  4385. /** 业务员(手机端新增询价)角色组 id */
  4386. protected function mprocResolveMobileRfqGroupId(): int
  4387. {
  4388. $id = (int)Config::get('mproc.mobile_rfq_group_id');
  4389. if ($id <= 0) {
  4390. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  4391. }
  4392. if ($id > 0) {
  4393. return $id;
  4394. }
  4395. try {
  4396. $found = Db::name('auth_group')
  4397. ->where('name', '业务员')
  4398. ->where('status', 'normal')
  4399. ->order('id', 'asc')
  4400. ->value('id');
  4401. $id = (int)$found;
  4402. } catch (\Throwable $e) {
  4403. $id = 0;
  4404. }
  4405. return $id > 0 ? $id : 12;
  4406. }
  4407. /**
  4408. * @return int[]
  4409. */
  4410. protected function mprocAdminGroupIds(int $adminId): array
  4411. {
  4412. if ($adminId <= 0) {
  4413. return [];
  4414. }
  4415. try {
  4416. $ids = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
  4417. } catch (\Throwable $e) {
  4418. return [];
  4419. }
  4420. if (!is_array($ids)) {
  4421. return [];
  4422. }
  4423. return array_values(array_unique(array_filter(array_map('intval', $ids))));
  4424. }
  4425. /** 超管(角色组 rules=*)或协同「管理员」组 */
  4426. protected function mprocAdminIsMobileSuper(int $adminId): bool
  4427. {
  4428. if ($adminId <= 0) {
  4429. return false;
  4430. }
  4431. try {
  4432. $rows = Db::name('auth_group_access')
  4433. ->alias('aga')
  4434. ->join('auth_group ag', 'aga.group_id = ag.id')
  4435. ->where('aga.uid', $adminId)
  4436. ->field('ag.id,ag.rules')
  4437. ->select();
  4438. } catch (\Throwable $e) {
  4439. return false;
  4440. }
  4441. if (!is_array($rows)) {
  4442. return false;
  4443. }
  4444. foreach ($rows as $r) {
  4445. if (!is_array($r)) {
  4446. continue;
  4447. }
  4448. if (trim((string)($r['rules'] ?? '')) === '*') {
  4449. return true;
  4450. }
  4451. // 供应链协同「管理员」组
  4452. if ((int)($r['id'] ?? 0) === 11) {
  4453. return true;
  4454. }
  4455. }
  4456. return false;
  4457. }
  4458. /**
  4459. * @param array<string, mixed> $user
  4460. * @param string $role quality|delivery|rfq
  4461. */
  4462. protected function mprocAdminHasMobileRole(array $user, string $role): bool
  4463. {
  4464. if (empty($user['is_admin'])) {
  4465. return false;
  4466. }
  4467. $adminId = (int)($user['admin_id'] ?? 0);
  4468. if ($adminId <= 0) {
  4469. return false;
  4470. }
  4471. if ($this->mprocAdminIsMobileSuper($adminId)) {
  4472. return true;
  4473. }
  4474. $gids = $this->mprocAdminGroupIds($adminId);
  4475. if ($role === 'quality') {
  4476. $need = $this->mprocResolveMobileQualityGroupId();
  4477. return $need > 0 && in_array($need, $gids, true);
  4478. }
  4479. if ($role === 'delivery') {
  4480. $need = $this->mprocResolveMobileDeliveryGroupId();
  4481. return $need > 0 && in_array($need, $gids, true);
  4482. }
  4483. if ($role === 'rfq') {
  4484. $need = $this->mprocResolveMobileRfqGroupId();
  4485. return $need > 0 && in_array($need, $gids, true);
  4486. }
  4487. return false;
  4488. }
  4489. /**
  4490. * @return array<string, mixed>
  4491. */
  4492. protected function mprocRequireRfqUser(): array
  4493. {
  4494. $user = $this->mprocRequireAdminUser();
  4495. if (!$this->mprocAdminHasMobileRole($user, 'rfq')) {
  4496. $this->error('仅业务员账号可新增订单询价');
  4497. }
  4498. return $user;
  4499. }
  4500. /**
  4501. * @return array<string, mixed>
  4502. */
  4503. protected function mprocRequireQualityUser(): array
  4504. {
  4505. $user = $this->mprocRequireAdminUser();
  4506. if (!$this->mprocAdminHasMobileRole($user, 'quality')) {
  4507. $this->error('仅质检中心账号可操作质量评分');
  4508. }
  4509. return $user;
  4510. }
  4511. /**
  4512. * @return array<string, mixed>
  4513. */
  4514. protected function mprocRequireDeliveryUser(): array
  4515. {
  4516. $user = $this->mprocRequireAdminUser();
  4517. if (!$this->mprocAdminHasMobileRole($user, 'delivery')) {
  4518. $this->error('仅生产部账号可操作交货情况');
  4519. }
  4520. return $user;
  4521. }
  4522. protected function mprocEnsureInboundScoreTable(): void
  4523. {
  4524. static $ok = false;
  4525. if ($ok) {
  4526. return;
  4527. }
  4528. try {
  4529. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  4530. } catch (\Throwable $e) {
  4531. try {
  4532. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  4533. `id` int unsigned NOT NULL AUTO_INCREMENT,
  4534. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  4535. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  4536. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  4537. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  4538. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  4539. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  4540. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  4541. `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
  4542. `delivery_date` date DEFAULT NULL COMMENT '交货日期',
  4543. `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
  4544. `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明',
  4545. `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
  4546. `admin_id` int unsigned NOT NULL DEFAULT 0,
  4547. `admin_name` varchar(64) NOT NULL DEFAULT '',
  4548. `remark` varchar(500) NOT NULL DEFAULT '',
  4549. `createtime` datetime DEFAULT NULL,
  4550. `updatetime` datetime DEFAULT NULL,
  4551. PRIMARY KEY (`id`),
  4552. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  4553. KEY `idx_ccydh` (`ccydh`),
  4554. KEY `idx_result` (`result`),
  4555. KEY `idx_updatetime` (`updatetime`)
  4556. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
  4557. } catch (\Throwable $e2) {
  4558. Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
  4559. return;
  4560. }
  4561. }
  4562. foreach ([
  4563. 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
  4564. 'delivery_date' => "ADD COLUMN `delivery_date` date DEFAULT NULL COMMENT '交货日期' AFTER `delivery_status`",
  4565. 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `delivery_date`",
  4566. 'complaint_remark' => "ADD COLUMN `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明' AFTER `customer_complaint`",
  4567. 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `complaint_remark`",
  4568. ] as $col => $ddl) {
  4569. try {
  4570. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
  4571. if (!is_array($cols) || $cols === []) {
  4572. Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
  4573. }
  4574. } catch (\Throwable $e) {
  4575. Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
  4576. }
  4577. }
  4578. $ok = true;
  4579. }
  4580. /**
  4581. * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
  4582. * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
  4583. *
  4584. * @return array<int, array<string, mixed>>
  4585. */
  4586. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0, string $scope = 'quality'): array
  4587. {
  4588. $this->mprocEnsureInboundScoreTable();
  4589. $keyword = trim($keyword);
  4590. $scope = $scope === 'delivery' ? 'delivery' : 'quality';
  4591. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  4592. $tab = 'pending';
  4593. }
  4594. if ($tab === 'pass' || $tab === 'fail') {
  4595. $tab = 'scored';
  4596. }
  4597. try {
  4598. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  4599. $approvedIn = implode(',', array_map(static function ($v) {
  4600. return "'" . str_replace("'", "''", (string)$v) . "'";
  4601. }, $approvedVals));
  4602. $poRows = Db::table('purchase_order')
  4603. ->where('scydgy_id', '>', 0)
  4604. ->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%\')')
  4605. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  4606. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  4607. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  4608. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,pick_company_name,pick_time,wflow_status,status')
  4609. ->order('pick_time', 'desc')
  4610. ->order('id', 'asc')
  4611. ->limit(800)
  4612. ->select();
  4613. } catch (\Throwable $e) {
  4614. Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
  4615. return [];
  4616. }
  4617. if (!is_array($poRows) || $poRows === []) {
  4618. return [];
  4619. }
  4620. $sids = [];
  4621. foreach ($poRows as $po) {
  4622. if (!is_array($po)) {
  4623. continue;
  4624. }
  4625. $sid = (int)($po['scydgy_id'] ?? 0);
  4626. if ($sid > 0) {
  4627. $sids[$sid] = true;
  4628. }
  4629. }
  4630. $scoreMap = [];
  4631. if ($sids !== []) {
  4632. try {
  4633. $scores = Db::table('purchase_order_inbound_score')
  4634. ->where('scydgy_id', 'in', array_keys($sids))
  4635. ->field('scydgy_id,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  4636. ->select();
  4637. } catch (\Throwable $e) {
  4638. try {
  4639. $scores = Db::table('purchase_order_inbound_score')
  4640. ->where('scydgy_id', 'in', array_keys($sids))
  4641. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  4642. ->select();
  4643. } catch (\Throwable $e2) {
  4644. $scores = [];
  4645. }
  4646. }
  4647. if (is_array($scores)) {
  4648. foreach ($scores as $sc) {
  4649. if (!is_array($sc)) {
  4650. continue;
  4651. }
  4652. $sid = (int)($sc['scydgy_id'] ?? 0);
  4653. if ($sid > 0) {
  4654. $scoreMap[$sid] = $sc;
  4655. }
  4656. }
  4657. }
  4658. }
  4659. /** @var array<string, array<string, mixed>> $groups */
  4660. $groups = [];
  4661. foreach ($poRows as $po) {
  4662. if (!is_array($po)) {
  4663. continue;
  4664. }
  4665. $sid = (int)($po['scydgy_id'] ?? 0);
  4666. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  4667. if ($sid <= 0 || $ccydh === '') {
  4668. continue;
  4669. }
  4670. if (!isset($groups[$ccydh])) {
  4671. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  4672. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  4673. $groups[$ccydh] = [
  4674. 'CCYDH' => $ccydh,
  4675. 'scydgy_id' => $sid,
  4676. 'scydgy_ids' => [],
  4677. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  4678. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  4679. 'CGYMC_list' => [],
  4680. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4681. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  4682. 'pick_time_raw' => $pickRaw,
  4683. 'process_count' => 0,
  4684. 'results' => [],
  4685. 'score_admin_ids' => [],
  4686. 'score_time_raw' => '',
  4687. 'customer_complaint'=> 0,
  4688. 'complaint_remark' => '',
  4689. 'order_interrupt' => 0,
  4690. 'delivery_status' => '',
  4691. 'delivery_date' => '',
  4692. 'remark' => '',
  4693. ];
  4694. }
  4695. $g = &$groups[$ccydh];
  4696. $g['scydgy_ids'][] = $sid;
  4697. $g['process_count']++;
  4698. if ($g['scydgy_id'] <= 0) {
  4699. $g['scydgy_id'] = $sid;
  4700. }
  4701. if ($g['CYJMC'] === '') {
  4702. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  4703. }
  4704. if ($g['CCLBMMC'] === '') {
  4705. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  4706. }
  4707. if ($g['pick_company_name'] === '') {
  4708. $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
  4709. }
  4710. $pt = trim((string)($po['pick_time'] ?? ''));
  4711. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  4712. $g['pick_time_raw'] = $pt;
  4713. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  4714. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  4715. }
  4716. $gymc = trim((string)($po['CGYMC'] ?? ''));
  4717. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  4718. $g['CGYMC_list'][] = $gymc;
  4719. }
  4720. $sc = $scoreMap[$sid] ?? null;
  4721. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  4722. $g['results'][] = $res;
  4723. if (is_array($sc) && $res !== '') {
  4724. $aid = (int)($sc['admin_id'] ?? 0);
  4725. if ($aid > 0) {
  4726. $g['score_admin_ids'][$aid] = true;
  4727. }
  4728. if ((int)($sc['customer_complaint'] ?? 0) === 1) {
  4729. $g['customer_complaint'] = 1;
  4730. }
  4731. $crm = trim((string)($sc['complaint_remark'] ?? ''));
  4732. if ($crm !== '' && $g['complaint_remark'] === '') {
  4733. $g['complaint_remark'] = $crm;
  4734. }
  4735. if ((int)($sc['order_interrupt'] ?? 0) === 1) {
  4736. $g['order_interrupt'] = 1;
  4737. }
  4738. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4739. if ($ds !== '' && $g['delivery_status'] === '') {
  4740. $g['delivery_status'] = $ds;
  4741. }
  4742. $dd = trim((string)($sc['delivery_date'] ?? ''));
  4743. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  4744. $g['delivery_date'] = $mdd[1];
  4745. }
  4746. $rm = trim((string)($sc['remark'] ?? ''));
  4747. if ($rm !== '' && $g['remark'] === '') {
  4748. $g['remark'] = $rm;
  4749. }
  4750. $st = trim((string)($sc['updatetime'] ?? ''));
  4751. if ($st === '') {
  4752. $st = trim((string)($sc['createtime'] ?? ''));
  4753. }
  4754. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4755. $g['score_time_raw'] = $st;
  4756. }
  4757. } elseif (is_array($sc)) {
  4758. // 仅填了交货、尚未质量评分
  4759. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4760. if ($ds !== '' && $g['delivery_status'] === '') {
  4761. $g['delivery_status'] = $ds;
  4762. }
  4763. $dd = trim((string)($sc['delivery_date'] ?? ''));
  4764. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  4765. $g['delivery_date'] = $mdd[1];
  4766. }
  4767. $st = trim((string)($sc['updatetime'] ?? ''));
  4768. if ($st === '') {
  4769. $st = trim((string)($sc['createtime'] ?? ''));
  4770. }
  4771. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4772. $g['score_time_raw'] = $st;
  4773. }
  4774. }
  4775. unset($g);
  4776. }
  4777. $out = [];
  4778. foreach ($groups as $ccydh => $g) {
  4779. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  4780. $company = (string)($g['pick_company_name'] ?? '');
  4781. $cyjmc = (string)($g['CYJMC'] ?? '');
  4782. if ($keyword !== '') {
  4783. $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  4784. if (mb_stripos($blob, $keyword) === false) {
  4785. continue;
  4786. }
  4787. }
  4788. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  4789. $uniq = [];
  4790. $allScored = true;
  4791. foreach ($results as $r) {
  4792. $r = trim((string)$r);
  4793. if ($r === '') {
  4794. $allScored = false;
  4795. continue;
  4796. }
  4797. $uniq[$r] = true;
  4798. }
  4799. $orderResult = '';
  4800. if ($allScored && count($uniq) === 1) {
  4801. $keys = array_keys($uniq);
  4802. $orderResult = (string)($keys[0] ?? '');
  4803. } elseif ($allScored && count($uniq) > 1) {
  4804. $orderResult = '';
  4805. }
  4806. $deliveryStatus = trim((string)($g['delivery_status'] ?? ''));
  4807. $hasDelivery = ($deliveryStatus === '准时' || $deliveryStatus === '滞后');
  4808. if ($scope === 'quality') {
  4809. if ($tab === 'pending' && $orderResult !== '') {
  4810. continue;
  4811. }
  4812. if ($tab === 'scored') {
  4813. if ($orderResult !== '合格' && $orderResult !== '不合格') {
  4814. continue;
  4815. }
  4816. if ($adminId <= 0) {
  4817. continue;
  4818. }
  4819. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  4820. if (empty($adminIds[$adminId])) {
  4821. continue;
  4822. }
  4823. }
  4824. } else {
  4825. // 交货:待评=尚未填准时/滞后;已评=已填
  4826. if ($tab === 'pending' && $hasDelivery) {
  4827. continue;
  4828. }
  4829. if ($tab === 'scored' && !$hasDelivery) {
  4830. continue;
  4831. }
  4832. }
  4833. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  4834. $scoreTime = $scoreTimeRaw !== ''
  4835. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw)
  4836. : '';
  4837. $out[] = [
  4838. 'CCYDH' => $ccydh,
  4839. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  4840. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  4841. 'CYJMC' => $cyjmc,
  4842. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4843. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  4844. 'pick_company_name' => $company,
  4845. 'pick_time' => (string)($g['pick_time'] ?? ''),
  4846. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  4847. 'score_time_raw' => $scoreTimeRaw,
  4848. 'process_count' => (int)($g['process_count'] ?? 0),
  4849. 'result' => $orderResult,
  4850. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  4851. 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
  4852. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  4853. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  4854. 'delivery_date' => (string)($g['delivery_date'] ?? ''),
  4855. 'remark' => (string)($g['remark'] ?? ''),
  4856. ];
  4857. }
  4858. usort($out, static function ($a, $b) use ($tab) {
  4859. if ($tab === 'scored') {
  4860. $ta = (string)($a['score_time_raw'] ?? '');
  4861. $tb = (string)($b['score_time_raw'] ?? '');
  4862. if ($ta !== $tb) {
  4863. return strcmp($tb, $ta);
  4864. }
  4865. }
  4866. $ta = (string)($a['pick_time'] ?? '');
  4867. $tb = (string)($b['pick_time'] ?? '');
  4868. if ($ta !== $tb) {
  4869. return strcmp($tb, $ta);
  4870. }
  4871. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  4872. });
  4873. return $out;
  4874. }
  4875. /**
  4876. * 业务员:新增订单询价页
  4877. */
  4878. public function rfqadd()
  4879. {
  4880. $user = $this->mprocGetUser();
  4881. if (!$user) {
  4882. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4883. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4884. if ($safe !== '') {
  4885. Session::set('mproc_intended_url', $safe);
  4886. }
  4887. $this->redirect($this->mprocBuildLoginUrl($safe));
  4888. return;
  4889. }
  4890. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'rfq')) {
  4891. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4892. if ($jump === '') {
  4893. $this->mprocDropCurrentLogin();
  4894. $this->redirect(url('index/index/login'));
  4895. return;
  4896. }
  4897. $this->redirect($jump);
  4898. return;
  4899. }
  4900. $profile = $this->mprocProfileForUser($user);
  4901. $defaultDept = trim((string)($profile['department'] ?? ''));
  4902. if ($defaultDept === '' || $defaultDept === '业务员' || $defaultDept === '管理员') {
  4903. $defaultDept = '营销中心';
  4904. }
  4905. $this->view->assign('mprocProfile', $profile);
  4906. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  4907. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  4908. $this->view->assign('nextOrderCcydh', $this->mprocAllocateManualOrderCcydh());
  4909. $this->view->assign('defaultCclbmmc', $defaultDept);
  4910. $this->view->assign('adminNickname', trim((string)($profile['contact_name'] ?? '')) ?: '业务员');
  4911. $this->view->assign('rfqDeptOptions', $this->mprocLoadRfqDeptNameOptions());
  4912. $this->view->assign('rfqStatusTab', 'pending');
  4913. $this->view->assign('rows', $this->mprocLoadRfqAddRows($user, '', 'pending'));
  4914. return $this->view->fetch();
  4915. }
  4916. /**
  4917. * 业务员询价列表 JSON(本人发起或被通知)
  4918. * GET:q、status=pending|quoted
  4919. */
  4920. public function rfqaddlist()
  4921. {
  4922. $user = $this->mprocRequireRfqUser();
  4923. $q = trim((string)$this->request->get('q', ''));
  4924. $status = trim((string)$this->request->get('status', 'pending'));
  4925. if ($status !== 'quoted') {
  4926. $status = 'pending';
  4927. }
  4928. $rows = $this->mprocLoadRfqAddRows($user, $q, $status);
  4929. $this->success('ok', null, ['rows' => $rows, 'total' => count($rows), 'status' => $status]);
  4930. }
  4931. /**
  4932. * 业务员查看询价报价(供应商 + 单价)
  4933. * GET:scydgy_id
  4934. */
  4935. public function rfqaddquotes()
  4936. {
  4937. $user = $this->mprocRequireRfqUser();
  4938. $sid = (int)$this->request->param('scydgy_id', 0);
  4939. if ($sid >= 0) {
  4940. $this->error('仅支持手工询价单');
  4941. }
  4942. $po = $this->mprocLoadAccessibleRfqOrder($user, $sid);
  4943. if (!$po) {
  4944. $this->error('询价单不存在或无权查看');
  4945. }
  4946. $list = [];
  4947. try {
  4948. $rows = Db::table('purchase_order_detail')
  4949. ->where('scydgy_id', $sid)
  4950. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  4951. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  4952. ->field('id,company_name,amount')
  4953. ->order('id', 'asc')
  4954. ->select();
  4955. } catch (\Throwable $e) {
  4956. try {
  4957. $rows = Db::table('purchase_order_detail')
  4958. ->where('scydgy_id', $sid)
  4959. ->field('id,company_name,amount')
  4960. ->order('id', 'asc')
  4961. ->select();
  4962. } catch (\Throwable $e2) {
  4963. $rows = [];
  4964. }
  4965. }
  4966. if (!is_array($rows)) {
  4967. $rows = [];
  4968. }
  4969. foreach ($rows as $row) {
  4970. if (!is_array($row)) {
  4971. continue;
  4972. }
  4973. $amount = trim((string)($row['amount'] ?? ''));
  4974. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  4975. $list[] = [
  4976. 'company_name' => trim((string)($row['company_name'] ?? '')),
  4977. 'amount' => $amount,
  4978. 'amount_text' => $isQuoted ? $amount : '',
  4979. 'is_quoted' => $isQuoted,
  4980. ];
  4981. }
  4982. $this->success('ok', null, [
  4983. 'scydgy_id' => $sid,
  4984. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  4985. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  4986. 'list' => $list,
  4987. ]);
  4988. }
  4989. /**
  4990. * 业务员提交新增订单询价
  4991. * POST:CYJMC、CCLBMMC、CGYMC、CDW、This_quantity、ceilingPrice、CDF、MBZ
  4992. */
  4993. public function rfqaddsave()
  4994. {
  4995. $user = $this->mprocRequireRfqUser();
  4996. if (!$this->request->isPost()) {
  4997. $this->error('请使用 POST');
  4998. }
  4999. $profile = $this->mprocProfileForUser($user);
  5000. $cyjmc = trim((string)$this->request->post('CYJMC', ''));
  5001. $cgymc = trim((string)$this->request->post('CGYMC', ''));
  5002. $cclbmmc = trim((string)$this->request->post('CCLBMMC', ''));
  5003. if ($cyjmc === '') {
  5004. $this->error('请填写印件名称');
  5005. }
  5006. if ($cclbmmc === '') {
  5007. $cclbmmc = trim((string)($profile['department'] ?? ''));
  5008. }
  5009. if ($cclbmmc === '') {
  5010. $cclbmmc = '营销中心';
  5011. }
  5012. $cywyxm = trim((string)($profile['contact_name'] ?? ''));
  5013. if ($cywyxm === '') {
  5014. $cywyxm = trim((string)($user['username'] ?? ''));
  5015. }
  5016. $ccydh = $this->mprocAllocateManualOrderCcydh();
  5017. $sid = $this->mprocAllocateManualScydgyId();
  5018. $now = date('Y-m-d H:i:s');
  5019. $data = [
  5020. 'scydgy_id' => $sid,
  5021. 'CCYDH' => $ccydh,
  5022. 'CYJMC' => $cyjmc,
  5023. 'CGYMC' => $cgymc,
  5024. 'CCLBMMC' => $cclbmmc,
  5025. 'CDW' => trim((string)$this->request->post('CDW', '')),
  5026. 'NGZL' => '',
  5027. 'CDF' => trim((string)$this->request->post('CDF', '')),
  5028. 'cGzzxMc' => '',
  5029. 'MBZ' => trim((string)$this->request->post('MBZ', '')),
  5030. 'cywyxm' => $cywyxm,
  5031. 'notify_salesman' => '',
  5032. 'rfq_salesman_notified' => 0,
  5033. 'rfq_salesman_notify_time' => null,
  5034. 'This_quantity' => trim((string)$this->request->post('This_quantity', '')),
  5035. 'ceilingPrice' => trim((string)$this->request->post('ceilingPrice', '')),
  5036. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  5037. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5038. 'createtime' => $now,
  5039. 'dStamp' => $now,
  5040. 'dputrecord' => $now,
  5041. ];
  5042. try {
  5043. $this->mprocEnsureRfqSalesmanColumns();
  5044. Db::table('purchase_order')->insert($data);
  5045. } catch (\Throwable $e) {
  5046. $this->error('新增失败:' . $e->getMessage());
  5047. }
  5048. $this->success('新增成功', '', [
  5049. 'scydgy_id' => $sid,
  5050. 'CCYDH' => $ccydh,
  5051. 'nextOrderCcydh' => $this->mprocAllocateManualOrderCcydh(),
  5052. ]);
  5053. }
  5054. protected function mprocAllocateManualScydgyId(): int
  5055. {
  5056. try {
  5057. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  5058. $min = (int)$min;
  5059. return $min < 0 ? $min - 1 : -1;
  5060. } catch (\Throwable $e) {
  5061. return -1;
  5062. }
  5063. }
  5064. protected function mprocAllocateManualOrderCcydh(): string
  5065. {
  5066. $prefix = 'YW' . date('Ymd');
  5067. $maxSeq = 0;
  5068. try {
  5069. $rows = Db::table('purchase_order')
  5070. ->where('CCYDH', 'like', $prefix . '%')
  5071. ->column('CCYDH');
  5072. if (is_array($rows)) {
  5073. foreach ($rows as $ccydh) {
  5074. $ccydh = trim((string)$ccydh);
  5075. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  5076. $maxSeq = max($maxSeq, (int)$m[1]);
  5077. }
  5078. }
  5079. }
  5080. } catch (\Throwable $e) {
  5081. }
  5082. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  5083. }
  5084. /**
  5085. * @return string[]
  5086. */
  5087. protected function mprocLoadRfqDeptNameOptions(): array
  5088. {
  5089. $out = [];
  5090. try {
  5091. $vals = Db::table('mcyd')
  5092. ->where('CCLBMMC', '<>', '')
  5093. ->whereNotNull('CCLBMMC')
  5094. ->distinct(true)
  5095. ->limit(300)
  5096. ->column('CCLBMMC');
  5097. } catch (\Throwable $e) {
  5098. $vals = [];
  5099. }
  5100. if (is_array($vals)) {
  5101. foreach ($vals as $v) {
  5102. $v = trim((string)$v);
  5103. if ($v === '' || isset($out[$v])) {
  5104. continue;
  5105. }
  5106. $out[$v] = $v;
  5107. }
  5108. }
  5109. try {
  5110. $poVals = Db::table('purchase_order')
  5111. ->where('CCLBMMC', '<>', '')
  5112. ->whereNotNull('CCLBMMC')
  5113. ->distinct(true)
  5114. ->limit(200)
  5115. ->column('CCLBMMC');
  5116. } catch (\Throwable $e) {
  5117. $poVals = [];
  5118. }
  5119. if (is_array($poVals)) {
  5120. foreach ($poVals as $v) {
  5121. $v = trim((string)$v);
  5122. if ($v === '' || isset($out[$v])) {
  5123. continue;
  5124. }
  5125. $out[$v] = $v;
  5126. }
  5127. }
  5128. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  5129. if (!isset($out[$preset])) {
  5130. $out[$preset] = $preset;
  5131. }
  5132. }
  5133. $list = array_values($out);
  5134. usort($list, static function ($a, $b) {
  5135. $weight = [
  5136. '营销中心' => 1,
  5137. '业务部' => 2,
  5138. '市场部' => 3,
  5139. '外贸部' => 4,
  5140. '新华技术业务部' => 5,
  5141. ];
  5142. $wa = $weight[$a] ?? 100;
  5143. $wb = $weight[$b] ?? 100;
  5144. if ($wa !== $wb) {
  5145. return $wa <=> $wb;
  5146. }
  5147. return strcmp((string)$a, (string)$b);
  5148. });
  5149. return $list;
  5150. }
  5151. protected function mprocEnsureRfqSalesmanColumns(): void
  5152. {
  5153. static $ok = false;
  5154. if ($ok) {
  5155. return;
  5156. }
  5157. $alters = [
  5158. 'notify_salesman' => "ADD COLUMN `notify_salesman` varchar(500) NOT NULL DEFAULT '' COMMENT '通知业务员' AFTER `cywyxm`",
  5159. 'rfq_salesman_notified' => "ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '是否已通知业务员' AFTER `notify_salesman`",
  5160. 'rfq_salesman_notify_time' => "ADD COLUMN `rfq_salesman_notify_time` datetime DEFAULT NULL COMMENT '通知业务员时间' AFTER `rfq_salesman_notified`",
  5161. ];
  5162. foreach ($alters as $col => $sql) {
  5163. try {
  5164. $exists = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  5165. if (is_array($exists) && $exists !== []) {
  5166. continue;
  5167. }
  5168. Db::execute('ALTER TABLE `purchase_order` ' . $sql);
  5169. } catch (\Throwable $e) {
  5170. }
  5171. }
  5172. $ok = true;
  5173. }
  5174. /**
  5175. * 校验业务员是否可访问该手工询价单
  5176. *
  5177. * @param array<string, mixed> $user
  5178. * @return array<string, mixed>|null
  5179. */
  5180. protected function mprocLoadAccessibleRfqOrder(array $user, int $sid): ?array
  5181. {
  5182. if ($sid >= 0) {
  5183. return null;
  5184. }
  5185. $profile = $this->mprocProfileForUser($user);
  5186. $adminName = trim((string)($profile['contact_name'] ?? ''));
  5187. if ($adminName === '') {
  5188. $adminName = trim((string)($user['username'] ?? ''));
  5189. }
  5190. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  5191. $this->mprocEnsureRfqSalesmanColumns();
  5192. try {
  5193. $query = Db::table('purchase_order')
  5194. ->where('scydgy_id', $sid)
  5195. ->whereRaw(
  5196. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5197. );
  5198. if (!$isSuper) {
  5199. if ($adminName === '') {
  5200. return null;
  5201. }
  5202. $query->where(function ($q2) use ($adminName) {
  5203. $q2->where('cywyxm', $adminName)
  5204. ->whereOr('notify_salesman', $adminName)
  5205. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  5206. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  5207. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  5208. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  5209. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  5210. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  5211. });
  5212. }
  5213. $row = $query->find();
  5214. } catch (\Throwable $e) {
  5215. return null;
  5216. }
  5217. return is_array($row) ? $row : null;
  5218. }
  5219. /**
  5220. * 手机端业务员询价列表(本人发起 / 被通知)
  5221. *
  5222. * @param array<string, mixed> $user
  5223. * @param string $status pending|quoted|''(空=全部)
  5224. * @return array<int, array<string, mixed>>
  5225. */
  5226. protected function mprocLoadRfqAddRows(array $user, string $q, string $status = ''): array
  5227. {
  5228. $profile = $this->mprocProfileForUser($user);
  5229. $adminName = trim((string)($profile['contact_name'] ?? ''));
  5230. if ($adminName === '') {
  5231. $adminName = trim((string)($user['username'] ?? ''));
  5232. }
  5233. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  5234. $this->mprocEnsureRfqSalesmanColumns();
  5235. try {
  5236. $query = Db::table('purchase_order')
  5237. ->where('scydgy_id', '<', 0)
  5238. ->whereRaw(
  5239. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5240. );
  5241. if (!$isSuper) {
  5242. if ($adminName === '') {
  5243. return [];
  5244. }
  5245. $query->where(function ($q2) use ($adminName) {
  5246. $q2->where('cywyxm', $adminName)
  5247. ->whereOr('notify_salesman', $adminName)
  5248. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  5249. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  5250. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  5251. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  5252. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  5253. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  5254. });
  5255. }
  5256. $q = trim($q);
  5257. if ($q !== '') {
  5258. $like = '%' . str_replace(['%', '_'], ['\\%', '\\_'], $q) . '%';
  5259. $query->where(function ($q2) use ($like) {
  5260. $q2->where('CCYDH', 'like', $like)
  5261. ->whereOr('CYJMC', 'like', $like)
  5262. ->whereOr('CGYMC', 'like', $like)
  5263. ->whereOr('CCLBMMC', 'like', $like)
  5264. ->whereOr('MBZ', 'like', $like);
  5265. });
  5266. }
  5267. $rows = $query
  5268. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cywyxm,MBZ,status,wflow_status,rfq_salesman_notified,createtime,dStamp')
  5269. ->order('id', 'desc')
  5270. ->limit(200)
  5271. ->select();
  5272. } catch (\Throwable $e) {
  5273. $rows = [];
  5274. }
  5275. if (!is_array($rows)) {
  5276. $rows = [];
  5277. }
  5278. $out = [];
  5279. $sids = [];
  5280. foreach ($rows as $r) {
  5281. if (!is_array($r)) {
  5282. continue;
  5283. }
  5284. $sid = (int)($r['scydgy_id'] ?? 0);
  5285. if ($sid < 0) {
  5286. $sids[$sid] = $sid;
  5287. }
  5288. }
  5289. $quotedMap = $this->mprocLoadRfqQuotedSidMap(array_values($sids));
  5290. $status = trim($status);
  5291. if ($status !== 'pending' && $status !== 'quoted') {
  5292. $status = '';
  5293. }
  5294. foreach ($rows as $r) {
  5295. if (!is_array($r)) {
  5296. continue;
  5297. }
  5298. $sid = (int)($r['scydgy_id'] ?? 0);
  5299. $isQuoted = !empty($quotedMap[$sid]);
  5300. if ($status === 'pending' && $isQuoted) {
  5301. continue;
  5302. }
  5303. if ($status === 'quoted' && !$isQuoted) {
  5304. continue;
  5305. }
  5306. $created = trim((string)($r['createtime'] ?? ''));
  5307. if ($created === '' || stripos($created, '0000-00-00') === 0) {
  5308. $created = trim((string)($r['dStamp'] ?? ''));
  5309. }
  5310. if (preg_match('/^\d{10,}$/', $created)) {
  5311. $created = date('Y-m-d H:i:s', (int)$created);
  5312. }
  5313. if ($created !== '' && stripos($created, '0000-00-00') === 0) {
  5314. $created = '';
  5315. }
  5316. $out[] = [
  5317. 'id' => (int)($r['id'] ?? 0),
  5318. 'scydgy_id' => $sid,
  5319. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5320. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5321. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5322. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5323. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5324. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5325. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  5326. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  5327. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5328. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5329. 'progress_text' => $isQuoted ? '已报价' : '待询价',
  5330. 'createtime' => $created,
  5331. ];
  5332. }
  5333. return $out;
  5334. }
  5335. /**
  5336. * 哪些手工询价单已有有效报价(amount 非空且非 0)
  5337. *
  5338. * @param array<int, int> $sids
  5339. * @return array<int, bool>
  5340. */
  5341. protected function mprocLoadRfqQuotedSidMap(array $sids): array
  5342. {
  5343. $out = [];
  5344. $sids = array_values(array_unique(array_filter(array_map('intval', $sids), static function ($v) {
  5345. return $v < 0;
  5346. })));
  5347. if ($sids === []) {
  5348. return $out;
  5349. }
  5350. foreach (array_chunk($sids, 200) as $chunk) {
  5351. try {
  5352. $rows = Db::table('purchase_order_detail')
  5353. ->where('scydgy_id', 'in', $chunk)
  5354. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  5355. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  5356. ->where('amount', '<>', '')
  5357. ->whereNotNull('amount')
  5358. ->where('amount', '<>', '0')
  5359. ->where('amount', '<>', '0.00')
  5360. ->field('scydgy_id')
  5361. ->group('scydgy_id')
  5362. ->select();
  5363. } catch (\Throwable $e) {
  5364. try {
  5365. $rows = Db::table('purchase_order_detail')
  5366. ->where('scydgy_id', 'in', $chunk)
  5367. ->where('amount', '<>', '')
  5368. ->whereNotNull('amount')
  5369. ->where('amount', '<>', '0')
  5370. ->where('amount', '<>', '0.00')
  5371. ->field('scydgy_id')
  5372. ->group('scydgy_id')
  5373. ->select();
  5374. } catch (\Throwable $e2) {
  5375. $rows = [];
  5376. }
  5377. }
  5378. if (!is_array($rows)) {
  5379. continue;
  5380. }
  5381. foreach ($rows as $r) {
  5382. if (!is_array($r)) {
  5383. continue;
  5384. }
  5385. $sid = (int)($r['scydgy_id'] ?? 0);
  5386. if ($sid < 0) {
  5387. $out[$sid] = true;
  5388. }
  5389. }
  5390. }
  5391. return $out;
  5392. }
  5393. /**
  5394. * @param array<string, mixed> $row
  5395. */
  5396. protected function mprocFormatRfqProgressText(array $row): string
  5397. {
  5398. $sid = (int)($row['scydgy_id'] ?? 0);
  5399. if ($sid < 0) {
  5400. $map = $this->mprocLoadRfqQuotedSidMap([$sid]);
  5401. if (!empty($map[$sid])) {
  5402. return '已报价';
  5403. }
  5404. }
  5405. return '待询价';
  5406. }
  5407. }