Index.php 124 KB

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