Index.php 209 KB

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