Index.php 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294
  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|pass|fail)
  3575. * pass/fail 仅返回当前账号操作过的记录
  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', 'pass', 'fail'], true)) {
  3584. $tab = 'pending';
  3585. }
  3586. $adminId = (int)($user['admin_id'] ?? 0);
  3587. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId);
  3588. $this->success('ok', '', [
  3589. 'tab' => $tab,
  3590. 'q' => $q,
  3591. 'rows' => $rows,
  3592. 'count' => count($rows),
  3593. ]);
  3594. }
  3595. /**
  3596. * 保存外协入库评分(仅管理员,POST:ccydh 或 scydgy_id、result=合格|不合格)
  3597. * 同一订单号下多道工序一并评分、一并完结(与历史存证一单一行一致)
  3598. */
  3599. public function inboundscoresave()
  3600. {
  3601. $user = $this->mprocRequireAdminUser();
  3602. if (!$this->request->isPost()) {
  3603. $this->error('请使用 POST');
  3604. }
  3605. $this->mprocEnsureInboundScoreTable();
  3606. $ccydh = trim((string)$this->request->post('ccydh', ''));
  3607. $sid = (int)$this->request->post('scydgy_id', 0);
  3608. $result = trim((string)$this->request->post('result', ''));
  3609. if ($result !== '合格' && $result !== '不合格') {
  3610. $this->error('请选择合格或不合格');
  3611. }
  3612. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  3613. $approvedIn = implode(',', array_map(static function ($v) {
  3614. return "'" . str_replace("'", "''", (string)$v) . "'";
  3615. }, $approvedVals));
  3616. try {
  3617. $q = Db::table('purchase_order')
  3618. ->where('scydgy_id', '>', 0)
  3619. ->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%\')')
  3620. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  3621. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  3622. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  3623. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name,pick_time,wflow_status,status');
  3624. if ($ccydh !== '') {
  3625. $q->where('CCYDH', $ccydh);
  3626. } elseif ($sid > 0) {
  3627. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  3628. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  3629. if ($ccydh === '') {
  3630. $this->error('缺少订单号');
  3631. }
  3632. $q->where('CCYDH', $ccydh);
  3633. } else {
  3634. $this->error('缺少订单号');
  3635. }
  3636. $poRows = $q->order('id', 'asc')->select();
  3637. } catch (\Throwable $e) {
  3638. $poRows = [];
  3639. }
  3640. if (!is_array($poRows) || $poRows === []) {
  3641. $this->error('未找到可评分的已审核订单');
  3642. }
  3643. $now = date('Y-m-d H:i:s');
  3644. $adminId = (int)($user['admin_id'] ?? 0);
  3645. // 操作日志记昵称,不用登录账号
  3646. $adminName = '';
  3647. if ($adminId > 0) {
  3648. try {
  3649. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  3650. if (is_array($adminRow)) {
  3651. $adminName = trim((string)($adminRow['nickname'] ?? ''));
  3652. if ($adminName === '') {
  3653. $adminName = trim((string)($adminRow['username'] ?? ''));
  3654. }
  3655. }
  3656. } catch (\Throwable $e) {
  3657. }
  3658. }
  3659. if ($adminName === '') {
  3660. $adminName = trim((string)($user['username'] ?? ''));
  3661. }
  3662. if ($adminName === '') {
  3663. $adminName = '管理员';
  3664. }
  3665. $saved = 0;
  3666. $firstSid = 0;
  3667. $firstPoId = 0;
  3668. try {
  3669. Db::startTrans();
  3670. foreach ($poRows as $po) {
  3671. if (!is_array($po)) {
  3672. continue;
  3673. }
  3674. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3675. if ($rowSid <= 0) {
  3676. continue;
  3677. }
  3678. if ($firstSid <= 0) {
  3679. $firstSid = $rowSid;
  3680. $firstPoId = (int)($po['id'] ?? 0);
  3681. }
  3682. $g = trim((string)($po['CGYMC'] ?? ''));
  3683. $data = [
  3684. 'scydgy_id' => $rowSid,
  3685. 'purchase_order_id' => (int)($po['id'] ?? 0),
  3686. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  3687. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  3688. 'cgymc' => $g,
  3689. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3690. 'result' => $result,
  3691. 'admin_id' => $adminId,
  3692. 'admin_name' => $adminName,
  3693. 'updatetime' => $now,
  3694. ];
  3695. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  3696. if (is_array($exist) && $exist !== []) {
  3697. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  3698. } else {
  3699. $data['createtime'] = $now;
  3700. Db::table('purchase_order_inbound_score')->insert($data);
  3701. }
  3702. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  3703. 'status' => ProcuremenStatus::PO_COMPLETED,
  3704. ]);
  3705. $saved++;
  3706. }
  3707. if ($saved < 1) {
  3708. throw new \RuntimeException('没有可保存的工序');
  3709. }
  3710. Db::commit();
  3711. } catch (\Throwable $e) {
  3712. try {
  3713. Db::rollback();
  3714. } catch (\Throwable $e2) {
  3715. }
  3716. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  3717. $this->error('保存失败,请稍后重试');
  3718. }
  3719. \app\common\library\ProcuremenOperLog::write(
  3720. $firstSid,
  3721. 'inbound_score',
  3722. '入库评分:' . $result,
  3723. $firstPoId > 0 ? $firstPoId : null,
  3724. [$adminId, $adminName]
  3725. );
  3726. // 按入库合格/不合格重算该供应商当月质量得分
  3727. $companyName = '';
  3728. foreach ($poRows as $po) {
  3729. if (!is_array($po)) {
  3730. continue;
  3731. }
  3732. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  3733. if ($companyName !== '') {
  3734. break;
  3735. }
  3736. }
  3737. $scoreYm = date('Y-m', strtotime($now) ?: time());
  3738. if ($companyName !== '') {
  3739. try {
  3740. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  3741. } catch (\Throwable $e) {
  3742. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  3743. }
  3744. }
  3745. $this->success('操作成功', '', [
  3746. 'ccydh' => $ccydh,
  3747. 'result' => $result,
  3748. 'count' => $saved,
  3749. 'status' => '已完结',
  3750. ]);
  3751. }
  3752. /**
  3753. * @return array<string, mixed>
  3754. */
  3755. protected function mprocRequireAdminUser(): array
  3756. {
  3757. $user = $this->mprocGetUser();
  3758. if (!$user) {
  3759. $this->error('请先登录', url('index/index/login'));
  3760. }
  3761. if (empty($user['is_admin'])) {
  3762. $this->error('仅系统管理员可操作');
  3763. }
  3764. return $user;
  3765. }
  3766. protected function mprocEnsureInboundScoreTable(): void
  3767. {
  3768. static $ok = false;
  3769. if ($ok) {
  3770. return;
  3771. }
  3772. try {
  3773. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  3774. $ok = true;
  3775. return;
  3776. } catch (\Throwable $e) {
  3777. }
  3778. try {
  3779. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  3780. `id` int unsigned NOT NULL AUTO_INCREMENT,
  3781. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  3782. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  3783. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  3784. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  3785. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  3786. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  3787. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  3788. `admin_id` int unsigned NOT NULL DEFAULT 0,
  3789. `admin_name` varchar(64) NOT NULL DEFAULT '',
  3790. `remark` varchar(500) NOT NULL DEFAULT '',
  3791. `createtime` datetime DEFAULT NULL,
  3792. `updatetime` datetime DEFAULT NULL,
  3793. PRIMARY KEY (`id`),
  3794. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  3795. KEY `idx_ccydh` (`ccydh`),
  3796. KEY `idx_result` (`result`),
  3797. KEY `idx_updatetime` (`updatetime`)
  3798. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='外协入库评分'");
  3799. $ok = true;
  3800. } catch (\Throwable $e) {
  3801. Log::record('mprocEnsureInboundScoreTable: ' . $e->getMessage(), 'error');
  3802. }
  3803. }
  3804. /**
  3805. * 外协入库评分列表:按订单号合并(一单一行,工序顿号合并)
  3806. * tab=pending 待评分;pass/fail 仅当前管理员操作过的合格/不合格
  3807. *
  3808. * @return array<int, array<string, mixed>>
  3809. */
  3810. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0): array
  3811. {
  3812. $this->mprocEnsureInboundScoreTable();
  3813. $keyword = trim($keyword);
  3814. if (!in_array($tab, ['pending', 'pass', 'fail'], true)) {
  3815. $tab = 'pending';
  3816. }
  3817. try {
  3818. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  3819. $approvedIn = implode(',', array_map(static function ($v) {
  3820. return "'" . str_replace("'", "''", (string)$v) . "'";
  3821. }, $approvedVals));
  3822. $poRows = Db::table('purchase_order')
  3823. ->where('scydgy_id', '>', 0)
  3824. ->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%\')')
  3825. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  3826. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  3827. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  3828. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,pick_company_name,pick_time,wflow_status,status')
  3829. ->order('pick_time', 'desc')
  3830. ->order('id', 'asc')
  3831. ->limit(800)
  3832. ->select();
  3833. } catch (\Throwable $e) {
  3834. Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
  3835. return [];
  3836. }
  3837. if (!is_array($poRows) || $poRows === []) {
  3838. return [];
  3839. }
  3840. $sids = [];
  3841. foreach ($poRows as $po) {
  3842. if (!is_array($po)) {
  3843. continue;
  3844. }
  3845. $sid = (int)($po['scydgy_id'] ?? 0);
  3846. if ($sid > 0) {
  3847. $sids[$sid] = true;
  3848. }
  3849. }
  3850. $scoreMap = [];
  3851. if ($sids !== []) {
  3852. try {
  3853. $scores = Db::table('purchase_order_inbound_score')
  3854. ->where('scydgy_id', 'in', array_keys($sids))
  3855. ->field('scydgy_id,result,admin_id,admin_name,updatetime,createtime')
  3856. ->select();
  3857. } catch (\Throwable $e) {
  3858. $scores = [];
  3859. }
  3860. if (is_array($scores)) {
  3861. foreach ($scores as $sc) {
  3862. if (!is_array($sc)) {
  3863. continue;
  3864. }
  3865. $sid = (int)($sc['scydgy_id'] ?? 0);
  3866. if ($sid > 0) {
  3867. $scoreMap[$sid] = $sc;
  3868. }
  3869. }
  3870. }
  3871. }
  3872. /** @var array<string, array<string, mixed>> $groups */
  3873. $groups = [];
  3874. foreach ($poRows as $po) {
  3875. if (!is_array($po)) {
  3876. continue;
  3877. }
  3878. $sid = (int)($po['scydgy_id'] ?? 0);
  3879. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  3880. if ($sid <= 0 || $ccydh === '') {
  3881. continue;
  3882. }
  3883. if (!isset($groups[$ccydh])) {
  3884. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  3885. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  3886. $groups[$ccydh] = [
  3887. 'CCYDH' => $ccydh,
  3888. 'scydgy_id' => $sid,
  3889. 'scydgy_ids' => [],
  3890. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  3891. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  3892. 'CGYMC_list' => [],
  3893. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3894. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  3895. 'pick_time_raw' => $pickRaw,
  3896. 'process_count' => 0,
  3897. 'results' => [],
  3898. 'score_admin_ids' => [],
  3899. 'score_time_raw' => '',
  3900. ];
  3901. }
  3902. $g = &$groups[$ccydh];
  3903. $g['scydgy_ids'][] = $sid;
  3904. $g['process_count']++;
  3905. if ($g['scydgy_id'] <= 0) {
  3906. $g['scydgy_id'] = $sid;
  3907. }
  3908. if ($g['CYJMC'] === '') {
  3909. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  3910. }
  3911. if ($g['CCLBMMC'] === '') {
  3912. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  3913. }
  3914. if ($g['pick_company_name'] === '') {
  3915. $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
  3916. }
  3917. $pt = trim((string)($po['pick_time'] ?? ''));
  3918. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  3919. $g['pick_time_raw'] = $pt;
  3920. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  3921. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  3922. }
  3923. $gymc = trim((string)($po['CGYMC'] ?? ''));
  3924. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  3925. $g['CGYMC_list'][] = $gymc;
  3926. }
  3927. $sc = $scoreMap[$sid] ?? null;
  3928. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  3929. $g['results'][] = $res;
  3930. if (is_array($sc) && $res !== '') {
  3931. $aid = (int)($sc['admin_id'] ?? 0);
  3932. if ($aid > 0) {
  3933. $g['score_admin_ids'][$aid] = true;
  3934. }
  3935. $st = trim((string)($sc['updatetime'] ?? ''));
  3936. if ($st === '') {
  3937. $st = trim((string)($sc['createtime'] ?? ''));
  3938. }
  3939. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  3940. $g['score_time_raw'] = $st;
  3941. }
  3942. }
  3943. unset($g);
  3944. }
  3945. $out = [];
  3946. foreach ($groups as $ccydh => $g) {
  3947. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  3948. $company = (string)($g['pick_company_name'] ?? '');
  3949. $cyjmc = (string)($g['CYJMC'] ?? '');
  3950. if ($keyword !== '') {
  3951. $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  3952. if (mb_stripos($blob, $keyword) === false) {
  3953. continue;
  3954. }
  3955. }
  3956. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  3957. $uniq = [];
  3958. $allScored = true;
  3959. foreach ($results as $r) {
  3960. $r = trim((string)$r);
  3961. if ($r === '') {
  3962. $allScored = false;
  3963. continue;
  3964. }
  3965. $uniq[$r] = true;
  3966. }
  3967. $orderResult = '';
  3968. if ($allScored && count($uniq) === 1) {
  3969. $keys = array_keys($uniq);
  3970. $orderResult = (string)($keys[0] ?? '');
  3971. } elseif ($allScored && count($uniq) > 1) {
  3972. $orderResult = '';
  3973. }
  3974. if ($tab === 'pending' && $orderResult !== '') {
  3975. continue;
  3976. }
  3977. if ($tab === 'pass' && $orderResult !== '合格') {
  3978. continue;
  3979. }
  3980. if ($tab === 'fail' && $orderResult !== '不合格') {
  3981. continue;
  3982. }
  3983. // 合格/不合格:仅当前账号操作过的
  3984. if ($tab === 'pass' || $tab === 'fail') {
  3985. if ($adminId <= 0) {
  3986. continue;
  3987. }
  3988. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  3989. if (empty($adminIds[$adminId])) {
  3990. continue;
  3991. }
  3992. }
  3993. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  3994. $scoreTime = $scoreTimeRaw !== ''
  3995. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw)
  3996. : '';
  3997. $out[] = [
  3998. 'CCYDH' => $ccydh,
  3999. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  4000. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  4001. 'CYJMC' => $cyjmc,
  4002. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4003. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  4004. 'pick_company_name' => $company,
  4005. 'pick_time' => (string)($g['pick_time'] ?? ''),
  4006. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  4007. 'score_time_raw' => $scoreTimeRaw,
  4008. 'process_count' => (int)($g['process_count'] ?? 0),
  4009. 'result' => $orderResult,
  4010. ];
  4011. }
  4012. usort($out, static function ($a, $b) use ($tab) {
  4013. if ($tab === 'pass' || $tab === 'fail') {
  4014. $ta = (string)($a['score_time_raw'] ?? '');
  4015. $tb = (string)($b['score_time_raw'] ?? '');
  4016. if ($ta !== $tb) {
  4017. return strcmp($tb, $ta);
  4018. }
  4019. }
  4020. $ta = (string)($a['pick_time'] ?? '');
  4021. $tb = (string)($b['pick_time'] ?? '');
  4022. if ($ta !== $tb) {
  4023. return strcmp($tb, $ta);
  4024. }
  4025. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  4026. });
  4027. return $out;
  4028. }
  4029. }