Index.php 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371
  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. * 管理员(admin):登录后进「质量评分」,对订单评合格/不合格、客户投诉、订单中断
  17. */
  18. class Index extends Frontend
  19. {
  20. protected $noNeedLogin = ['*'];
  21. protected $noNeedRight = ['*'];
  22. protected $layout = '';
  23. /** @var int 登录态有效天数 */
  24. protected $mprocTtlSeconds = 0;
  25. /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
  26. protected static $mprocProcuremenColumns = null;
  27. public function _initialize()
  28. {
  29. parent::_initialize();
  30. if (is_file(APP_PATH . 'extra/mproc.php')) {
  31. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  32. }
  33. $hours = (int)Config::get('mproc.session_hours');
  34. if ($hours > 0) {
  35. $this->mprocTtlSeconds = max(1, min(720, $hours)) * 3600;
  36. } else {
  37. $days = (int)(Config::get('mproc.session_days') ?: 3);
  38. $days = max(1, min(30, $days));
  39. $this->mprocTtlSeconds = $days * 86400;
  40. }
  41. if (PHP_VERSION_ID >= 70300) {
  42. ini_set('session.cookie_lifetime', (string)$this->mprocTtlSeconds);
  43. ini_set('session.gc_maxlifetime', (string)$this->mprocTtlSeconds);
  44. }
  45. }
  46. /** 登录有效小时数(用于前端 localStorage 过期时间) */
  47. protected function mprocKeepHours(): int
  48. {
  49. return max(1, (int)round($this->mprocTtlSeconds / 3600));
  50. }
  51. /**
  52. * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
  53. */
  54. protected function mprocGetUser()
  55. {
  56. $token = $this->mprocReadTokenFromRequest();
  57. if ($token !== '') {
  58. $user = $this->mprocLoadUserByToken($token);
  59. if ($user) {
  60. $token = $this->mprocTouchLoginState($user, $token);
  61. $user['token'] = $token;
  62. return $user;
  63. }
  64. }
  65. $user = $this->mprocUserFromRememberCookie();
  66. if (!$user) {
  67. return null;
  68. }
  69. $token = $this->mprocPackSignedAuthToken($user);
  70. $token = $this->mprocTouchLoginState($user, $token);
  71. $user['token'] = $token;
  72. return $user;
  73. }
  74. protected function mprocReadTokenFromRequest(): string
  75. {
  76. $token = Session::get('mproc_token');
  77. if ($token === null || $token === '') {
  78. $token = Cookie::get('mproc_token');
  79. }
  80. if ($token === null || $token === '') {
  81. $token = $this->request->header('X-Mproc-Token');
  82. }
  83. if ($token === null || $token === '') {
  84. $token = $this->request->request('mproc_token', '');
  85. }
  86. $token = trim((string)$token);
  87. if ($token === '') {
  88. return '';
  89. }
  90. if ($this->mprocIsSignedAuthToken($token)) {
  91. return $token;
  92. }
  93. $token = preg_replace('/[^a-f0-9]/i', '', $token);
  94. return strlen($token) >= 16 ? $token : '';
  95. }
  96. protected function mprocIsSignedAuthToken(string $token): bool
  97. {
  98. return strpos($token, '.') !== false
  99. && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
  100. }
  101. protected function mprocAuthCacheKey(string $token): string
  102. {
  103. return 'mproc_u_' . md5($token);
  104. }
  105. /**
  106. * @return array<string, mixed>|null
  107. */
  108. protected function mprocLoadUserByToken(string $token): ?array
  109. {
  110. if ($this->mprocIsSignedAuthToken($token)) {
  111. if ($this->mprocIsAuthTokenRevoked($token)) {
  112. return null;
  113. }
  114. $user = $this->mprocUserFromSignedToken($token);
  115. if (!$user) {
  116. return null;
  117. }
  118. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  119. $this->mprocClearLogin($token);
  120. return null;
  121. }
  122. $user['token'] = $token;
  123. return $user;
  124. }
  125. $user = Cache::get('mproc_u_' . $token);
  126. if (!is_array($user)) {
  127. $user = $this->mprocUserFromRememberCookie();
  128. if (!$user) {
  129. return null;
  130. }
  131. }
  132. if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
  133. return null;
  134. }
  135. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  136. $this->mprocClearLogin($token);
  137. return null;
  138. }
  139. $user['token'] = $token;
  140. return $user;
  141. }
  142. /**
  143. * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
  144. *
  145. * @param array<string, mixed> $user
  146. */
  147. protected function mprocTouchLoginState(array $user, string $token): string
  148. {
  149. $user['login_time'] = time();
  150. if ($this->mprocIsSignedAuthToken($token)) {
  151. $token = $this->mprocPackSignedAuthToken($user);
  152. }
  153. Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
  154. if (!$this->mprocIsSignedAuthToken($token)) {
  155. Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
  156. }
  157. Session::set('mproc_token', $token);
  158. $this->mprocSetTokenCookie($token);
  159. $this->mprocSetRememberCookie($user, $token);
  160. return $token;
  161. }
  162. /**
  163. * @return array<string, mixed>
  164. */
  165. protected function mprocCookieOptions(): array
  166. {
  167. $opts = [
  168. 'expire' => $this->mprocTtlSeconds,
  169. 'path' => '/',
  170. 'httponly' => true,
  171. ];
  172. if ($this->request->isSsl()) {
  173. $opts['secure'] = true;
  174. }
  175. if (PHP_VERSION_ID >= 70300) {
  176. $opts['samesite'] = 'Lax';
  177. }
  178. return $opts;
  179. }
  180. protected function mprocSetTokenCookie(string $token): void
  181. {
  182. Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
  183. }
  184. /**
  185. * @param array<string, mixed> $user
  186. */
  187. protected function mprocSetRememberCookie(array $user, ?string $token = null): void
  188. {
  189. $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
  190. Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
  191. }
  192. protected function mprocAuthSignSecret(): string
  193. {
  194. $key = trim((string)Config::get('mproc.auth_sign_key'));
  195. if ($key === '') {
  196. $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
  197. }
  198. return hash('sha256', $key);
  199. }
  200. /**
  201. * @param array<string, mixed> $user
  202. */
  203. protected function mprocPackSignedAuthToken(array $user): string
  204. {
  205. $payload = [
  206. 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
  207. 'phone' => trim((string)($user['phone'] ?? '')),
  208. 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
  209. 'admin' => !empty($user['is_admin']) ? 1 : 0,
  210. 'lt' => time(),
  211. ];
  212. $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
  213. $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
  214. return $b64 . '.' . $sig;
  215. }
  216. /** @deprecated 使用 mprocPackSignedAuthToken */
  217. protected function mprocPackRememberCookie(array $user): string
  218. {
  219. return $this->mprocPackSignedAuthToken($user);
  220. }
  221. /**
  222. * @return array<string, mixed>|null
  223. */
  224. protected function mprocUserFromSignedToken(string $raw): ?array
  225. {
  226. $parts = explode('.', trim($raw), 2);
  227. if (count($parts) !== 2) {
  228. return null;
  229. }
  230. $b64 = $parts[0];
  231. $sig = $parts[1];
  232. if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
  233. return null;
  234. }
  235. $pad = strlen($b64) % 4;
  236. if ($pad > 0) {
  237. $b64 .= str_repeat('=', 4 - $pad);
  238. }
  239. $json = base64_decode(strtr($b64, '-_', '+/'), true);
  240. if ($json === false || $json === '') {
  241. return null;
  242. }
  243. $payload = json_decode($json, true);
  244. if (!is_array($payload)) {
  245. return null;
  246. }
  247. $lt = (int)($payload['lt'] ?? 0);
  248. if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
  249. return null;
  250. }
  251. return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
  252. }
  253. /**
  254. * @return array<string, mixed>|null
  255. */
  256. protected function mprocUserFromRememberCookie(): ?array
  257. {
  258. $raw = Cookie::get('mproc_remember');
  259. if ($raw === null || $raw === '') {
  260. $raw = Cookie::get('mproc_token');
  261. }
  262. if ($raw === null || $raw === '') {
  263. return null;
  264. }
  265. $raw = (string)$raw;
  266. if ($this->mprocIsAuthTokenRevoked($raw)) {
  267. return null;
  268. }
  269. return $this->mprocUserFromSignedToken($raw);
  270. }
  271. /**
  272. * @param array<string, mixed> $payload
  273. * @return array<string, mixed>|null
  274. */
  275. protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
  276. {
  277. if (!empty($payload['admin'])) {
  278. $uname = trim((string)($payload['uname'] ?? ''));
  279. if ($uname === '') {
  280. return null;
  281. }
  282. try {
  283. $row = Db::name('admin')->where('username', $uname)->find();
  284. } catch (\Throwable $e) {
  285. $row = null;
  286. }
  287. if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
  288. return null;
  289. }
  290. return [
  291. 'phone' => trim((string)($row['mobile'] ?? '')),
  292. 'company_name' => '',
  293. 'username' => $uname,
  294. 'customer_user_id' => 0,
  295. 'admin_id' => (int)($row['id'] ?? 0),
  296. 'login_type' => 'remember',
  297. 'is_admin' => 1,
  298. 'login_time' => $loginTime,
  299. ];
  300. }
  301. $cid = (int)($payload['uid'] ?? 0);
  302. if ($cid > 0) {
  303. try {
  304. $cu = Db::table('customer')->where('id', $cid)->find();
  305. } catch (\Throwable $e) {
  306. $cu = null;
  307. }
  308. if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
  309. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  310. $user['login_time'] = $loginTime;
  311. return $user;
  312. }
  313. }
  314. $phone = trim((string)($payload['phone'] ?? ''));
  315. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  316. $cu = $this->mprocFindCustomerUserByMobile($phone);
  317. if ($cu) {
  318. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  319. $user['login_time'] = $loginTime;
  320. return $user;
  321. }
  322. }
  323. return null;
  324. }
  325. protected function mprocAuthRevokeCacheKey(string $token): string
  326. {
  327. return 'mproc_revoked_' . md5($token);
  328. }
  329. protected function mprocRevokeAuthToken(string $token): void
  330. {
  331. $token = trim($token);
  332. if ($token === '') {
  333. return;
  334. }
  335. try {
  336. Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
  337. } catch (\Throwable $e) {
  338. }
  339. }
  340. protected function mprocIsAuthTokenRevoked(string $token): bool
  341. {
  342. $token = trim($token);
  343. if ($token === '') {
  344. return false;
  345. }
  346. try {
  347. return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
  348. } catch (\Throwable $e) {
  349. return false;
  350. }
  351. }
  352. /**
  353. * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
  354. */
  355. protected function mprocExpireAuthCookies(): void
  356. {
  357. $opts = $this->mprocCookieOptions();
  358. $opts['expire'] = -3600;
  359. try {
  360. Cookie::set('mproc_token', '', $opts);
  361. Cookie::set('mproc_remember', '', $opts);
  362. } catch (\Throwable $e) {
  363. }
  364. try {
  365. Cookie::delete('mproc_token');
  366. Cookie::delete('mproc_remember');
  367. } catch (\Throwable $e) {
  368. }
  369. unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
  370. $prefix = (string)Config::get('cookie.prefix');
  371. if ($prefix !== '') {
  372. unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
  373. }
  374. }
  375. protected function mprocClearLogin($token)
  376. {
  377. $token = trim((string)($token ?? ''));
  378. if ($token !== '') {
  379. $this->mprocRevokeAuthToken($token);
  380. try {
  381. Cache::rm($this->mprocAuthCacheKey($token));
  382. } catch (\Throwable $e) {
  383. }
  384. if (!$this->mprocIsSignedAuthToken($token)) {
  385. try {
  386. Cache::rm('mproc_u_' . $token);
  387. } catch (\Throwable $e) {
  388. }
  389. }
  390. }
  391. // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
  392. foreach (['mproc_token', 'mproc_remember'] as $ck) {
  393. $raw = Cookie::get($ck);
  394. if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
  395. $this->mprocRevokeAuthToken((string)$raw);
  396. }
  397. }
  398. Session::delete('mproc_token');
  399. $this->mprocExpireAuthCookies();
  400. }
  401. /**
  402. * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
  403. *
  404. * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
  405. */
  406. protected function mprocSanitizeRedirectUrl($raw)
  407. {
  408. $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
  409. if ($s === '') {
  410. return '';
  411. }
  412. if (preg_match('#^https?://#i', $s)) {
  413. $h = parse_url($s, PHP_URL_HOST);
  414. if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
  415. return '';
  416. }
  417. $path = parse_url($s, PHP_URL_PATH);
  418. $query = parse_url($s, PHP_URL_QUERY);
  419. $s = (is_string($path) && $path !== '' ? $path : '/');
  420. if (is_string($query) && $query !== '') {
  421. $s .= '?' . $query;
  422. }
  423. }
  424. if (strpos($s, '://') !== false) {
  425. return '';
  426. }
  427. if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
  428. return '';
  429. }
  430. if ($s[0] !== '/') {
  431. $s = '/' . ltrim($s, '/');
  432. }
  433. if (strpos($s, '//') === 0) {
  434. return '';
  435. }
  436. $okHome = stripos($s, 'index/index/index') !== false;
  437. $okInbound = stripos($s, 'index/index/inboundscore') !== false;
  438. if (!$okHome && !$okInbound) {
  439. return '';
  440. }
  441. if (stripos($s, 'index/index/login') !== false) {
  442. return '';
  443. }
  444. return $s;
  445. }
  446. protected function mprocRememberFocusEid(int $focusEid): void
  447. {
  448. if ($focusEid > 0) {
  449. Session::set('mproc_focus_eid', $focusEid);
  450. }
  451. }
  452. protected function mprocPullSessionFocusEid(): int
  453. {
  454. $fe = (int)Session::get('mproc_focus_eid', 0);
  455. if ($fe > 0) {
  456. Session::delete('mproc_focus_eid');
  457. }
  458. return $fe;
  459. }
  460. /**
  461. * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &amp;focus_eid 拼进上一参数值的情况)
  462. */
  463. protected function mprocParseFocusEidFromUriString(string $uri): int
  464. {
  465. if ($uri === '' || stripos($uri, 'focus_eid') === false) {
  466. return 0;
  467. }
  468. if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
  469. return (int)$m[1];
  470. }
  471. $query = parse_url($uri, PHP_URL_QUERY);
  472. if (!is_string($query) || $query === '') {
  473. return 0;
  474. }
  475. $q = [];
  476. parse_str($query, $q);
  477. if (!is_array($q)) {
  478. return 0;
  479. }
  480. if (isset($q['focus_eid'])) {
  481. $fe = (int)$q['focus_eid'];
  482. if ($fe > 0) {
  483. return $fe;
  484. }
  485. }
  486. foreach ($q as $k => $v) {
  487. $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
  488. if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
  489. return (int)$m2[1];
  490. }
  491. }
  492. return 0;
  493. }
  494. /**
  495. * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
  496. */
  497. protected function mprocReadFocusEidFromRequest(): int
  498. {
  499. $fe = (int)$this->request->param('focus_eid', 0);
  500. if ($fe > 0) {
  501. $this->mprocRememberFocusEid($fe);
  502. return $fe;
  503. }
  504. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  505. $fe = $this->mprocParseFocusEidFromUriString($uri);
  506. if ($fe > 0) {
  507. $this->mprocRememberFocusEid($fe);
  508. return $fe;
  509. }
  510. $fe = (int)Session::get('mproc_focus_eid', 0);
  511. if ($fe > 0) {
  512. return $fe;
  513. }
  514. return 0;
  515. }
  516. /**
  517. * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
  518. *
  519. * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
  520. */
  521. protected function mprocBuildLoginUrl($redirectPath = '')
  522. {
  523. $root = rtrim($this->request->root(), '/');
  524. $path = '/index/index/login';
  525. $rp = trim((string)$redirectPath);
  526. if ($rp === '') {
  527. return $root . $path;
  528. }
  529. return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
  530. }
  531. /**
  532. * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
  533. *
  534. * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
  535. */
  536. protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
  537. {
  538. $raw = trim((string)$redirectPathOrUrl);
  539. if ($raw === '') {
  540. return url('index/index/index', '', '', true);
  541. }
  542. $queryStr = '';
  543. if (preg_match('#^https?://#i', $raw)) {
  544. $pq = parse_url($raw);
  545. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  546. } elseif (isset($raw[0]) && $raw[0] === '/') {
  547. $pq = parse_url('http://127.0.0.1' . $raw);
  548. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  549. } else {
  550. $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
  551. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  552. }
  553. $q = [];
  554. if ($queryStr !== '') {
  555. parse_str($queryStr, $q);
  556. if (!is_array($q)) {
  557. $q = [];
  558. }
  559. }
  560. $allowed = [];
  561. $fe = 0;
  562. if (isset($q['focus_eid'])) {
  563. $fe = (int)$q['focus_eid'];
  564. }
  565. if ($fe <= 0) {
  566. $fe = $this->mprocParseFocusEidFromUriString($raw);
  567. }
  568. if ($fe <= 0) {
  569. $fe = (int)Session::get('mproc_focus_eid', 0);
  570. }
  571. if ($fe > 0) {
  572. $allowed['focus_eid'] = $fe;
  573. $this->mprocRememberFocusEid($fe);
  574. }
  575. $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
  576. if ($mt === 'me' || $mt === 'orders') {
  577. $allowed['main_tab'] = $mt;
  578. }
  579. $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
  580. if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
  581. $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
  582. }
  583. if (isset($q['q']) && trim((string)$q['q']) !== '') {
  584. $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
  585. }
  586. if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
  587. $allowed['main_tab'] = 'orders';
  588. }
  589. $base = rtrim($this->request->root(true), '/');
  590. $path = '/index/index/index';
  591. if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
  592. $fe = (int)$allowed['focus_eid'];
  593. if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
  594. return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
  595. }
  596. $ordered = ['focus_eid' => $fe];
  597. if (isset($allowed['tab'])) {
  598. $ordered['tab'] = $allowed['tab'];
  599. }
  600. if (isset($allowed['main_tab'])) {
  601. $ordered['main_tab'] = $allowed['main_tab'];
  602. }
  603. return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
  604. }
  605. $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
  606. return $base . $path . $qs;
  607. }
  608. /**
  609. * 按登录身份决定首页:供应商→报价列表;管理员→质量评分
  610. *
  611. * @param array<string, mixed> $user
  612. * @param string $redirectPathOrUrl
  613. */
  614. protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
  615. {
  616. if (!empty($user['is_admin'])) {
  617. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  618. if ($raw !== '' && stripos($raw, 'inboundscore') !== false) {
  619. $base = rtrim($this->request->root(true), '/');
  620. $path = parse_url($raw, PHP_URL_PATH);
  621. $query = parse_url($raw, PHP_URL_QUERY);
  622. if (!is_string($path) || $path === '') {
  623. return url('index/index/inboundscore', '', '', true);
  624. }
  625. if (stripos($path, 'inboundscore') === false) {
  626. return url('index/index/inboundscore', '', '', true);
  627. }
  628. return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
  629. }
  630. return url('index/index/inboundscore', '', '', true);
  631. }
  632. return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
  633. }
  634. /**
  635. * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
  636. *
  637. * @param string[] $candidatesLower 如 ['status','istatus']
  638. * @return string|null
  639. */
  640. protected function mprocResolveProcuremenColumn(array $candidatesLower)
  641. {
  642. if (self::$mprocProcuremenColumns === null) {
  643. self::$mprocProcuremenColumns = [];
  644. try {
  645. $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
  646. if (is_array($rows)) {
  647. foreach ($rows as $c) {
  648. $name = isset($c['Field']) ? (string)$c['Field'] : '';
  649. if ($name !== '') {
  650. self::$mprocProcuremenColumns[strtolower($name)] = $name;
  651. }
  652. }
  653. }
  654. } catch (\Throwable $e) {
  655. self::$mprocProcuremenColumns = [];
  656. }
  657. }
  658. foreach ($candidatesLower as $low) {
  659. $k = strtolower((string)$low);
  660. if (isset(self::$mprocProcuremenColumns[$k])) {
  661. return self::$mprocProcuremenColumns[$k];
  662. }
  663. }
  664. return null;
  665. }
  666. /**
  667. * 供应商整单备注(purchase_order_detail.remark)
  668. *
  669. * @param array<string, mixed> $row
  670. */
  671. protected function mprocResolveDetailRemark(array $row): string
  672. {
  673. $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  674. if ($col === null) {
  675. return '';
  676. }
  677. foreach ($row as $k => $v) {
  678. if (strcasecmp((string)$k, $col) === 0) {
  679. return trim((string)$v);
  680. }
  681. }
  682. return '';
  683. }
  684. /**
  685. * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
  686. *
  687. * @return array|callable 可直接 $query->where(...);空数组表示不加条件
  688. */
  689. protected function mprocListWhereForLoginUser(array $user)
  690. {
  691. if (!empty($user['is_admin'])) {
  692. return [];
  693. }
  694. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  695. $pCol = $this->mprocResolveProcuremenColumn(['phone']);
  696. if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
  697. return ['id' => 0];
  698. }
  699. $cn = trim((string)($user['company_name'] ?? ''));
  700. $phone = trim((string)($user['phone'] ?? ''));
  701. if ($cn === '' && $phone !== '') {
  702. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  703. }
  704. if ($cn === '' && $phone === '') {
  705. return ['id' => 0];
  706. }
  707. return function ($q) use ($cCol, $pCol, $cn, $phone) {
  708. $first = true;
  709. if ($cCol !== null && $cCol !== '' && $cn !== '') {
  710. $q->where($cCol, $cn);
  711. $first = false;
  712. }
  713. if ($pCol !== null && $pCol !== '' && $phone !== '') {
  714. if ($first) {
  715. $q->where($pCol, $phone);
  716. } else {
  717. $q->whereOr($pCol, $phone);
  718. }
  719. }
  720. if ($first) {
  721. $q->where('id', 0);
  722. }
  723. };
  724. }
  725. /**
  726. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  727. */
  728. protected function mprocCustomerUserActive(array $row): bool
  729. {
  730. $st = $row['status'] ?? '';
  731. if ($st === '' || $st === null) {
  732. return true;
  733. }
  734. return $st === 1 || $st === '1';
  735. }
  736. /**
  737. * @return array<string, mixed>|null
  738. */
  739. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  740. {
  741. return $this->mprocFindCustomerRowByPhone($phone);
  742. }
  743. /**
  744. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  745. *
  746. * @return array<string, mixed>|null
  747. */
  748. protected function mprocFindCustomerUserByUsername(string $username): ?array
  749. {
  750. $username = trim($username);
  751. if ($username === '') {
  752. return null;
  753. }
  754. try {
  755. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  756. } catch (\Throwable $e) {
  757. $row = null;
  758. }
  759. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  760. $row = $this->mprocFindCustomerRowByPhone($username);
  761. }
  762. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  763. return null;
  764. }
  765. return $row;
  766. }
  767. /**
  768. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  769. */
  770. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  771. {
  772. $stored = (string)($row['password'] ?? '');
  773. if ($stored === '' || $password === '') {
  774. return false;
  775. }
  776. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  777. return password_verify($password, $stored);
  778. }
  779. return hash_equals($stored, md5(md5($password)));
  780. }
  781. /**
  782. * 生成 customer 登录密码密文
  783. */
  784. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  785. {
  786. unset($existingSalt);
  787. return md5(md5($password));
  788. }
  789. /**
  790. * 手机端强密码校验:通过返回空字符串,否则返回错误提示
  791. */
  792. protected function mprocValidateStrongPassword(string $password): string
  793. {
  794. $len = strlen($password);
  795. if ($len < 8 || $len > 20) {
  796. return '密码长度须为8~20位';
  797. }
  798. if (preg_match('/\s/', $password)) {
  799. return '密码不能包含空格';
  800. }
  801. if (preg_match('/^\d+$/', $password)) {
  802. return '密码不能为纯数字,请同时包含字母';
  803. }
  804. if (preg_match('/^[a-zA-Z]+$/', $password)) {
  805. return '密码不能为纯字母,请同时包含数字';
  806. }
  807. if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
  808. return '密码须同时包含字母和数字';
  809. }
  810. if (preg_match('/(.)\1{3,}/', $password)) {
  811. return '密码不能包含过多重复字符(如1111、aaaa)';
  812. }
  813. if ($this->mprocPasswordHasSequentialRun($password, 4)) {
  814. return '密码不能包含连续字符(如1234、abcd)';
  815. }
  816. $weak = [
  817. '12345678', '123456789', '1234567890', '87654321', '01234567',
  818. 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
  819. 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
  820. '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
  821. ];
  822. if (in_array(strtolower($password), $weak, true)) {
  823. return '密码过于简单,请重新设置';
  824. }
  825. return '';
  826. }
  827. /**
  828. * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
  829. */
  830. protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
  831. {
  832. $runLen = max(3, $runLen);
  833. $lower = strtolower($password);
  834. $n = strlen($lower);
  835. if ($n < $runLen) {
  836. return false;
  837. }
  838. for ($i = 0; $i <= $n - $runLen; $i++) {
  839. $asc = true;
  840. $desc = true;
  841. for ($j = 1; $j < $runLen; $j++) {
  842. $prev = ord($lower[$i + $j - 1]);
  843. $cur = ord($lower[$i + $j]);
  844. if ($cur !== $prev + 1) {
  845. $asc = false;
  846. }
  847. if ($cur !== $prev - 1) {
  848. $desc = false;
  849. }
  850. if (!$asc && !$desc) {
  851. break;
  852. }
  853. }
  854. if ($asc || $desc) {
  855. return true;
  856. }
  857. }
  858. return false;
  859. }
  860. /**
  861. * @param array<string, mixed> $cu
  862. * @return array<string, mixed>
  863. */
  864. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  865. {
  866. $phone = trim((string)($cu['phone'] ?? ''));
  867. $account = trim((string)($cu['account'] ?? ''));
  868. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  869. $phone = $account;
  870. }
  871. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  872. $account = $phone;
  873. }
  874. $companyName = trim((string)($cu['company_name'] ?? ''));
  875. if ($companyName === '' && $phone !== '') {
  876. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  877. }
  878. $id = (int)($cu['id'] ?? 0);
  879. return [
  880. 'phone' => $phone,
  881. 'account' => $account,
  882. 'company_name' => $companyName,
  883. 'username' => trim((string)($cu['username'] ?? '')),
  884. 'customer_id' => $id,
  885. 'customer_user_id' => $id,
  886. 'login_type' => $loginType,
  887. 'is_admin' => 0,
  888. ];
  889. }
  890. /**
  891. * 写入手机端登录态并返回跳转 URL
  892. *
  893. * @param array<string, mixed> $userData
  894. */
  895. protected function mprocFinishLogin(array $userData): void
  896. {
  897. $old = Session::get('mproc_token');
  898. if ($old) {
  899. $this->mprocClearLogin((string)$old);
  900. }
  901. $userData['login_time'] = time();
  902. $token = $this->mprocPackSignedAuthToken($userData);
  903. $token = $this->mprocTouchLoginState($userData, $token);
  904. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  905. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  906. Session::delete('mproc_intended_url');
  907. $raw = $postR !== '' ? $postR : $sessR;
  908. $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
  909. $this->success('登录成功', $jump, [
  910. 'mproc_token' => $token,
  911. 'keep_hours' => $this->mprocKeepHours(),
  912. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  913. ]);
  914. }
  915. /**
  916. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  917. */
  918. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  919. {
  920. $phone = trim($phone);
  921. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  922. return '';
  923. }
  924. $cust = $this->mprocFindCustomerRowByPhone($phone);
  925. if (is_array($cust) && $cust !== []) {
  926. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  927. if ($co !== '') {
  928. return $co;
  929. }
  930. }
  931. try {
  932. $one = Db::table('purchase_order_detail')
  933. ->where('phone', $phone)
  934. ->order('id', 'desc')
  935. ->find();
  936. if (is_array($one)) {
  937. $n = trim((string)($one['company_name'] ?? ''));
  938. if ($n !== '') {
  939. return $n;
  940. }
  941. }
  942. } catch (\Throwable $e) {
  943. }
  944. return '';
  945. }
  946. /**
  947. * 按手机号匹配 customer(phone 或 account 单值相等)
  948. *
  949. * @return array<string, mixed>|null
  950. */
  951. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  952. {
  953. $phone = trim($phone);
  954. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  955. return null;
  956. }
  957. try {
  958. $row = Db::table('customer')
  959. ->where(function ($q) use ($phone) {
  960. $q->where('phone', $phone)->whereOr('account', $phone);
  961. })
  962. ->order('id', 'asc')
  963. ->find();
  964. } catch (\Throwable $e) {
  965. return null;
  966. }
  967. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  968. return null;
  969. }
  970. return $row;
  971. }
  972. /**
  973. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  974. *
  975. * @return array<string, mixed>|null
  976. */
  977. protected function mprocAdminRowByMobile(string $phone): ?array
  978. {
  979. $phone = trim($phone);
  980. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  981. return null;
  982. }
  983. try {
  984. $row = Db::name('admin')
  985. ->where('mobile', $phone)
  986. ->where('status', '<>', 'hidden')
  987. ->order('id', 'asc')
  988. ->find();
  989. } catch (\Throwable $e) {
  990. return null;
  991. }
  992. return is_array($row) && $row !== [] ? $row : null;
  993. }
  994. /**
  995. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  996. *
  997. * @return array<string, mixed>|null
  998. */
  999. protected function mprocFindCustomerRowForUser(array $user): ?array
  1000. {
  1001. $phone = trim((string)($user['phone'] ?? ''));
  1002. if ($phone === '') {
  1003. $phone = trim((string)($user['account'] ?? ''));
  1004. }
  1005. $cn = trim((string)($user['company_name'] ?? ''));
  1006. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1007. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  1008. if ($byPhone !== null) {
  1009. return $byPhone;
  1010. }
  1011. }
  1012. if ($cn !== '') {
  1013. try {
  1014. // customer 表无 name 列,勿用 whereOr('name')
  1015. $hit = Db::table('customer')
  1016. ->where('company_name', $cn)
  1017. ->order('id', 'desc')
  1018. ->find();
  1019. } catch (\Throwable $e) {
  1020. $hit = null;
  1021. }
  1022. if (is_array($hit) && $hit !== []) {
  1023. return $hit;
  1024. }
  1025. }
  1026. return null;
  1027. }
  1028. /**
  1029. * 从 customer 行取字段(兼容列名大小写)
  1030. *
  1031. * @param string[] $candidates
  1032. */
  1033. protected function mprocCustomerPickField(array $row, array $candidates): string
  1034. {
  1035. foreach ($candidates as $want) {
  1036. $lw = strtolower($want);
  1037. foreach ($row as $k => $v) {
  1038. if (!is_string($k)) {
  1039. continue;
  1040. }
  1041. if (strtolower($k) !== $lw) {
  1042. continue;
  1043. }
  1044. $s = trim((string)$v);
  1045. if ($s !== '') {
  1046. return $s;
  1047. }
  1048. }
  1049. }
  1050. return '';
  1051. }
  1052. /**
  1053. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  1054. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  1055. *
  1056. * @param \think\db\Query $query
  1057. */
  1058. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  1059. {
  1060. $kw = trim((string)$search);
  1061. if ($kw === '') {
  1062. return;
  1063. }
  1064. $map = self::$mprocProcuremenColumns;
  1065. if (!is_array($map) || $map === []) {
  1066. return;
  1067. }
  1068. $like = '%' . addcslashes($kw, '%_\\') . '%';
  1069. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  1070. $detailCols = [];
  1071. foreach ($wantLower as $low) {
  1072. if (isset($map[$low])) {
  1073. $detailCols[] = $map[$low];
  1074. }
  1075. }
  1076. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  1077. $idCol = isset($map['id']) ? $map['id'] : 'id';
  1078. $poSidList = [];
  1079. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  1080. try {
  1081. $col = Db::table('purchase_order')
  1082. ->where(function ($sub) use ($like, $poWant) {
  1083. $firstPo = true;
  1084. foreach ($poWant as $pf) {
  1085. if ($firstPo) {
  1086. $sub->where($pf, 'like', $like);
  1087. $firstPo = false;
  1088. } else {
  1089. $sub->whereOr($pf, 'like', $like);
  1090. }
  1091. }
  1092. })
  1093. ->column('scydgy_id');
  1094. if (is_array($col)) {
  1095. foreach ($col as $v) {
  1096. $id = (int)$v;
  1097. if ($this->mprocIsValidScydgyRowId($id)) {
  1098. $poSidList[$id] = true;
  1099. }
  1100. }
  1101. }
  1102. $poSidList = array_keys($poSidList);
  1103. } catch (\Throwable $e) {
  1104. $poSidList = [];
  1105. }
  1106. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  1107. $first = true;
  1108. foreach ($detailCols as $col) {
  1109. if ($first) {
  1110. $q2->where($col, 'like', $like);
  1111. $first = false;
  1112. } else {
  1113. $q2->whereOr($col, 'like', $like);
  1114. }
  1115. }
  1116. if ($poSidList !== []) {
  1117. if ($first) {
  1118. $q2->where($scydgyCol, 'in', $poSidList);
  1119. $first = false;
  1120. } else {
  1121. $q2->whereOr($scydgyCol, 'in', $poSidList);
  1122. }
  1123. }
  1124. if ($first) {
  1125. $q2->where($idCol, '=', 0);
  1126. }
  1127. });
  1128. }
  1129. /**
  1130. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  1131. * - draft:status_name = 未提交
  1132. * - submitted:status_name = 已提交
  1133. * - done:status_name = 已完成
  1134. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  1135. *
  1136. * @param mixed $query
  1137. * @param string $tab draft|submitted|done
  1138. * @param string|null $statusNameCol 真实列名,如 status_name
  1139. */
  1140. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  1141. {
  1142. if ($statusNameCol === null) {
  1143. return;
  1144. }
  1145. $map = [
  1146. 'draft' => '未提交',
  1147. 'submitted' => '已提交',
  1148. 'done' => '已完成',
  1149. ];
  1150. $label = $map[$tab] ?? '未提交';
  1151. $query->where($statusNameCol, '=', $label);
  1152. }
  1153. /**
  1154. * 按登录态解析 customer 行
  1155. *
  1156. * @return array<string, mixed>|null
  1157. */
  1158. protected function mprocResolveCustomerUserForSession(array $user): ?array
  1159. {
  1160. if (!empty($user['is_admin'])) {
  1161. return null;
  1162. }
  1163. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1164. if ($cuId > 0) {
  1165. try {
  1166. $row = Db::table('customer')->where('id', $cuId)->find();
  1167. } catch (\Throwable $e) {
  1168. $row = null;
  1169. }
  1170. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  1171. return $row;
  1172. }
  1173. }
  1174. $account = trim((string)($user['account'] ?? ''));
  1175. if ($account !== '') {
  1176. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  1177. if ($byAcc !== null) {
  1178. return $byAcc;
  1179. }
  1180. }
  1181. $phone = trim((string)($user['phone'] ?? ''));
  1182. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1183. return $this->mprocFindCustomerUserByMobile($phone);
  1184. }
  1185. $uname = trim((string)($user['username'] ?? ''));
  1186. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1187. return $this->mprocFindCustomerUserByMobile($uname);
  1188. }
  1189. return null;
  1190. }
  1191. /**
  1192. * customer 表字段 →「我的」展示结构
  1193. *
  1194. * @param array<string, mixed> $cu
  1195. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  1196. */
  1197. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1198. {
  1199. $nm = trim((string)($cu['username'] ?? ''));
  1200. $phone = trim((string)($cu['phone'] ?? ''));
  1201. if ($phone === '') {
  1202. $phone = trim((string)($cu['account'] ?? ''));
  1203. }
  1204. return [
  1205. 'company_name' => trim((string)($cu['company_name'] ?? '')),
  1206. 'contact_name' => $nm,
  1207. 'phone' => $phone,
  1208. 'email' => trim((string)($cu['email'] ?? '')),
  1209. ];
  1210. }
  1211. /**
  1212. * 管理员「我的」:admin 表
  1213. *
  1214. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  1215. */
  1216. protected function mprocProfileForAdmin(array $user): array
  1217. {
  1218. $uname = trim((string)($user['username'] ?? ''));
  1219. $out = [
  1220. 'company_name' => '管理员',
  1221. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1222. 'phone' => trim((string)($user['phone'] ?? '')),
  1223. 'email' => '',
  1224. ];
  1225. if ($uname === '') {
  1226. return $out;
  1227. }
  1228. try {
  1229. $row = Db::name('admin')->where('username', $uname)->find();
  1230. } catch (\Throwable $e) {
  1231. $row = null;
  1232. }
  1233. if (!is_array($row) || $row === []) {
  1234. return $out;
  1235. }
  1236. $nick = trim((string)($row['nickname'] ?? ''));
  1237. if ($nick !== '') {
  1238. $out['contact_name'] = $nick;
  1239. }
  1240. $mob = trim((string)($row['mobile'] ?? ''));
  1241. if ($mob !== '') {
  1242. $out['phone'] = $mob;
  1243. }
  1244. $em = trim((string)($row['email'] ?? ''));
  1245. if ($em !== '') {
  1246. $out['email'] = $em;
  1247. }
  1248. return $out;
  1249. }
  1250. /**
  1251. * 旧会话补全 customer_id 等字段
  1252. */
  1253. protected function mprocSyncSessionCustomerUser(array $user): array
  1254. {
  1255. if (!empty($user['is_admin'])) {
  1256. return $user;
  1257. }
  1258. $cu = $this->mprocResolveCustomerUserForSession($user);
  1259. if (!$cu) {
  1260. return $user;
  1261. }
  1262. $id = (int)($cu['id'] ?? 0);
  1263. $user['customer_id'] = $id;
  1264. $user['customer_user_id'] = $id;
  1265. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1266. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1267. $user['account'] = trim((string)($cu['account'] ?? ''));
  1268. $mob = trim((string)($cu['phone'] ?? ''));
  1269. if ($mob === '') {
  1270. $mob = trim((string)($cu['account'] ?? ''));
  1271. }
  1272. if ($mob !== '') {
  1273. $user['phone'] = $mob;
  1274. }
  1275. $token = Session::get('mproc_token');
  1276. if ($token) {
  1277. $user['login_time'] = (int)($user['login_time'] ?? time());
  1278. $tok = trim((string)$token);
  1279. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1280. if (!$this->mprocIsSignedAuthToken($tok)) {
  1281. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1282. }
  1283. }
  1284. return $user;
  1285. }
  1286. /**
  1287. * 「我的」:普通用户 customer;管理员 admin
  1288. */
  1289. protected function mprocProfileForUser(array $user)
  1290. {
  1291. if (!empty($user['is_admin'])) {
  1292. return $this->mprocProfileForAdmin($user);
  1293. }
  1294. $cu = $this->mprocResolveCustomerUserForSession($user);
  1295. if (is_array($cu) && $cu !== []) {
  1296. return $this->mprocProfileFromCustomerUserRow($cu);
  1297. }
  1298. $phone = trim((string)($user['phone'] ?? ''));
  1299. if ($phone === '') {
  1300. $phone = trim((string)($user['account'] ?? ''));
  1301. }
  1302. return [
  1303. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1304. 'contact_name' => trim((string)($user['username'] ?? '')),
  1305. 'phone' => $phone,
  1306. 'email' => '',
  1307. ];
  1308. }
  1309. protected function mprocIsValidScydgyRowId($id): bool
  1310. {
  1311. return (int)$id !== 0;
  1312. }
  1313. /**
  1314. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1315. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1316. *
  1317. * @param array $row 引用:明细行
  1318. * @param array $poRow purchase_order 一行
  1319. */
  1320. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1321. {
  1322. $pl = array_change_key_case($poRow, CASE_LOWER);
  1323. $hdr = [
  1324. 'ccydh' => 'CCYDH',
  1325. 'cyjmc' => 'CYJMC',
  1326. 'cdf' => 'CDF',
  1327. 'cgzzxmc' => 'cGzzxMc',
  1328. 'cgymc' => 'CGYMC',
  1329. 'cdxmc' => 'CDXMC',
  1330. 'ngzl' => 'NGZL',
  1331. 'cdw' => 'CDW',
  1332. 'cgybh' => 'CGYBH',
  1333. ];
  1334. foreach ($hdr as $lk => $out) {
  1335. if (!array_key_exists($lk, $pl)) {
  1336. continue;
  1337. }
  1338. $v = $pl[$lk];
  1339. if ($v !== null && $v !== '') {
  1340. $row[$out] = $v;
  1341. }
  1342. }
  1343. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1344. $qtyRaw = '';
  1345. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1346. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1347. $qtyRaw = trim((string)$pl[$qk]);
  1348. break;
  1349. }
  1350. }
  1351. if ($qtyRaw === '') {
  1352. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1353. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1354. $qtyRaw = trim((string)$poRow[$qk]);
  1355. break;
  1356. }
  1357. }
  1358. }
  1359. if ($qtyRaw !== '') {
  1360. $row['This_quantity'] = $qtyRaw;
  1361. }
  1362. $ceilRaw = '';
  1363. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1364. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1365. $ceilRaw = trim((string)$pl[$ck]);
  1366. break;
  1367. }
  1368. }
  1369. if ($ceilRaw === '') {
  1370. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1371. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1372. $ceilRaw = trim((string)$poRow[$ck]);
  1373. break;
  1374. }
  1375. }
  1376. }
  1377. if ($ceilRaw !== '') {
  1378. $row['ceilingPrice'] = $ceilRaw;
  1379. }
  1380. $sysRq = '';
  1381. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1382. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1383. $sysRq = trim((string)$pl[$sk]);
  1384. break;
  1385. }
  1386. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1387. $sysRq = trim((string)$poRow[$sk]);
  1388. break;
  1389. }
  1390. }
  1391. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1392. $row['sys_rq'] = $sysRq;
  1393. }
  1394. $deliveryDeadline = '';
  1395. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1396. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1397. $deliveryDeadline = trim((string)$pl[$dk]);
  1398. break;
  1399. }
  1400. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1401. $deliveryDeadline = trim((string)$poRow[$dk]);
  1402. break;
  1403. }
  1404. }
  1405. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1406. $row['delivery_deadline'] = $deliveryDeadline;
  1407. }
  1408. }
  1409. /**
  1410. * 统一取年月日(无效则空串)
  1411. */
  1412. protected function mprocFormatYmdValue($raw): string
  1413. {
  1414. $s = trim((string)$raw);
  1415. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1416. return '';
  1417. }
  1418. $s = str_replace(['/', '.'], '-', $s);
  1419. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1420. return $m[1];
  1421. }
  1422. $ts = strtotime(str_replace('T', ' ', $s));
  1423. if ($ts === false || $ts <= 0) {
  1424. return '';
  1425. }
  1426. return date('Y-m-d', $ts);
  1427. }
  1428. /**
  1429. * 列表展示:招标截止 / 交货截止
  1430. *
  1431. * @param array<string, mixed> $row
  1432. */
  1433. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1434. {
  1435. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1436. $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
  1437. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1438. $row['mproc_bid_deadline_display'] = $bid;
  1439. // 完整截止时间供前端保存前校验(含时分秒)
  1440. $row['mproc_bid_deadline'] = $sysRqRaw;
  1441. $row['mproc_delivery_deadline_display'] = $del;
  1442. $row['mproc_delivery_deadline'] = $del;
  1443. }
  1444. /**
  1445. * 明细对应主表的交货截止日期 Y-m-d
  1446. *
  1447. * @param array<string, mixed> $row
  1448. */
  1449. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1450. {
  1451. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1452. if ($fromRow !== '') {
  1453. return $fromRow;
  1454. }
  1455. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1456. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1457. return '';
  1458. }
  1459. try {
  1460. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1461. } catch (\Throwable $e) {
  1462. $po = null;
  1463. }
  1464. if (!is_array($po)) {
  1465. return '';
  1466. }
  1467. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1468. }
  1469. /**
  1470. * 主表报价截止时间(未设置则视为未截止)
  1471. *
  1472. * @param array<string, mixed>|null $po
  1473. */
  1474. protected function mprocResolveSysRqFromPo(?array $po): string
  1475. {
  1476. if (!is_array($po)) {
  1477. return '';
  1478. }
  1479. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1480. if ($sr === '') {
  1481. $pl = array_change_key_case($po, CASE_LOWER);
  1482. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1483. }
  1484. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1485. }
  1486. /**
  1487. * 从主表/明细解析订单号
  1488. *
  1489. * @param array<string, mixed>|null $po
  1490. * @param array<string, mixed>|null $row
  1491. */
  1492. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1493. {
  1494. foreach ([$po, $row] as $src) {
  1495. if (!is_array($src)) {
  1496. continue;
  1497. }
  1498. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1499. if ($c !== '') {
  1500. return $c;
  1501. }
  1502. }
  1503. return '';
  1504. }
  1505. /**
  1506. * 批量:已开标验证的订单号集合(本请求内可复用)
  1507. *
  1508. * @var array<string, bool>|null
  1509. */
  1510. protected $mprocBidOpenVerifiedSet = null;
  1511. /**
  1512. * @param array<int, string> $ccydhs
  1513. * @return array<string, bool>
  1514. */
  1515. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1516. {
  1517. $set = [];
  1518. $list = [];
  1519. foreach ($ccydhs as $c) {
  1520. $c = trim((string)$c);
  1521. if ($c !== '') {
  1522. $list[$c] = true;
  1523. }
  1524. }
  1525. if ($list === []) {
  1526. return $set;
  1527. }
  1528. try {
  1529. $rows = Db::table('purchase_order_bid_open')
  1530. ->where('ccydh', 'in', array_keys($list))
  1531. ->field('ccydh')
  1532. ->select();
  1533. if (!is_array($rows)) {
  1534. return $set;
  1535. }
  1536. foreach ($rows as $row) {
  1537. if (!is_array($row)) {
  1538. continue;
  1539. }
  1540. $c = trim((string)($row['ccydh'] ?? ''));
  1541. if ($c !== '') {
  1542. $set[$c] = true;
  1543. }
  1544. }
  1545. } catch (\Throwable $e) {
  1546. return [];
  1547. }
  1548. return $set;
  1549. }
  1550. /**
  1551. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1552. */
  1553. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1554. {
  1555. $ccydh = trim($ccydh);
  1556. if ($ccydh === '') {
  1557. return false;
  1558. }
  1559. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1560. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1561. }
  1562. try {
  1563. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1564. return is_array($row);
  1565. } catch (\Throwable $e) {
  1566. return false;
  1567. }
  1568. }
  1569. /**
  1570. * @param array<string, mixed>|null $po
  1571. * @param array<string, mixed>|null $row
  1572. */
  1573. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1574. {
  1575. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1576. }
  1577. /**
  1578. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1579. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1580. *
  1581. * @param array<string, mixed>|null $po
  1582. */
  1583. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1584. {
  1585. $raw = $this->mprocResolveSysRqFromPo($po);
  1586. if ($raw === '') {
  1587. return false;
  1588. }
  1589. $ts = strtotime(str_replace('T', ' ', $raw));
  1590. if ($ts === false || $ts <= 0) {
  1591. return false;
  1592. }
  1593. return time() >= $ts;
  1594. }
  1595. /**
  1596. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1597. *
  1598. * @param array<string, mixed>|null $po
  1599. */
  1600. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1601. {
  1602. // 以库中最新主表为准,避免内存中旧快照
  1603. $freshPo = null;
  1604. if (is_array($po)) {
  1605. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1606. if ($this->mprocIsValidScydgyRowId($sid)) {
  1607. try {
  1608. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1609. } catch (\Throwable $e) {
  1610. $freshPo = null;
  1611. }
  1612. }
  1613. }
  1614. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1615. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1616. throw new \InvalidArgumentException(
  1617. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1618. );
  1619. }
  1620. }
  1621. /**
  1622. * 保存前:截止时间 + 已开标均不可再改
  1623. *
  1624. * @param array<string, mixed>|null $po
  1625. * @param array<string, mixed>|null $row
  1626. */
  1627. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1628. {
  1629. $sid = 0;
  1630. if (is_array($row)) {
  1631. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1632. }
  1633. if ($sid === 0 && is_array($po)) {
  1634. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1635. }
  1636. // 手工询价无招标截止、不开标
  1637. if ($sid < 0) {
  1638. return;
  1639. }
  1640. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1641. $freshPo = is_array($po) ? $po : null;
  1642. if (is_array($po)) {
  1643. if ($this->mprocIsValidScydgyRowId($sid)) {
  1644. try {
  1645. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1646. if (is_array($got)) {
  1647. $freshPo = $got;
  1648. }
  1649. } catch (\Throwable $e) {
  1650. }
  1651. }
  1652. }
  1653. // 保存场景不走列表缓存,直接查库
  1654. $prev = $this->mprocBidOpenVerifiedSet;
  1655. $this->mprocBidOpenVerifiedSet = null;
  1656. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1657. $this->mprocBidOpenVerifiedSet = $prev;
  1658. if ($opened) {
  1659. throw new \InvalidArgumentException(
  1660. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1661. );
  1662. }
  1663. }
  1664. /**
  1665. * 主单已完结后:中标 / 未中标
  1666. *
  1667. * @param array<string, mixed> $row
  1668. * @param array<string, mixed>|null $po
  1669. */
  1670. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1671. {
  1672. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1673. return '';
  1674. }
  1675. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1676. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1677. }
  1678. /**
  1679. * 手机端左侧 Tab:
  1680. * 询价:rfq / rfq_submitted(手工单 scydgy_id&lt;0,仅未提交/已提交)
  1681. * 报价:draft / submitted / done(协助下发)
  1682. *
  1683. * @param array<string, mixed> $row
  1684. * @param array<string, mixed>|null $po
  1685. */
  1686. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1687. {
  1688. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1689. // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
  1690. if ($sid < 0) {
  1691. if ($effectiveSn === '已提交'
  1692. || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1693. return 'rfq_submitted';
  1694. }
  1695. return 'rfq';
  1696. }
  1697. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1698. return 'done';
  1699. }
  1700. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
  1701. || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1702. // 已开标或已过招标截止 →「已完成」
  1703. return 'done';
  1704. }
  1705. if ($effectiveSn === '已提交') {
  1706. return 'submitted';
  1707. }
  1708. return 'draft';
  1709. }
  1710. /**
  1711. * @return string[]
  1712. */
  1713. protected function mprocListTabWhitelist(): array
  1714. {
  1715. return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
  1716. }
  1717. /**
  1718. * 兼容旧地址 tab=rfq_done → 询价已提交
  1719. */
  1720. protected function mprocNormalizeListTab(string $tab): string
  1721. {
  1722. if ($tab === 'rfq_done') {
  1723. return 'rfq_submitted';
  1724. }
  1725. if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
  1726. return 'draft';
  1727. }
  1728. return $tab;
  1729. }
  1730. protected function mprocIsDoneListTab(string $tab): bool
  1731. {
  1732. return $tab === 'done';
  1733. }
  1734. protected function mprocIsRfqListTab(string $tab): bool
  1735. {
  1736. return $tab === 'rfq' || $tab === 'rfq_submitted';
  1737. }
  1738. /**
  1739. * 复合 Tab → 状态维度:draft|submitted|done
  1740. */
  1741. protected function mprocStatusFromListTab(string $tab): string
  1742. {
  1743. if ($tab === 'rfq' || $tab === 'draft') {
  1744. return 'draft';
  1745. }
  1746. if ($tab === 'rfq_submitted' || $tab === 'submitted') {
  1747. return 'submitted';
  1748. }
  1749. if ($this->mprocIsDoneListTab($tab)) {
  1750. return 'done';
  1751. }
  1752. return 'draft';
  1753. }
  1754. /**
  1755. * 同一订单号 + 供应商合并为一张卡片
  1756. *
  1757. * @param array<int, array<string, mixed>> $rows
  1758. * @return array<int, array<string, mixed>>
  1759. */
  1760. protected function mprocGroupRowsByOrder(array $rows): array
  1761. {
  1762. $groups = [];
  1763. $order = [];
  1764. foreach ($rows as $row) {
  1765. if (!is_array($row)) {
  1766. continue;
  1767. }
  1768. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1769. $cname = trim((string)($row['company_name'] ?? ''));
  1770. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1771. if (!isset($groups[$key])) {
  1772. $groups[$key] = [
  1773. 'group_key' => $key,
  1774. 'CCYDH' => $ccydh,
  1775. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1776. 'company_name' => $cname,
  1777. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  1778. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  1779. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  1780. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  1781. 'lines' => [],
  1782. ];
  1783. $order[] = $key;
  1784. } else {
  1785. if ($groups[$key]['mproc_delivery_deadline'] === ''
  1786. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  1787. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  1788. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  1789. }
  1790. if ($groups[$key]['mproc_bid_deadline'] === ''
  1791. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  1792. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  1793. }
  1794. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  1795. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  1796. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  1797. }
  1798. }
  1799. $groups[$key]['lines'][] = $row;
  1800. }
  1801. $out = [];
  1802. foreach ($order as $key) {
  1803. $g = $groups[$key];
  1804. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1805. usort($lines, function ($a, $b) {
  1806. $sa = (int)($a['scydgy_id'] ?? 0);
  1807. $sb = (int)($b['scydgy_id'] ?? 0);
  1808. if ($sa !== $sb) {
  1809. return $sa <=> $sb;
  1810. }
  1811. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1812. });
  1813. $g['lines'] = $lines;
  1814. $g['line_count'] = count($lines);
  1815. $canEdit = false;
  1816. $bidOpen = false;
  1817. foreach ($lines as $ln) {
  1818. if (!is_array($ln)) {
  1819. continue;
  1820. }
  1821. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1822. $canEdit = true;
  1823. }
  1824. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  1825. $bidOpen = true;
  1826. }
  1827. }
  1828. $g['can_edit'] = $canEdit ? 1 : 0;
  1829. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  1830. $remark = '';
  1831. $doneLabel = '';
  1832. $pickResult = '';
  1833. $hasWin = false;
  1834. $hasLose = false;
  1835. $hasExpired = false;
  1836. foreach ($lines as $ln) {
  1837. if (!is_array($ln)) {
  1838. continue;
  1839. }
  1840. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1841. if ($rm !== '' && $remark === '') {
  1842. $remark = $rm;
  1843. }
  1844. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1845. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1846. if ($pr === '中标' || $dl === '中标') {
  1847. $hasWin = true;
  1848. } elseif ($pr === '未中标' || $dl === '未中标') {
  1849. $hasLose = true;
  1850. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  1851. $hasExpired = true;
  1852. }
  1853. }
  1854. if ($hasWin) {
  1855. $doneLabel = '中标';
  1856. $pickResult = '中标';
  1857. } elseif ($hasLose) {
  1858. $doneLabel = '未中标';
  1859. $pickResult = '未中标';
  1860. } elseif ($hasExpired) {
  1861. $doneLabel = '已截止';
  1862. $pickResult = '';
  1863. }
  1864. $g['remark'] = $remark;
  1865. $g['mproc_done_label'] = $doneLabel;
  1866. $g['mproc_pick_result'] = $pickResult;
  1867. $out[] = $g;
  1868. }
  1869. return $out;
  1870. }
  1871. /**
  1872. * 查询 purchase_order_detail 列表(订单页)
  1873. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  1874. * 有搜索词时:在当前 Tab 内做关键字匹配
  1875. *
  1876. * @param string $tab draft|submitted|done
  1877. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  1878. * @return array{rows: array, done_no_status: int}
  1879. */
  1880. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  1881. {
  1882. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  1883. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  1884. $userWhere = $this->mprocListWhereForLoginUser($user);
  1885. if ($userWhere !== []) {
  1886. $query->where($userWhere);
  1887. }
  1888. if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
  1889. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  1890. }
  1891. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  1892. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  1893. try {
  1894. $rows = $query->limit(500)->select();
  1895. } catch (\Throwable $e) {
  1896. $rows = [];
  1897. }
  1898. if (!is_array($rows)) {
  1899. $rows = [];
  1900. }
  1901. $poBySid = [];
  1902. $sidList = [];
  1903. foreach ($rows as $r0) {
  1904. if (!is_array($r0)) {
  1905. continue;
  1906. }
  1907. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  1908. if ($this->mprocIsValidScydgyRowId($sid0)) {
  1909. $sidList[$sid0] = true;
  1910. }
  1911. }
  1912. if ($sidList !== []) {
  1913. try {
  1914. $poRows = Db::table('purchase_order')
  1915. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  1916. ->select();
  1917. if (is_array($poRows)) {
  1918. foreach ($poRows as $pr) {
  1919. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1920. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1921. $poBySid[$sidk] = $pr;
  1922. }
  1923. }
  1924. }
  1925. } catch (\Throwable $e) {
  1926. }
  1927. }
  1928. $ccydhForBid = [];
  1929. foreach ($poBySid as $pr) {
  1930. if (!is_array($pr)) {
  1931. continue;
  1932. }
  1933. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  1934. if ($c !== '') {
  1935. $ccydhForBid[$c] = true;
  1936. }
  1937. }
  1938. foreach ($rows as $r0) {
  1939. if (!is_array($r0)) {
  1940. continue;
  1941. }
  1942. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  1943. if ($c !== '') {
  1944. $ccydhForBid[$c] = true;
  1945. }
  1946. }
  1947. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  1948. foreach ($rows as &$row) {
  1949. if (!is_array($row)) {
  1950. continue;
  1951. }
  1952. // 废弃明细不在手机端展示
  1953. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
  1954. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
  1955. $row = null;
  1956. continue;
  1957. }
  1958. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  1959. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1960. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  1961. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  1962. }
  1963. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  1964. $oldSn = trim((string)($row['status_name'] ?? ''));
  1965. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  1966. $row['status_name'] = $effectiveSn;
  1967. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  1968. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  1969. }
  1970. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  1971. $row['mproc_list_tab'] = $listTab;
  1972. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  1973. if ((int)$row['mproc_is_rfq'] === 1) {
  1974. // 手工询价不展示招标/交货截止,也不走开标截止逻辑
  1975. $row['mproc_bid_deadline'] = '';
  1976. $row['mproc_bid_deadline_display'] = '';
  1977. $row['mproc_delivery_deadline'] = '';
  1978. $row['mproc_delivery_deadline_display'] = '';
  1979. $row['mproc_deadline_reached'] = 0;
  1980. $row['mproc_bid_open_verified'] = 0;
  1981. $row['mproc_pick_result'] = '';
  1982. } else {
  1983. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  1984. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  1985. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  1986. }
  1987. if ($row['mproc_pick_result'] !== '') {
  1988. $row['mproc_done_label'] = $row['mproc_pick_result'];
  1989. } elseif ($this->mprocIsDoneListTab($listTab) && (
  1990. (int)$row['mproc_deadline_reached'] === 1
  1991. || (int)$row['mproc_bid_open_verified'] === 1
  1992. )) {
  1993. $row['mproc_done_label'] = '已截止';
  1994. } else {
  1995. $row['mproc_done_label'] = '';
  1996. }
  1997. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  1998. if (!isset($row['status_name']) || $row['status_name'] === null) {
  1999. $row['status_name'] = '';
  2000. } else {
  2001. $row['status_name'] = trim((string)$row['status_name']);
  2002. }
  2003. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2004. $am = $row['amount'] ?? null;
  2005. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  2006. $row['amount_display'] = '';
  2007. } else {
  2008. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  2009. }
  2010. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2011. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2012. $row['delivery_display'] = $m[1];
  2013. } elseif ($dv !== '') {
  2014. $row['delivery_display'] = $dv;
  2015. } else {
  2016. $row['delivery_display'] = '';
  2017. }
  2018. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2019. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2020. $this->mprocEnrichLeadDaysDisplay($row);
  2021. if ((int)$row['mproc_is_rfq'] === 1) {
  2022. $row['mproc_bid_deadline'] = '';
  2023. $row['mproc_bid_deadline_display'] = '';
  2024. $row['mproc_delivery_deadline'] = '';
  2025. $row['mproc_delivery_deadline_display'] = '';
  2026. } else {
  2027. $this->mprocEnrichOrderDeadlineDisplay($row);
  2028. }
  2029. $row['mproc_fill_hint'] = '';
  2030. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2031. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  2032. }
  2033. unset($row);
  2034. $rows = array_values(array_filter($rows, function ($r) {
  2035. return is_array($r);
  2036. }));
  2037. // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
  2038. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  2039. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  2040. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  2041. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  2042. }));
  2043. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  2044. if ($this->mprocIsDoneListTab((string)$tab)) {
  2045. $rows = array_values(array_filter($rows, function ($r) {
  2046. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  2047. }));
  2048. }
  2049. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  2050. $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
  2051. $groups = $this->mprocGroupRowsByOrder($rows);
  2052. return [
  2053. 'rows' => $rows ?: [],
  2054. 'groups' => $groups ?: [],
  2055. 'done_no_status' => (int)($statusNameCol === null),
  2056. ];
  2057. }
  2058. /**
  2059. * 按招标截止时间排序(无截止时间的排最后)
  2060. *
  2061. * @param array<int, array<string, mixed>> $rows
  2062. * @param string $dir asc|desc
  2063. * @return array<int, array<string, mixed>>
  2064. */
  2065. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  2066. {
  2067. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  2068. usort($rows, function ($a, $b) use ($dir) {
  2069. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  2070. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  2071. $ha = $ta > 0;
  2072. $hb = $tb > 0;
  2073. if ($ha !== $hb) {
  2074. return $ha ? -1 : 1;
  2075. }
  2076. if ($ha && $ta !== $tb) {
  2077. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  2078. }
  2079. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  2080. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  2081. return $idb <=> $ida;
  2082. });
  2083. return array_values($rows);
  2084. }
  2085. /**
  2086. * @param array<string, mixed> $row
  2087. */
  2088. protected function mprocBidDeadlineSortTs(array $row): int
  2089. {
  2090. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  2091. if ($raw === '') {
  2092. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  2093. }
  2094. if ($raw === '') {
  2095. return 0;
  2096. }
  2097. $ts = strtotime(str_replace('T', ' ', $raw));
  2098. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  2099. }
  2100. /**
  2101. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  2102. *
  2103. * @param array<string, mixed> $row
  2104. */
  2105. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  2106. {
  2107. $months = max(1, $months);
  2108. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  2109. if ($since === false) {
  2110. return true;
  2111. }
  2112. $candidates = [
  2113. $row['mproc_bid_deadline'] ?? '',
  2114. $row['sys_rq'] ?? '',
  2115. $row['SYS_RQ'] ?? '',
  2116. $row['mproc_bid_deadline_display'] ?? '',
  2117. $row['mproc_delivery_deadline'] ?? '',
  2118. $row['delivery_deadline'] ?? '',
  2119. $row['mproc_delivery_deadline_display'] ?? '',
  2120. $row['createtime'] ?? '',
  2121. $row['updatetime'] ?? '',
  2122. ];
  2123. foreach ($candidates as $raw) {
  2124. $raw = trim((string)$raw);
  2125. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  2126. continue;
  2127. }
  2128. $ts = strtotime(str_replace('T', ' ', $raw));
  2129. if ($ts === false || $ts <= 0) {
  2130. continue;
  2131. }
  2132. return $ts >= $since;
  2133. }
  2134. return false;
  2135. }
  2136. /**
  2137. * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
  2138. *
  2139. * @param array<int, array<string, mixed>> $rows
  2140. * @return array<int, array<string, mixed>>
  2141. */
  2142. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  2143. {
  2144. $best = [];
  2145. $orderKeys = [];
  2146. foreach ($rows as $row) {
  2147. if (!is_array($row)) {
  2148. continue;
  2149. }
  2150. $cn = trim((string)($row['company_name'] ?? ''));
  2151. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2152. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  2153. if ($this->mprocIsValidScydgyRowId($sid)) {
  2154. $key = $cn . '|sid:' . $sid;
  2155. } else {
  2156. $key = $cn . '|eid:' . $eid;
  2157. }
  2158. if (!isset($best[$key])) {
  2159. $best[$key] = $row;
  2160. $orderKeys[] = $key;
  2161. continue;
  2162. }
  2163. $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
  2164. if ($eid > $prevEid) {
  2165. $best[$key] = $row;
  2166. }
  2167. }
  2168. $out = [];
  2169. foreach ($orderKeys as $key) {
  2170. if (isset($best[$key])) {
  2171. $out[] = $best[$key];
  2172. }
  2173. }
  2174. return $out;
  2175. }
  2176. /**
  2177. * status_name → 手机端左侧 Tab
  2178. */
  2179. protected function mprocStatusNameToListTab(string $statusName): string
  2180. {
  2181. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2182. $sn = trim($statusName);
  2183. return isset($map[$sn]) ? $map[$sn] : '';
  2184. }
  2185. /**
  2186. * 短信/邮件 focus_eid 应落在的列表 Tab
  2187. */
  2188. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2189. {
  2190. if ($focusEid <= 0) {
  2191. return '';
  2192. }
  2193. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2194. if ($idCol === null) {
  2195. return '';
  2196. }
  2197. try {
  2198. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2199. $qw = $this->mprocListWhereForLoginUser($user);
  2200. if ($qw !== []) {
  2201. $qrow->where($qw);
  2202. }
  2203. $dr = $qrow->find();
  2204. } catch (\Throwable $e) {
  2205. $dr = null;
  2206. }
  2207. if (!is_array($dr) || $dr === []) {
  2208. return '';
  2209. }
  2210. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2211. $po = null;
  2212. if ($this->mprocIsValidScydgyRowId($sid)) {
  2213. try {
  2214. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2215. } catch (\Throwable $e) {
  2216. $po = null;
  2217. }
  2218. }
  2219. return $this->mprocResolveListTabForRow(
  2220. $dr,
  2221. is_array($po) ? $po : null,
  2222. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2223. );
  2224. }
  2225. /**
  2226. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2227. *
  2228. * @param array<string, mixed> $bundle
  2229. * @param array<string, mixed> $user
  2230. * @return array<string, mixed>
  2231. */
  2232. protected function mprocEnsureFocusRowInList(
  2233. array $bundle,
  2234. int $focusEid,
  2235. array $user,
  2236. $statusNameCol,
  2237. string $tab = 'draft',
  2238. string $q = ''
  2239. ): array {
  2240. if ($focusEid <= 0) {
  2241. return $bundle;
  2242. }
  2243. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2244. $foundIdx = -1;
  2245. foreach ($rows as $idx => $r) {
  2246. if (!is_array($r)) {
  2247. continue;
  2248. }
  2249. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2250. $foundIdx = (int)$idx;
  2251. break;
  2252. }
  2253. }
  2254. if ($foundIdx > 0) {
  2255. $hit = $rows[$foundIdx];
  2256. array_splice($rows, $foundIdx, 1);
  2257. array_unshift($rows, $hit);
  2258. $bundle['rows'] = $rows;
  2259. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2260. return $bundle;
  2261. }
  2262. if ($foundIdx === 0) {
  2263. return $bundle;
  2264. }
  2265. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2266. if ($idCol === null) {
  2267. return $bundle;
  2268. }
  2269. try {
  2270. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2271. $qw = $this->mprocListWhereForLoginUser($user);
  2272. if ($qw !== []) {
  2273. $qrow->where($qw);
  2274. }
  2275. $dr = $qrow->find();
  2276. } catch (\Throwable $e) {
  2277. $dr = null;
  2278. }
  2279. if (!is_array($dr) || $dr === []) {
  2280. return $bundle;
  2281. }
  2282. $row = $dr;
  2283. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2284. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2285. $poRow = null;
  2286. if ($this->mprocIsValidScydgyRowId($sid)) {
  2287. try {
  2288. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2289. } catch (\Throwable $e) {
  2290. $poRow = null;
  2291. }
  2292. if (is_array($poRow)) {
  2293. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2294. }
  2295. }
  2296. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2297. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2298. if ($rowTab !== '' && $rowTab !== $tab) {
  2299. return $bundle;
  2300. }
  2301. $row['status_name'] = $effectiveSn;
  2302. $listTab = $rowTab;
  2303. $row['mproc_list_tab'] = $listTab;
  2304. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2305. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2306. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2307. if ($row['mproc_pick_result'] !== '') {
  2308. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2309. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2310. (int)$row['mproc_deadline_reached'] === 1
  2311. || (int)$row['mproc_bid_open_verified'] === 1
  2312. )) {
  2313. $row['mproc_done_label'] = '已截止';
  2314. } else {
  2315. $row['mproc_done_label'] = '';
  2316. }
  2317. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2318. $am = $row['amount'] ?? null;
  2319. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2320. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2321. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2322. $row['delivery_display'] = $m[1];
  2323. } elseif ($dv !== '') {
  2324. $row['delivery_display'] = $dv;
  2325. } else {
  2326. $row['delivery_display'] = '';
  2327. }
  2328. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2329. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2330. $this->mprocEnrichLeadDaysDisplay($row);
  2331. $this->mprocEnrichOrderDeadlineDisplay($row);
  2332. $row['mproc_fill_hint'] = '';
  2333. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2334. array_unshift($rows, $row);
  2335. $bundle['rows'] = $rows;
  2336. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2337. return $bundle;
  2338. }
  2339. /**
  2340. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2341. *
  2342. * @param array<string, mixed> $row
  2343. */
  2344. protected function mprocResolveDisplayThisQuantity(array $row): string
  2345. {
  2346. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2347. if ($qty !== '') {
  2348. return $qty;
  2349. }
  2350. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2351. if ($gzl === null || $gzl === '') {
  2352. return '';
  2353. }
  2354. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2355. }
  2356. /**
  2357. * 明细是否已填写单价或交货日期
  2358. *
  2359. * @param array<string, mixed> $row
  2360. */
  2361. protected function mprocDetailQuoteSubmitted(array $row): bool
  2362. {
  2363. $am = $row['amount'] ?? null;
  2364. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2365. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2366. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2367. return $amountFilled || $deliveryFilled;
  2368. }
  2369. /**
  2370. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2371. *
  2372. * @param array<string, mixed> $row
  2373. * @param array<string, mixed>|null $po
  2374. */
  2375. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2376. {
  2377. $sn = trim((string)($row['status_name'] ?? ''));
  2378. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2379. return $sn;
  2380. }
  2381. if (!is_array($po)) {
  2382. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2383. return '已提交';
  2384. }
  2385. if ($sn !== '') {
  2386. return $sn;
  2387. }
  2388. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2389. }
  2390. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2391. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2392. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2393. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2394. return '已提交';
  2395. }
  2396. if ($sn !== '') {
  2397. return $sn;
  2398. }
  2399. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2400. }
  2401. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2402. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2403. return '已完成';
  2404. }
  2405. if ($sn === '已提交') {
  2406. return '未通过';
  2407. }
  2408. return $sn !== '' ? $sn : '未提交';
  2409. }
  2410. /**
  2411. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2412. */
  2413. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2414. {
  2415. if ($detailId <= 0 || $statusNameCol === '') {
  2416. return;
  2417. }
  2418. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2419. if ($idCol === null || $idCol === '') {
  2420. return;
  2421. }
  2422. try {
  2423. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2424. } catch (\Throwable $e) {
  2425. }
  2426. }
  2427. /**
  2428. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2429. *
  2430. * @param array<string, mixed> $user
  2431. */
  2432. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2433. {
  2434. $userWhere = $this->mprocListWhereForLoginUser($user);
  2435. try {
  2436. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2437. if ($userWhere !== []) {
  2438. $query->where($userWhere);
  2439. }
  2440. $candidates = $query->limit(200)->select();
  2441. } catch (\Throwable $e) {
  2442. return;
  2443. }
  2444. if (!is_array($candidates) || $candidates === []) {
  2445. return;
  2446. }
  2447. $sidList = [];
  2448. foreach ($candidates as $cr) {
  2449. if (!is_array($cr)) {
  2450. continue;
  2451. }
  2452. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2453. if ($this->mprocIsValidScydgyRowId($sid)) {
  2454. $sidList[$sid] = true;
  2455. }
  2456. }
  2457. if ($sidList === []) {
  2458. return;
  2459. }
  2460. $poBySid = [];
  2461. try {
  2462. $poRows = Db::table('purchase_order')
  2463. ->where('scydgy_id', 'in', array_keys($sidList))
  2464. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2465. ->select();
  2466. if (is_array($poRows)) {
  2467. foreach ($poRows as $pr) {
  2468. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2469. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2470. $poBySid[$sidk] = $pr;
  2471. }
  2472. }
  2473. }
  2474. } catch (\Throwable $e) {
  2475. return;
  2476. }
  2477. if ($poBySid === []) {
  2478. return;
  2479. }
  2480. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2481. if ($idCol === null || $idCol === '') {
  2482. return;
  2483. }
  2484. foreach ($candidates as $cr) {
  2485. if (!is_array($cr)) {
  2486. continue;
  2487. }
  2488. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2489. if (!isset($poBySid[$sid])) {
  2490. continue;
  2491. }
  2492. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2493. if ($detailId <= 0) {
  2494. continue;
  2495. }
  2496. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2497. if ($targetSn === '已提交') {
  2498. continue;
  2499. }
  2500. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2501. }
  2502. }
  2503. /**
  2504. * 协助明细首页(需登录)
  2505. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2506. */
  2507. public function index()
  2508. {
  2509. $user = $this->mprocGetUser();
  2510. if (!$user) {
  2511. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2512. if ($pendingFocus > 0) {
  2513. $this->mprocRememberFocusEid($pendingFocus);
  2514. }
  2515. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2516. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2517. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2518. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2519. }
  2520. if ($safe !== '') {
  2521. Session::set('mproc_intended_url', $safe);
  2522. }
  2523. $this->redirect($this->mprocBuildLoginUrl($safe));
  2524. return;
  2525. }
  2526. // 管理员进质量评分,不进供应商报价列表
  2527. if (!empty($user['is_admin'])) {
  2528. $this->redirect(url('index/index/inboundscore', '', '', true));
  2529. return;
  2530. }
  2531. $user = $this->mprocSyncSessionCustomerUser($user);
  2532. $tabParamRaw = $this->request->get('tab', null);
  2533. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2534. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2535. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2536. // 旧地址 ?tab=me 表示「我的」
  2537. if ($tabParam === 'me') {
  2538. $mainTab = 'me';
  2539. }
  2540. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2541. $mainTab = 'orders';
  2542. }
  2543. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2544. $q = trim((string)$this->request->get('q', ''));
  2545. $mprocFocusEid = 0;
  2546. $focusEid = $this->mprocReadFocusEidFromRequest();
  2547. if ($focusEid > 0 && $mainTab === 'orders') {
  2548. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2549. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2550. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2551. Session::delete('mproc_focus_eid');
  2552. $focusEid = 0;
  2553. } else {
  2554. $mprocFocusEid = $focusEid;
  2555. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2556. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2557. if (!$focusFromUrl) {
  2558. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2559. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2560. }
  2561. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2562. if ($resolvedTab !== '') {
  2563. $tab = $resolvedTab;
  2564. }
  2565. }
  2566. }
  2567. }
  2568. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2569. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2570. $profile = $this->mprocProfileForUser($user);
  2571. $this->view->assign('mprocMainTab', $mainTab);
  2572. $this->view->assign('mprocTab', $tab);
  2573. $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
  2574. $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
  2575. $this->view->assign('mprocSearchQ', $q);
  2576. $this->view->assign('mprocProfile', $profile);
  2577. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2578. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2579. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2580. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2581. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2582. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2583. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2584. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2585. if ($mainTab === 'me') {
  2586. $this->view->assign('rows', []);
  2587. return $this->view->fetch();
  2588. }
  2589. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2590. if ($mprocFocusEid > 0) {
  2591. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2592. }
  2593. $this->view->assign('rows', $bundle['rows']);
  2594. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2595. return $this->view->fetch();
  2596. }
  2597. /**
  2598. * 协助明细列表 JSON(需登录)
  2599. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2600. */
  2601. public function mprocList()
  2602. {
  2603. $user = $this->mprocGetUser();
  2604. if (!$user) {
  2605. $this->error('请先登录', url('index/index/login'));
  2606. }
  2607. $user = $this->mprocSyncSessionCustomerUser($user);
  2608. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  2609. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  2610. if ($tabParam === 'me') {
  2611. $mainTab = 'me';
  2612. }
  2613. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2614. $mainTab = 'orders';
  2615. }
  2616. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2617. $q = trim((string)$this->request->request('q', ''));
  2618. if ($mainTab === 'me') {
  2619. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  2620. $this->success('ok', '', [
  2621. 'main_tab' => 'me',
  2622. 'tab' => $tab,
  2623. 'rows' => [],
  2624. 'profile' => $this->mprocProfileForUser($user),
  2625. 'done_no_status' => 0,
  2626. ]);
  2627. }
  2628. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2629. if ((int)$this->request->request('clear_focus', 0) === 1) {
  2630. Session::delete('mproc_focus_eid');
  2631. $focusEid = 0;
  2632. $focusTab = '';
  2633. } else {
  2634. $focusEid = $this->mprocReadFocusEidFromRequest();
  2635. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  2636. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  2637. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  2638. Session::delete('mproc_focus_eid');
  2639. $focusEid = 0;
  2640. $focusTab = '';
  2641. }
  2642. }
  2643. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2644. if ($focusEid > 0) {
  2645. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  2646. }
  2647. $this->success('ok', '', array_merge([
  2648. 'main_tab' => 'orders',
  2649. 'tab' => $tab,
  2650. 'focus_tab' => $focusTab,
  2651. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  2652. 'focus_eid' => $focusEid,
  2653. ], $bundle));
  2654. }
  2655. /**
  2656. * 登录页(手机号验证码 / 账号密码)
  2657. */
  2658. public function login()
  2659. {
  2660. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  2661. $user = $this->mprocGetUser();
  2662. if ($user) {
  2663. $this->redirect($this->mprocBuildAfterLoginHomeUrl($user, $redirect));
  2664. }
  2665. if ($redirect !== '') {
  2666. Session::set('mproc_intended_url', $redirect);
  2667. }
  2668. $this->view->assign('mprocLoginRedirect', $redirect);
  2669. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  2670. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  2671. return $this->view->fetch();
  2672. }
  2673. /**
  2674. * 图形验证码(手机号登录用)
  2675. */
  2676. public function captcha($id = '')
  2677. {
  2678. $captcha = new Captcha((array)Config::get('captcha'));
  2679. return $captcha->entry($id);
  2680. }
  2681. /**
  2682. * 发送登录验证码(POST:phone、captcha)
  2683. */
  2684. public function sendSms()
  2685. {
  2686. if (!$this->request->isPost()) {
  2687. $this->error('请使用 POST');
  2688. }
  2689. $phone = trim((string)$this->request->post('phone', ''));
  2690. $captcha = trim((string)$this->request->post('captcha', ''));
  2691. if (!preg_match('/^1\d{10}$/', $phone)) {
  2692. $this->error('请输入正确的11位手机号');
  2693. }
  2694. if ($captcha === '') {
  2695. $this->error('请输入图形验证码');
  2696. }
  2697. if (!$this->mprocFindCustomerUserByMobile($phone)) {
  2698. $this->error('该手机号未开通或已禁用,请联系管理员');
  2699. }
  2700. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  2701. if (Cache::get('mproc_sms_wait_' . $phone)) {
  2702. $this->error('发送过于频繁,请稍后再试');
  2703. }
  2704. if (!Validate::is($captcha, 'captcha')) {
  2705. $this->error('图形验证码不正确');
  2706. }
  2707. $code = (string)random_int(100000, 999999);
  2708. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  2709. $ttl = max(60, min(600, $ttl));
  2710. Cache::set('mproc_code_' . $phone, $code, $ttl);
  2711. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  2712. try {
  2713. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  2714. if ($tpl === '') {
  2715. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  2716. }
  2717. $content = str_replace('{code}', $code, $tpl);
  2718. $this->mprocSmsSend($phone, $content);
  2719. } catch (\Exception $e) {
  2720. Cache::rm('mproc_code_' . $phone);
  2721. Cache::rm('mproc_sms_wait_' . $phone);
  2722. $this->error($e->getMessage());
  2723. }
  2724. $this->success('验证码已发送');
  2725. }
  2726. /**
  2727. * 验证码登录(POST:phone、code)
  2728. */
  2729. public function doLogin()
  2730. {
  2731. if (!$this->request->isPost()) {
  2732. $this->error('请使用 POST');
  2733. }
  2734. $phone = trim((string)$this->request->post('phone', ''));
  2735. $code = trim((string)$this->request->post('code', ''));
  2736. if (!preg_match('/^1\d{10}$/', $phone)) {
  2737. $this->error('手机号格式不正确');
  2738. }
  2739. if (!preg_match('/^\d{6}$/', $code)) {
  2740. $this->error('请输入6位验证码');
  2741. }
  2742. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2743. $mock = Config::get('mproc.mock_sms_code');
  2744. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2745. Cache::rm('mproc_code_' . $phone);
  2746. } else {
  2747. $cached = Cache::get('mproc_code_' . $phone);
  2748. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2749. $this->error('验证码错误或已过期');
  2750. }
  2751. Cache::rm('mproc_code_' . $phone);
  2752. }
  2753. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2754. if (!$cu) {
  2755. $this->error('该手机号未开通或已禁用,请联系管理员');
  2756. }
  2757. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2758. }
  2759. /**
  2760. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2761. */
  2762. public function mprocRestore()
  2763. {
  2764. if (!$this->request->isPost()) {
  2765. $this->error('请使用 POST');
  2766. }
  2767. $token = $this->mprocReadTokenFromRequest();
  2768. $user = null;
  2769. if ($token !== '') {
  2770. $user = $this->mprocLoadUserByToken($token);
  2771. }
  2772. if (!$user) {
  2773. $user = $this->mprocUserFromRememberCookie();
  2774. if ($user) {
  2775. $token = $this->mprocPackSignedAuthToken($user);
  2776. }
  2777. }
  2778. if (!$user) {
  2779. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2780. }
  2781. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2782. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2783. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2784. $this->success('ok', $jump, [
  2785. 'mproc_token' => $token,
  2786. 'keep_hours' => $this->mprocKeepHours(),
  2787. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2788. ]);
  2789. }
  2790. /**
  2791. * 账号密码登录(POST:username、password)
  2792. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2793. */
  2794. public function doLoginPwd()
  2795. {
  2796. if (!$this->request->isPost()) {
  2797. $this->error('请使用 POST');
  2798. }
  2799. $username = trim((string)$this->request->post('username', ''));
  2800. $password = (string)$this->request->post('password', '');
  2801. if ($username === '' || $password === '') {
  2802. $this->error('请输入账号和密码');
  2803. }
  2804. $cu = $this->mprocFindCustomerUserByUsername($username);
  2805. if ($cu) {
  2806. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2807. $this->error('账号或密码错误');
  2808. }
  2809. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2810. }
  2811. // 管理员:表 admin
  2812. $row = null;
  2813. try {
  2814. $row = Db::name('admin')
  2815. ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
  2816. ->where('username', $username)
  2817. ->find();
  2818. } catch (\Throwable $e) {
  2819. $row = null;
  2820. }
  2821. if (!$row || !is_array($row)) {
  2822. $this->error('账号或密码错误');
  2823. }
  2824. $id = (int)($row['id'] ?? 0);
  2825. if (($row['status'] ?? '') == 'hidden') {
  2826. $this->error('该账号已禁用');
  2827. }
  2828. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  2829. $this->error('登录失败次数过多,请24小时后再试');
  2830. }
  2831. $salt = (string)($row['salt'] ?? '');
  2832. $hashStored = (string)($row['password'] ?? '');
  2833. $hashInput = md5(md5($password) . $salt);
  2834. if ($hashStored === '' || $hashInput !== $hashStored) {
  2835. if ($id > 0) {
  2836. try {
  2837. Db::name('admin')->where('id', $id)->update([
  2838. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  2839. 'updatetime' => time(),
  2840. ]);
  2841. } catch (\Throwable $e) {
  2842. }
  2843. }
  2844. $this->error('账号或密码错误');
  2845. }
  2846. if ($id > 0) {
  2847. try {
  2848. Db::name('admin')->where('id', $id)->update([
  2849. 'loginfailure' => 0,
  2850. 'updatetime' => time(),
  2851. ]);
  2852. } catch (\Throwable $e) {
  2853. }
  2854. }
  2855. $this->mprocFinishLogin([
  2856. 'phone' => trim((string)($row['mobile'] ?? '')),
  2857. 'company_name' => '',
  2858. 'username' => $username,
  2859. 'customer_user_id' => 0,
  2860. 'admin_id' => $id,
  2861. 'login_type' => 'pwd',
  2862. 'is_admin' => 1,
  2863. ]);
  2864. }
  2865. /**
  2866. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  2867. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  2868. */
  2869. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  2870. {
  2871. if (!empty($user['is_admin'])) {
  2872. return false;
  2873. }
  2874. $sn = trim((string)($row['status_name'] ?? ''));
  2875. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2876. return false;
  2877. }
  2878. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2879. // 手工询价无招标截止/开标限制
  2880. if ($sid >= 0) {
  2881. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  2882. return false;
  2883. }
  2884. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  2885. return false;
  2886. }
  2887. }
  2888. $uCo = trim((string)($user['company_name'] ?? ''));
  2889. if ($uCo === '') {
  2890. $uPhone = trim((string)($user['phone'] ?? ''));
  2891. if ($uPhone !== '') {
  2892. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  2893. }
  2894. }
  2895. $rCo = trim((string)($row['company_name'] ?? ''));
  2896. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  2897. return true;
  2898. }
  2899. $uPhone = trim((string)($user['phone'] ?? ''));
  2900. $rPhone = trim((string)($row['phone'] ?? ''));
  2901. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  2902. }
  2903. /**
  2904. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  2905. *
  2906. * @param array<string, mixed> $detailRow
  2907. */
  2908. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  2909. {
  2910. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  2911. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  2912. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  2913. try {
  2914. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2915. } catch (\Throwable $e) {
  2916. $po = null;
  2917. }
  2918. if (is_array($po)) {
  2919. $pl = array_change_key_case($po, CASE_LOWER);
  2920. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  2921. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  2922. $raw = trim((string)$pl[$ck]);
  2923. break;
  2924. }
  2925. }
  2926. if ($raw === '') {
  2927. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  2928. }
  2929. }
  2930. }
  2931. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  2932. return null;
  2933. }
  2934. return (float)$raw;
  2935. }
  2936. protected function mprocFormatCeilingPriceDisplay(float $n): string
  2937. {
  2938. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  2939. return $s === '' ? '0' : $s;
  2940. }
  2941. /**
  2942. * 确保 purchase_order_detail.lead_days 字段存在
  2943. */
  2944. protected function mprocEnsureLeadDaysColumn(): void
  2945. {
  2946. static $done = false;
  2947. if ($done) {
  2948. return;
  2949. }
  2950. $done = true;
  2951. try {
  2952. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  2953. if (empty($cols)) {
  2954. Db::execute(
  2955. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  2956. );
  2957. }
  2958. } catch (\Throwable $e) {
  2959. // 忽略:保存时再按列是否存在处理
  2960. }
  2961. }
  2962. /**
  2963. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  2964. */
  2965. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  2966. {
  2967. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  2968. return null;
  2969. }
  2970. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2971. $t2 = strtotime($m[1] . ' 00:00:00');
  2972. if ($t1 === false || $t2 === false) {
  2973. return null;
  2974. }
  2975. return (int)round(($t2 - $t1) / 86400);
  2976. }
  2977. protected function mprocAddDaysToToday(int $days): string
  2978. {
  2979. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  2980. if ($base === false) {
  2981. $base = time();
  2982. }
  2983. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  2984. }
  2985. /**
  2986. * @param array<string, mixed> $row
  2987. */
  2988. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  2989. {
  2990. $days = null;
  2991. $raw = $row['lead_days'] ?? null;
  2992. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  2993. $days = max(0, (int)$raw);
  2994. } else {
  2995. $dd = trim((string)($row['delivery_display'] ?? ''));
  2996. if ($dd === '') {
  2997. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2998. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2999. $dd = $m[1];
  3000. }
  3001. }
  3002. if ($dd !== '') {
  3003. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  3004. if ($calc !== null) {
  3005. $days = max(0, $calc);
  3006. }
  3007. }
  3008. }
  3009. if ($days !== null) {
  3010. $row['lead_days'] = $days;
  3011. $row['lead_days_display'] = (string)$days;
  3012. $row['lead_days_missing'] = 0;
  3013. } else {
  3014. $row['lead_days'] = '';
  3015. $row['lead_days_display'] = '';
  3016. $row['lead_days_missing'] = 1;
  3017. }
  3018. }
  3019. /**
  3020. * 保存单条协助明细的金额、交期、工期(内部)
  3021. *
  3022. * @param array<string, mixed> $user
  3023. * @param int $id
  3024. * @param string $amountRaw
  3025. * @param string $deliveryRaw
  3026. * @param string|int|null $leadDaysRaw
  3027. * @return string 工序名(用于批量错误提示)
  3028. */
  3029. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  3030. {
  3031. if ($id <= 0) {
  3032. throw new \InvalidArgumentException('参数错误');
  3033. }
  3034. $row = null;
  3035. try {
  3036. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  3037. if (!$row) {
  3038. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  3039. }
  3040. } catch (\Throwable $e) {
  3041. $row = null;
  3042. }
  3043. if (!$row || !is_array($row)) {
  3044. throw new \InvalidArgumentException('记录不存在');
  3045. }
  3046. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  3047. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3048. $po = null;
  3049. if ($this->mprocIsValidScydgyRowId($sid)) {
  3050. try {
  3051. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3052. } catch (\Throwable $e) {
  3053. $po = null;
  3054. }
  3055. if (is_array($po)) {
  3056. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3057. if ($gymc === '') {
  3058. $gymc = trim((string)($row['CGYMC'] ?? ''));
  3059. }
  3060. }
  3061. }
  3062. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  3063. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3064. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3065. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  3066. }
  3067. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  3068. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3069. if (!empty($user['is_admin'])) {
  3070. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  3071. }
  3072. // 截止后 / 已开标 canEdit=false,统一给明确文案
  3073. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3074. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  3075. }
  3076. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3077. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  3078. }
  3079. throw new \InvalidArgumentException($label . '无权修改');
  3080. }
  3081. $this->mprocEnsureLeadDaysColumn();
  3082. $amountRaw = trim($amountRaw);
  3083. $deliveryRaw = trim($deliveryRaw);
  3084. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  3085. $hasAmt = $amountRaw !== '';
  3086. $hasLead = $leadRaw !== '';
  3087. $hasDel = $deliveryRaw !== '';
  3088. $isManualRfq = ($sid < 0);
  3089. if ($isManualRfq) {
  3090. // 手工询价:只需填写单价
  3091. if (!$hasAmt) {
  3092. throw new \InvalidArgumentException($label . '请填写单价');
  3093. }
  3094. } else {
  3095. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  3096. if ($filledCount === 0) {
  3097. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  3098. }
  3099. if ($filledCount < 3) {
  3100. if (!$hasAmt) {
  3101. throw new \InvalidArgumentException($label . '请填写单价');
  3102. }
  3103. if (!$hasLead) {
  3104. throw new \InvalidArgumentException($label . '请填写工期');
  3105. }
  3106. throw new \InvalidArgumentException($label . '请填写交期');
  3107. }
  3108. }
  3109. $leadDays = null;
  3110. if ($leadRaw !== '') {
  3111. if (!preg_match('/^\d+$/', $leadRaw)) {
  3112. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  3113. }
  3114. $leadDays = (int)$leadRaw;
  3115. }
  3116. $data = [];
  3117. if ($amountRaw === '') {
  3118. $data['amount'] = null;
  3119. } else {
  3120. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  3121. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  3122. }
  3123. if ((float)$amountRaw <= 0) {
  3124. throw new \InvalidArgumentException($label . '单价必须大于0');
  3125. }
  3126. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  3127. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  3128. throw new \InvalidArgumentException(
  3129. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  3130. );
  3131. }
  3132. $data['amount'] = $amountRaw;
  3133. }
  3134. if ($deliveryRaw === '') {
  3135. $data['delivery'] = null;
  3136. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  3137. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3138. $timePart = date('H:i:s');
  3139. if ($existingDel !== '') {
  3140. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  3141. if ($tsEx !== false) {
  3142. $hms = date('H:i:s', $tsEx);
  3143. if ($hms !== '00:00:00') {
  3144. $timePart = $hms;
  3145. }
  3146. }
  3147. }
  3148. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  3149. } else {
  3150. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  3151. $ts = strtotime($deliveryRaw);
  3152. if ($ts === false) {
  3153. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  3154. }
  3155. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  3156. }
  3157. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  3158. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  3159. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  3160. }
  3161. if ($leadDays === null && !empty($data['delivery'])) {
  3162. $ymd = substr((string)$data['delivery'], 0, 10);
  3163. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  3164. if ($calc !== null) {
  3165. $leadDays = max(0, $calc);
  3166. }
  3167. }
  3168. $data['lead_days'] = $leadDays;
  3169. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  3170. if ($dcCol !== null) {
  3171. $shouldStampQuoteTime = false;
  3172. if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  3173. $shouldStampQuoteTime = true;
  3174. }
  3175. // 手工询价只填单价:有单价也记报价时间
  3176. if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
  3177. $shouldStampQuoteTime = true;
  3178. }
  3179. if ($shouldStampQuoteTime) {
  3180. $data[$dcCol] = date('Y-m-d H:i:s');
  3181. }
  3182. }
  3183. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3184. if ($upCol !== null) {
  3185. $data[$upCol] = date('Y-m-d H:i:s');
  3186. }
  3187. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3188. if ($statusNameCol !== null) {
  3189. $curSn = '';
  3190. foreach ($row as $k => $v) {
  3191. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  3192. $curSn = trim((string)$v);
  3193. break;
  3194. }
  3195. }
  3196. if ($curSn !== '已完成') {
  3197. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  3198. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  3199. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  3200. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  3201. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3202. }
  3203. }
  3204. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3205. $pkVal = (int)($row[$pkField] ?? $id);
  3206. try {
  3207. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3208. } catch (\Throwable $e) {
  3209. $msg = $e->getMessage();
  3210. if (stripos($msg, 'Unknown column') !== false) {
  3211. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3212. }
  3213. throw new \RuntimeException('保存失败:' . $msg);
  3214. }
  3215. if ($aff === false) {
  3216. throw new \RuntimeException($label . '保存失败');
  3217. }
  3218. return $gymc;
  3219. }
  3220. /**
  3221. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3222. *
  3223. * @param array<string, mixed> $user
  3224. * @param int[] $detailIds 本次保存涉及的明细 ID
  3225. * @param string $remarkRaw
  3226. */
  3227. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3228. {
  3229. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3230. if ($remarkCol === null) {
  3231. return;
  3232. }
  3233. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3234. if ($detailIds === []) {
  3235. return;
  3236. }
  3237. $anchorId = $detailIds[0];
  3238. $row = null;
  3239. try {
  3240. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3241. if (!$row) {
  3242. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3243. }
  3244. } catch (\Throwable $e) {
  3245. $row = null;
  3246. }
  3247. if (!$row || !is_array($row)) {
  3248. throw new \InvalidArgumentException('记录不存在');
  3249. }
  3250. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3251. $po = null;
  3252. if ($this->mprocIsValidScydgyRowId($sid)) {
  3253. try {
  3254. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3255. } catch (\Throwable $e) {
  3256. $po = null;
  3257. }
  3258. if (is_array($po)) {
  3259. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3260. }
  3261. }
  3262. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3263. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3264. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3265. }
  3266. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3267. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3268. if (!empty($user['is_admin'])) {
  3269. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3270. }
  3271. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3272. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3273. }
  3274. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3275. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3276. }
  3277. throw new \InvalidArgumentException('无权修改备注');
  3278. }
  3279. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3280. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3281. if ($ccydhCol === null || $companyCol === null) {
  3282. return;
  3283. }
  3284. $ccydh = '';
  3285. $company = '';
  3286. foreach ($row as $k => $v) {
  3287. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3288. $ccydh = trim((string)$v);
  3289. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3290. $company = trim((string)$v);
  3291. }
  3292. }
  3293. if ($ccydh === '' || $company === '') {
  3294. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3295. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3296. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3297. if ($upCol !== null) {
  3298. $data[$upCol] = date('Y-m-d H:i:s');
  3299. }
  3300. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3301. return;
  3302. }
  3303. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3304. $data = [$remarkCol => $remarkVal];
  3305. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3306. if ($upCol !== null) {
  3307. $data[$upCol] = date('Y-m-d H:i:s');
  3308. }
  3309. $query = Db::table('purchase_order_detail')
  3310. ->where($ccydhCol, $ccydh)
  3311. ->where($companyCol, $company);
  3312. $userWhere = $this->mprocListWhereForLoginUser($user);
  3313. if ($userWhere !== []) {
  3314. $query->where($userWhere);
  3315. }
  3316. try {
  3317. $query->update($data);
  3318. } catch (\Throwable $e) {
  3319. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3320. }
  3321. }
  3322. /**
  3323. * 保存协助明细金额、交期、工期
  3324. * 单条:POST id、amount、delivery、lead_days
  3325. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3326. */
  3327. public function mprocSave()
  3328. {
  3329. if (!$this->request->isPost()) {
  3330. $this->error('请使用 POST');
  3331. }
  3332. $user = $this->mprocGetUser();
  3333. if (!$user) {
  3334. $this->error('请先登录', url('index/index/login'));
  3335. }
  3336. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3337. $itemsRaw = $this->request->post('items', '', null);
  3338. if ($itemsRaw === '' || $itemsRaw === null) {
  3339. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3340. }
  3341. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3342. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3343. }
  3344. $items = [];
  3345. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3346. $decoded = json_decode($itemsRaw, true);
  3347. if (!is_array($decoded)) {
  3348. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3349. }
  3350. if (is_array($decoded)) {
  3351. $items = $decoded;
  3352. }
  3353. } elseif (is_array($itemsRaw)) {
  3354. $items = $itemsRaw;
  3355. }
  3356. if ($items === []) {
  3357. $id = (int)$this->request->post('id', 0, null);
  3358. if ($id <= 0) {
  3359. $this->error('保存失败,请关闭弹窗后重试');
  3360. }
  3361. $items = [[
  3362. 'id' => $id,
  3363. 'amount' => (string)$this->request->post('amount', '', null),
  3364. 'delivery' => (string)$this->request->post('delivery', '', null),
  3365. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3366. ]];
  3367. }
  3368. $saved = 0;
  3369. $savedIds = [];
  3370. $remarkRaw = $this->request->post('remark', '', null);
  3371. if ($remarkRaw === '' || $remarkRaw === null) {
  3372. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3373. }
  3374. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3375. Db::startTrans();
  3376. try {
  3377. foreach ($items as $it) {
  3378. if (!is_array($it)) {
  3379. continue;
  3380. }
  3381. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3382. if ($id <= 0) {
  3383. continue;
  3384. }
  3385. $delivery = (string)($it['delivery'] ?? '');
  3386. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3387. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3388. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3389. }
  3390. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3391. $amount = trim((string)($it['amount'] ?? ''));
  3392. $leadDays = trim($leadDays);
  3393. $delivery = trim($delivery);
  3394. // 全空工序跳过:多工序时允许只保存已填全的
  3395. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3396. continue;
  3397. }
  3398. $this->mprocSaveDetailQuote(
  3399. $user,
  3400. $id,
  3401. $amount,
  3402. $delivery,
  3403. $leadDays
  3404. );
  3405. $saved++;
  3406. $savedIds[] = $id;
  3407. }
  3408. if ($saved < 1) {
  3409. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3410. }
  3411. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3412. Db::commit();
  3413. } catch (\InvalidArgumentException $e) {
  3414. Db::rollback();
  3415. $this->error($e->getMessage());
  3416. } catch (\Throwable $e) {
  3417. Db::rollback();
  3418. $this->error($e->getMessage());
  3419. }
  3420. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3421. }
  3422. /**
  3423. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  3424. */
  3425. public function mprocChangePwd()
  3426. {
  3427. if (!$this->request->isPost()) {
  3428. $this->error('请使用 POST');
  3429. }
  3430. $user = $this->mprocGetUser();
  3431. if (!$user) {
  3432. $this->error('请先登录', url('index/index/login'));
  3433. }
  3434. $user = $this->mprocSyncSessionCustomerUser($user);
  3435. if (!empty($user['is_admin'])) {
  3436. $this->error('当前账号不支持修改密码');
  3437. }
  3438. $cu = $this->mprocResolveCustomerUserForSession($user);
  3439. if (!$cu) {
  3440. $this->error('账号不存在或已禁用');
  3441. }
  3442. $oldPwd = (string)$this->request->post('old_password', '');
  3443. $newPwd = (string)$this->request->post('new_password', '');
  3444. $renewPwd = (string)$this->request->post('renew_password', '');
  3445. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3446. $this->error('请填写完整');
  3447. }
  3448. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3449. if ($pwdErr !== '') {
  3450. $this->error($pwdErr);
  3451. }
  3452. if ($newPwd !== $renewPwd) {
  3453. $this->error('两次输入的新密码不一致');
  3454. }
  3455. if ($oldPwd === $newPwd) {
  3456. $this->error('新密码不能与旧密码相同');
  3457. }
  3458. $cuId = (int)($cu['id'] ?? 0);
  3459. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3460. $this->error('原密码不正确');
  3461. }
  3462. $data = [
  3463. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3464. 'updatetime' => date('Y-m-d H:i:s'),
  3465. ];
  3466. try {
  3467. Db::table('customer')->where('id', $cuId)->update($data);
  3468. } catch (\Throwable $e) {
  3469. $this->error('修改失败:' . $e->getMessage());
  3470. }
  3471. // 改密后强制重新登录
  3472. $token = Session::get('mproc_token');
  3473. if ($token === null || $token === '') {
  3474. $token = Cookie::get('mproc_token');
  3475. }
  3476. if ($token === null || $token === '') {
  3477. $token = Cookie::get('mproc_remember');
  3478. }
  3479. $this->mprocClearLogin((string)$token);
  3480. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3481. }
  3482. /**
  3483. * 退出登录
  3484. */
  3485. public function logout()
  3486. {
  3487. $token = Session::get('mproc_token');
  3488. if ($token === null || $token === '') {
  3489. $token = Cookie::get('mproc_token');
  3490. }
  3491. if ($token === null || $token === '') {
  3492. $token = Cookie::get('mproc_remember');
  3493. }
  3494. // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
  3495. $this->mprocClearLogin((string)$token);
  3496. $this->redirect(url('index/index/login'));
  3497. }
  3498. /**
  3499. * 短信宝(与后台协助审核一致,便于复用账号)
  3500. *
  3501. * @throws \Exception
  3502. */
  3503. protected function mprocSmsSend($phone, $content)
  3504. {
  3505. $statusStr = [
  3506. '0' => '短信发送成功',
  3507. '-1' => '参数不全',
  3508. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3509. '30' => '密码错误',
  3510. '40' => '账号不存在',
  3511. '41' => '余额不足',
  3512. '42' => '帐户已过期',
  3513. '43' => 'IP地址限制',
  3514. '50' => '内容含有敏感词',
  3515. ];
  3516. $smsapi = 'http://api.smsbao.com/';
  3517. $user = trim((string)Config::get('mproc.smsbao_user'));
  3518. if ($user === '') {
  3519. $user = 'zhuwei123';
  3520. }
  3521. $passPlain = Config::get('mproc.smsbao_pass');
  3522. $pass = ($passPlain !== null && $passPlain !== '')
  3523. ? md5((string)$passPlain)
  3524. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3525. $phone = trim((string)$phone);
  3526. $content = trim((string)$content);
  3527. if ($phone === '' || $content === '') {
  3528. throw new \Exception('短信发送失败:参数不全');
  3529. }
  3530. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3531. $result = @file_get_contents($sendurl);
  3532. if ($result === false) {
  3533. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3534. throw new \Exception('短信发送失败:网络异常');
  3535. }
  3536. $result = trim((string)$result);
  3537. if ($result !== '0') {
  3538. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3539. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3540. throw new \Exception('短信发送失败:' . $msg);
  3541. }
  3542. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3543. }
  3544. /**
  3545. * 质量评分页(仅管理员)
  3546. */
  3547. public function inboundscore()
  3548. {
  3549. $user = $this->mprocGetUser();
  3550. if (!$user) {
  3551. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3552. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3553. if ($safe !== '') {
  3554. Session::set('mproc_intended_url', $safe);
  3555. }
  3556. $this->redirect($this->mprocBuildLoginUrl($safe));
  3557. return;
  3558. }
  3559. if (empty($user['is_admin'])) {
  3560. $this->redirect(url('index/index/index', '', '', true));
  3561. return;
  3562. }
  3563. $this->mprocEnsureInboundScoreTable();
  3564. $q = trim((string)$this->request->get('q', ''));
  3565. $profile = $this->mprocProfileForUser($user);
  3566. $this->view->assign('mprocSearchQ', $q);
  3567. $this->view->assign('mprocProfile', $profile);
  3568. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3569. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3570. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0)));
  3571. return $this->view->fetch();
  3572. }
  3573. /**
  3574. * 质量评分列表 JSON(仅管理员;tab=pending|scored)
  3575. * scored 仅返回当前账号操作过的已评分记录
  3576. */
  3577. public function inboundscorelist()
  3578. {
  3579. $user = $this->mprocRequireAdminUser();
  3580. $this->mprocEnsureInboundScoreTable();
  3581. $q = trim((string)$this->request->request('q', ''));
  3582. $tab = trim((string)$this->request->request('tab', 'pending'));
  3583. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  3584. $tab = 'pending';
  3585. }
  3586. // 兼容旧 tab:合格/不合格并入已评分
  3587. if ($tab === 'pass' || $tab === 'fail') {
  3588. $tab = 'scored';
  3589. }
  3590. $adminId = (int)($user['admin_id'] ?? 0);
  3591. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId);
  3592. $this->success('ok', '', [
  3593. 'tab' => $tab,
  3594. 'q' => $q,
  3595. 'rows' => $rows,
  3596. 'count' => count($rows),
  3597. ]);
  3598. }
  3599. /**
  3600. * 保存质量评分(仅管理员)
  3601. * POST:ccydh 或 scydgy_id、result=合格|不合格、delivery_status=准时|滞后、customer_complaint=0|1、order_interrupt=0|1、remark
  3602. * 同一订单号下多道工序一并评分、一并完结(与历史存证一单一行一致)
  3603. */
  3604. public function inboundscoresave()
  3605. {
  3606. $user = $this->mprocRequireAdminUser();
  3607. if (!$this->request->isPost()) {
  3608. $this->error('请使用 POST');
  3609. }
  3610. $this->mprocEnsureInboundScoreTable();
  3611. $ccydh = trim((string)$this->request->post('ccydh', ''));
  3612. $sid = (int)$this->request->post('scydgy_id', 0);
  3613. $result = trim((string)$this->request->post('result', ''));
  3614. if ($result !== '合格' && $result !== '不合格') {
  3615. $this->error('请选择是否合格');
  3616. }
  3617. $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
  3618. if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
  3619. $this->error('请选择交货情况');
  3620. }
  3621. $customerComplaint = (int)$this->request->post('customer_complaint', -1);
  3622. $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
  3623. if ($customerComplaint !== 0 && $customerComplaint !== 1) {
  3624. $this->error('请选择客户是否投诉');
  3625. }
  3626. if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
  3627. $this->error('请选择订单是否中断');
  3628. }
  3629. $remark = trim((string)$this->request->post('remark', ''));
  3630. if ($result === '不合格' && $remark === '') {
  3631. $this->error('请填写不合格原因');
  3632. }
  3633. if (mb_strlen($remark) > 500) {
  3634. $remark = mb_substr($remark, 0, 500);
  3635. }
  3636. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  3637. $approvedIn = implode(',', array_map(static function ($v) {
  3638. return "'" . str_replace("'", "''", (string)$v) . "'";
  3639. }, $approvedVals));
  3640. try {
  3641. $q = Db::table('purchase_order')
  3642. ->where('scydgy_id', '>', 0)
  3643. ->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%\')')
  3644. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  3645. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  3646. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  3647. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name,pick_time,wflow_status,status');
  3648. if ($ccydh !== '') {
  3649. $q->where('CCYDH', $ccydh);
  3650. } elseif ($sid > 0) {
  3651. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  3652. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  3653. if ($ccydh === '') {
  3654. $this->error('缺少订单号');
  3655. }
  3656. $q->where('CCYDH', $ccydh);
  3657. } else {
  3658. $this->error('缺少订单号');
  3659. }
  3660. $poRows = $q->order('id', 'asc')->select();
  3661. } catch (\Throwable $e) {
  3662. $poRows = [];
  3663. }
  3664. if (!is_array($poRows) || $poRows === []) {
  3665. $this->error('未找到可评分的已审核订单');
  3666. }
  3667. $now = date('Y-m-d H:i:s');
  3668. $adminId = (int)($user['admin_id'] ?? 0);
  3669. // 操作日志记昵称,不用登录账号
  3670. $adminName = '';
  3671. if ($adminId > 0) {
  3672. try {
  3673. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  3674. if (is_array($adminRow)) {
  3675. $adminName = trim((string)($adminRow['nickname'] ?? ''));
  3676. if ($adminName === '') {
  3677. $adminName = trim((string)($adminRow['username'] ?? ''));
  3678. }
  3679. }
  3680. } catch (\Throwable $e) {
  3681. }
  3682. }
  3683. if ($adminName === '') {
  3684. $adminName = trim((string)($user['username'] ?? ''));
  3685. }
  3686. if ($adminName === '') {
  3687. $adminName = '管理员';
  3688. }
  3689. $saved = 0;
  3690. $firstSid = 0;
  3691. $firstPoId = 0;
  3692. try {
  3693. Db::startTrans();
  3694. foreach ($poRows as $po) {
  3695. if (!is_array($po)) {
  3696. continue;
  3697. }
  3698. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3699. if ($rowSid <= 0) {
  3700. continue;
  3701. }
  3702. if ($firstSid <= 0) {
  3703. $firstSid = $rowSid;
  3704. $firstPoId = (int)($po['id'] ?? 0);
  3705. }
  3706. $g = trim((string)($po['CGYMC'] ?? ''));
  3707. $data = [
  3708. 'scydgy_id' => $rowSid,
  3709. 'purchase_order_id' => (int)($po['id'] ?? 0),
  3710. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  3711. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  3712. 'cgymc' => $g,
  3713. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3714. 'result' => $result,
  3715. 'delivery_status' => $deliveryStatus,
  3716. 'customer_complaint' => $customerComplaint,
  3717. 'order_interrupt' => $orderInterrupt,
  3718. 'remark' => $remark,
  3719. 'admin_id' => $adminId,
  3720. 'admin_name' => $adminName,
  3721. 'updatetime' => $now,
  3722. ];
  3723. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  3724. if (is_array($exist) && $exist !== []) {
  3725. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  3726. } else {
  3727. $data['createtime'] = $now;
  3728. Db::table('purchase_order_inbound_score')->insert($data);
  3729. }
  3730. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  3731. 'status' => ProcuremenStatus::PO_COMPLETED,
  3732. ]);
  3733. $saved++;
  3734. }
  3735. if ($saved < 1) {
  3736. throw new \RuntimeException('没有可保存的工序');
  3737. }
  3738. Db::commit();
  3739. } catch (\Throwable $e) {
  3740. try {
  3741. Db::rollback();
  3742. } catch (\Throwable $e2) {
  3743. }
  3744. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  3745. $this->error('保存失败,请稍后重试');
  3746. }
  3747. $logDetail = '质量评分:是否合格=' . $result
  3748. . ';交货情况=' . $deliveryStatus
  3749. . ';客户投诉:' . ($customerComplaint === 1 ? '是' : '否')
  3750. . ';订单中断:' . ($orderInterrupt === 1 ? '是' : '否');
  3751. if ($remark !== '') {
  3752. $logDetail .= ';备注:' . $remark;
  3753. }
  3754. \app\common\library\ProcuremenOperLog::write(
  3755. $firstSid,
  3756. 'inbound_score',
  3757. $logDetail,
  3758. $firstPoId > 0 ? $firstPoId : null,
  3759. [$adminId, $adminName]
  3760. );
  3761. // 按入库合格/不合格重算该供应商当月质量得分
  3762. $companyName = '';
  3763. foreach ($poRows as $po) {
  3764. if (!is_array($po)) {
  3765. continue;
  3766. }
  3767. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  3768. if ($companyName !== '') {
  3769. break;
  3770. }
  3771. }
  3772. $scoreYm = date('Y-m', strtotime($now) ?: time());
  3773. if ($companyName !== '') {
  3774. try {
  3775. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  3776. } catch (\Throwable $e) {
  3777. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  3778. }
  3779. }
  3780. $this->success('操作成功', '', [
  3781. 'ccydh' => $ccydh,
  3782. 'result' => $result,
  3783. 'delivery_status' => $deliveryStatus,
  3784. 'customer_complaint' => $customerComplaint,
  3785. 'order_interrupt' => $orderInterrupt,
  3786. 'remark' => $remark,
  3787. 'count' => $saved,
  3788. 'status' => '已完结',
  3789. ]);
  3790. }
  3791. /**
  3792. * @return array<string, mixed>
  3793. */
  3794. protected function mprocRequireAdminUser(): array
  3795. {
  3796. $user = $this->mprocGetUser();
  3797. if (!$user) {
  3798. $this->error('请先登录', url('index/index/login'));
  3799. }
  3800. if (empty($user['is_admin'])) {
  3801. $this->error('仅系统管理员可操作');
  3802. }
  3803. return $user;
  3804. }
  3805. protected function mprocEnsureInboundScoreTable(): void
  3806. {
  3807. static $ok = false;
  3808. if ($ok) {
  3809. return;
  3810. }
  3811. try {
  3812. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  3813. } catch (\Throwable $e) {
  3814. try {
  3815. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  3816. `id` int unsigned NOT NULL AUTO_INCREMENT,
  3817. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  3818. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  3819. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  3820. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  3821. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  3822. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  3823. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  3824. `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
  3825. `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
  3826. `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
  3827. `admin_id` int unsigned NOT NULL DEFAULT 0,
  3828. `admin_name` varchar(64) NOT NULL DEFAULT '',
  3829. `remark` varchar(500) NOT NULL DEFAULT '',
  3830. `createtime` datetime DEFAULT NULL,
  3831. `updatetime` datetime DEFAULT NULL,
  3832. PRIMARY KEY (`id`),
  3833. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  3834. KEY `idx_ccydh` (`ccydh`),
  3835. KEY `idx_result` (`result`),
  3836. KEY `idx_updatetime` (`updatetime`)
  3837. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
  3838. } catch (\Throwable $e2) {
  3839. Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
  3840. return;
  3841. }
  3842. }
  3843. foreach ([
  3844. 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
  3845. 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `delivery_status`",
  3846. 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `customer_complaint`",
  3847. ] as $col => $ddl) {
  3848. try {
  3849. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
  3850. if (!is_array($cols) || $cols === []) {
  3851. Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
  3852. }
  3853. } catch (\Throwable $e) {
  3854. Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
  3855. }
  3856. }
  3857. $ok = true;
  3858. }
  3859. /**
  3860. * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
  3861. * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
  3862. *
  3863. * @return array<int, array<string, mixed>>
  3864. */
  3865. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0): array
  3866. {
  3867. $this->mprocEnsureInboundScoreTable();
  3868. $keyword = trim($keyword);
  3869. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  3870. $tab = 'pending';
  3871. }
  3872. if ($tab === 'pass' || $tab === 'fail') {
  3873. $tab = 'scored';
  3874. }
  3875. try {
  3876. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  3877. $approvedIn = implode(',', array_map(static function ($v) {
  3878. return "'" . str_replace("'", "''", (string)$v) . "'";
  3879. }, $approvedVals));
  3880. $poRows = Db::table('purchase_order')
  3881. ->where('scydgy_id', '>', 0)
  3882. ->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%\')')
  3883. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  3884. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  3885. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  3886. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,pick_company_name,pick_time,wflow_status,status')
  3887. ->order('pick_time', 'desc')
  3888. ->order('id', 'asc')
  3889. ->limit(800)
  3890. ->select();
  3891. } catch (\Throwable $e) {
  3892. Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
  3893. return [];
  3894. }
  3895. if (!is_array($poRows) || $poRows === []) {
  3896. return [];
  3897. }
  3898. $sids = [];
  3899. foreach ($poRows as $po) {
  3900. if (!is_array($po)) {
  3901. continue;
  3902. }
  3903. $sid = (int)($po['scydgy_id'] ?? 0);
  3904. if ($sid > 0) {
  3905. $sids[$sid] = true;
  3906. }
  3907. }
  3908. $scoreMap = [];
  3909. if ($sids !== []) {
  3910. try {
  3911. $scores = Db::table('purchase_order_inbound_score')
  3912. ->where('scydgy_id', 'in', array_keys($sids))
  3913. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  3914. ->select();
  3915. } catch (\Throwable $e) {
  3916. $scores = [];
  3917. }
  3918. if (is_array($scores)) {
  3919. foreach ($scores as $sc) {
  3920. if (!is_array($sc)) {
  3921. continue;
  3922. }
  3923. $sid = (int)($sc['scydgy_id'] ?? 0);
  3924. if ($sid > 0) {
  3925. $scoreMap[$sid] = $sc;
  3926. }
  3927. }
  3928. }
  3929. }
  3930. /** @var array<string, array<string, mixed>> $groups */
  3931. $groups = [];
  3932. foreach ($poRows as $po) {
  3933. if (!is_array($po)) {
  3934. continue;
  3935. }
  3936. $sid = (int)($po['scydgy_id'] ?? 0);
  3937. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  3938. if ($sid <= 0 || $ccydh === '') {
  3939. continue;
  3940. }
  3941. if (!isset($groups[$ccydh])) {
  3942. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  3943. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  3944. $groups[$ccydh] = [
  3945. 'CCYDH' => $ccydh,
  3946. 'scydgy_id' => $sid,
  3947. 'scydgy_ids' => [],
  3948. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  3949. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  3950. 'CGYMC_list' => [],
  3951. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3952. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  3953. 'pick_time_raw' => $pickRaw,
  3954. 'process_count' => 0,
  3955. 'results' => [],
  3956. 'score_admin_ids' => [],
  3957. 'score_time_raw' => '',
  3958. 'customer_complaint'=> 0,
  3959. 'order_interrupt' => 0,
  3960. 'delivery_status' => '',
  3961. 'remark' => '',
  3962. ];
  3963. }
  3964. $g = &$groups[$ccydh];
  3965. $g['scydgy_ids'][] = $sid;
  3966. $g['process_count']++;
  3967. if ($g['scydgy_id'] <= 0) {
  3968. $g['scydgy_id'] = $sid;
  3969. }
  3970. if ($g['CYJMC'] === '') {
  3971. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  3972. }
  3973. if ($g['CCLBMMC'] === '') {
  3974. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  3975. }
  3976. if ($g['pick_company_name'] === '') {
  3977. $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
  3978. }
  3979. $pt = trim((string)($po['pick_time'] ?? ''));
  3980. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  3981. $g['pick_time_raw'] = $pt;
  3982. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  3983. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  3984. }
  3985. $gymc = trim((string)($po['CGYMC'] ?? ''));
  3986. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  3987. $g['CGYMC_list'][] = $gymc;
  3988. }
  3989. $sc = $scoreMap[$sid] ?? null;
  3990. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  3991. $g['results'][] = $res;
  3992. if (is_array($sc) && $res !== '') {
  3993. $aid = (int)($sc['admin_id'] ?? 0);
  3994. if ($aid > 0) {
  3995. $g['score_admin_ids'][$aid] = true;
  3996. }
  3997. if ((int)($sc['customer_complaint'] ?? 0) === 1) {
  3998. $g['customer_complaint'] = 1;
  3999. }
  4000. if ((int)($sc['order_interrupt'] ?? 0) === 1) {
  4001. $g['order_interrupt'] = 1;
  4002. }
  4003. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4004. if ($ds !== '' && $g['delivery_status'] === '') {
  4005. $g['delivery_status'] = $ds;
  4006. }
  4007. $rm = trim((string)($sc['remark'] ?? ''));
  4008. if ($rm !== '' && $g['remark'] === '') {
  4009. $g['remark'] = $rm;
  4010. }
  4011. $st = trim((string)($sc['updatetime'] ?? ''));
  4012. if ($st === '') {
  4013. $st = trim((string)($sc['createtime'] ?? ''));
  4014. }
  4015. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4016. $g['score_time_raw'] = $st;
  4017. }
  4018. }
  4019. unset($g);
  4020. }
  4021. $out = [];
  4022. foreach ($groups as $ccydh => $g) {
  4023. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  4024. $company = (string)($g['pick_company_name'] ?? '');
  4025. $cyjmc = (string)($g['CYJMC'] ?? '');
  4026. if ($keyword !== '') {
  4027. $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  4028. if (mb_stripos($blob, $keyword) === false) {
  4029. continue;
  4030. }
  4031. }
  4032. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  4033. $uniq = [];
  4034. $allScored = true;
  4035. foreach ($results as $r) {
  4036. $r = trim((string)$r);
  4037. if ($r === '') {
  4038. $allScored = false;
  4039. continue;
  4040. }
  4041. $uniq[$r] = true;
  4042. }
  4043. $orderResult = '';
  4044. if ($allScored && count($uniq) === 1) {
  4045. $keys = array_keys($uniq);
  4046. $orderResult = (string)($keys[0] ?? '');
  4047. } elseif ($allScored && count($uniq) > 1) {
  4048. $orderResult = '';
  4049. }
  4050. if ($tab === 'pending' && $orderResult !== '') {
  4051. continue;
  4052. }
  4053. if ($tab === 'scored') {
  4054. if ($orderResult !== '合格' && $orderResult !== '不合格') {
  4055. continue;
  4056. }
  4057. // 已评分:仅当前账号操作过的
  4058. if ($adminId <= 0) {
  4059. continue;
  4060. }
  4061. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  4062. if (empty($adminIds[$adminId])) {
  4063. continue;
  4064. }
  4065. }
  4066. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  4067. $scoreTime = $scoreTimeRaw !== ''
  4068. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw)
  4069. : '';
  4070. $out[] = [
  4071. 'CCYDH' => $ccydh,
  4072. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  4073. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  4074. 'CYJMC' => $cyjmc,
  4075. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4076. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  4077. 'pick_company_name' => $company,
  4078. 'pick_time' => (string)($g['pick_time'] ?? ''),
  4079. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  4080. 'score_time_raw' => $scoreTimeRaw,
  4081. 'process_count' => (int)($g['process_count'] ?? 0),
  4082. 'result' => $orderResult,
  4083. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  4084. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  4085. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  4086. 'remark' => (string)($g['remark'] ?? ''),
  4087. ];
  4088. }
  4089. usort($out, static function ($a, $b) use ($tab) {
  4090. if ($tab === 'scored') {
  4091. $ta = (string)($a['score_time_raw'] ?? '');
  4092. $tb = (string)($b['score_time_raw'] ?? '');
  4093. if ($ta !== $tb) {
  4094. return strcmp($tb, $ta);
  4095. }
  4096. }
  4097. $ta = (string)($a['pick_time'] ?? '');
  4098. $tb = (string)($b['pick_time'] ?? '');
  4099. if ($ta !== $tb) {
  4100. return strcmp($tb, $ta);
  4101. }
  4102. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  4103. });
  4104. return $out;
  4105. }
  4106. }