Index.php 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251
  1. <?php
  2. namespace app\index\controller;
  3. use app\common\controller\Frontend;
  4. use think\Cache;
  5. use think\captcha\Captcha;
  6. use think\Config;
  7. use think\Cookie;
  8. use think\Db;
  9. use think\Log;
  10. use think\Session;
  11. use think\Validate;
  12. /**
  13. * 手机端:外发明细(purchase_order_detail)验证码 / 账号密码登录 + 列表
  14. * 普通用户:customer 表(手机号验证码 或 登录账号+密码);管理员:admin 表账号密码(看全部、仅查看)
  15. */
  16. class Index extends Frontend
  17. {
  18. protected $noNeedLogin = ['*'];
  19. protected $noNeedRight = ['*'];
  20. protected $layout = '';
  21. /** @var int 登录态有效天数 */
  22. protected $mprocTtlSeconds = 0;
  23. /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
  24. protected static $mprocProcuremenColumns = null;
  25. public function _initialize()
  26. {
  27. parent::_initialize();
  28. if (is_file(APP_PATH . 'extra/mproc.php')) {
  29. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  30. }
  31. $days = (int)(Config::get('mproc.session_days') ?: 7);
  32. $days = max(1, min(30, $days));
  33. $this->mprocTtlSeconds = $days * 86400;
  34. }
  35. /**
  36. * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
  37. */
  38. protected function mprocGetUser()
  39. {
  40. $token = $this->mprocReadTokenFromRequest();
  41. if ($token !== '') {
  42. $user = $this->mprocLoadUserByToken($token);
  43. if ($user) {
  44. $token = $this->mprocTouchLoginState($user, $token);
  45. $user['token'] = $token;
  46. return $user;
  47. }
  48. }
  49. $user = $this->mprocUserFromRememberCookie();
  50. if (!$user) {
  51. return null;
  52. }
  53. $token = $this->mprocPackSignedAuthToken($user);
  54. $token = $this->mprocTouchLoginState($user, $token);
  55. $user['token'] = $token;
  56. return $user;
  57. }
  58. protected function mprocReadTokenFromRequest(): string
  59. {
  60. $token = Session::get('mproc_token');
  61. if ($token === null || $token === '') {
  62. $token = Cookie::get('mproc_token');
  63. }
  64. if ($token === null || $token === '') {
  65. $token = $this->request->header('X-Mproc-Token');
  66. }
  67. if ($token === null || $token === '') {
  68. $token = $this->request->request('mproc_token', '');
  69. }
  70. $token = trim((string)$token);
  71. if ($token === '') {
  72. return '';
  73. }
  74. if ($this->mprocIsSignedAuthToken($token)) {
  75. return $token;
  76. }
  77. $token = preg_replace('/[^a-f0-9]/i', '', $token);
  78. return strlen($token) >= 16 ? $token : '';
  79. }
  80. protected function mprocIsSignedAuthToken(string $token): bool
  81. {
  82. return strpos($token, '.') !== false
  83. && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
  84. }
  85. protected function mprocAuthCacheKey(string $token): string
  86. {
  87. return 'mproc_u_' . md5($token);
  88. }
  89. /**
  90. * @return array<string, mixed>|null
  91. */
  92. protected function mprocLoadUserByToken(string $token): ?array
  93. {
  94. if ($this->mprocIsSignedAuthToken($token)) {
  95. $user = $this->mprocUserFromSignedToken($token);
  96. if (!$user) {
  97. return null;
  98. }
  99. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  100. $this->mprocClearLogin($token);
  101. return null;
  102. }
  103. $user['token'] = $token;
  104. return $user;
  105. }
  106. $user = Cache::get('mproc_u_' . $token);
  107. if (!is_array($user)) {
  108. $user = $this->mprocUserFromRememberCookie();
  109. if (!$user) {
  110. return null;
  111. }
  112. }
  113. if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
  114. return null;
  115. }
  116. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  117. $this->mprocClearLogin($token);
  118. return null;
  119. }
  120. $user['token'] = $token;
  121. return $user;
  122. }
  123. /**
  124. * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
  125. *
  126. * @param array<string, mixed> $user
  127. */
  128. protected function mprocTouchLoginState(array $user, string $token): string
  129. {
  130. $user['login_time'] = time();
  131. if ($this->mprocIsSignedAuthToken($token)) {
  132. $token = $this->mprocPackSignedAuthToken($user);
  133. }
  134. Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
  135. if (!$this->mprocIsSignedAuthToken($token)) {
  136. Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
  137. }
  138. Session::set('mproc_token', $token);
  139. $this->mprocSetTokenCookie($token);
  140. $this->mprocSetRememberCookie($user, $token);
  141. return $token;
  142. }
  143. /**
  144. * @return array<string, mixed>
  145. */
  146. protected function mprocCookieOptions(): array
  147. {
  148. $opts = [
  149. 'expire' => $this->mprocTtlSeconds,
  150. 'path' => '/',
  151. 'httponly' => true,
  152. ];
  153. if ($this->request->isSsl()) {
  154. $opts['secure'] = true;
  155. }
  156. if (PHP_VERSION_ID >= 70300) {
  157. $opts['samesite'] = 'Lax';
  158. }
  159. return $opts;
  160. }
  161. protected function mprocSetTokenCookie(string $token): void
  162. {
  163. Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
  164. }
  165. /**
  166. * @param array<string, mixed> $user
  167. */
  168. protected function mprocSetRememberCookie(array $user, ?string $token = null): void
  169. {
  170. $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
  171. Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
  172. }
  173. protected function mprocAuthSignSecret(): string
  174. {
  175. $key = trim((string)Config::get('mproc.auth_sign_key'));
  176. if ($key === '') {
  177. $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
  178. }
  179. return hash('sha256', $key);
  180. }
  181. /**
  182. * @param array<string, mixed> $user
  183. */
  184. protected function mprocPackSignedAuthToken(array $user): string
  185. {
  186. $payload = [
  187. 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
  188. 'phone' => trim((string)($user['phone'] ?? '')),
  189. 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
  190. 'admin' => !empty($user['is_admin']) ? 1 : 0,
  191. 'lt' => time(),
  192. ];
  193. $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
  194. $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
  195. return $b64 . '.' . $sig;
  196. }
  197. /** @deprecated 使用 mprocPackSignedAuthToken */
  198. protected function mprocPackRememberCookie(array $user): string
  199. {
  200. return $this->mprocPackSignedAuthToken($user);
  201. }
  202. /**
  203. * @return array<string, mixed>|null
  204. */
  205. protected function mprocUserFromSignedToken(string $raw): ?array
  206. {
  207. $parts = explode('.', trim($raw), 2);
  208. if (count($parts) !== 2) {
  209. return null;
  210. }
  211. $b64 = $parts[0];
  212. $sig = $parts[1];
  213. if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
  214. return null;
  215. }
  216. $pad = strlen($b64) % 4;
  217. if ($pad > 0) {
  218. $b64 .= str_repeat('=', 4 - $pad);
  219. }
  220. $json = base64_decode(strtr($b64, '-_', '+/'), true);
  221. if ($json === false || $json === '') {
  222. return null;
  223. }
  224. $payload = json_decode($json, true);
  225. if (!is_array($payload)) {
  226. return null;
  227. }
  228. $lt = (int)($payload['lt'] ?? 0);
  229. if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
  230. return null;
  231. }
  232. return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
  233. }
  234. /**
  235. * @return array<string, mixed>|null
  236. */
  237. protected function mprocUserFromRememberCookie(): ?array
  238. {
  239. $raw = Cookie::get('mproc_remember');
  240. if ($raw === null || $raw === '') {
  241. $raw = Cookie::get('mproc_token');
  242. }
  243. if ($raw === null || $raw === '') {
  244. return null;
  245. }
  246. return $this->mprocUserFromSignedToken((string)$raw);
  247. }
  248. /**
  249. * @param array<string, mixed> $payload
  250. * @return array<string, mixed>|null
  251. */
  252. protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
  253. {
  254. if (!empty($payload['admin'])) {
  255. $uname = trim((string)($payload['uname'] ?? ''));
  256. if ($uname === '') {
  257. return null;
  258. }
  259. try {
  260. $row = Db::name('admin')->where('username', $uname)->find();
  261. } catch (\Throwable $e) {
  262. $row = null;
  263. }
  264. if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
  265. return null;
  266. }
  267. return [
  268. 'phone' => trim((string)($row['mobile'] ?? '')),
  269. 'company_name' => '',
  270. 'username' => $uname,
  271. 'customer_user_id' => 0,
  272. 'login_type' => 'remember',
  273. 'is_admin' => 1,
  274. 'login_time' => $loginTime,
  275. ];
  276. }
  277. $cid = (int)($payload['uid'] ?? 0);
  278. if ($cid > 0) {
  279. try {
  280. $cu = Db::table('customer')->where('id', $cid)->find();
  281. } catch (\Throwable $e) {
  282. $cu = null;
  283. }
  284. if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
  285. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  286. $user['login_time'] = $loginTime;
  287. return $user;
  288. }
  289. }
  290. $phone = trim((string)($payload['phone'] ?? ''));
  291. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  292. $cu = $this->mprocFindCustomerUserByMobile($phone);
  293. if ($cu) {
  294. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  295. $user['login_time'] = $loginTime;
  296. return $user;
  297. }
  298. }
  299. return null;
  300. }
  301. protected function mprocClearLogin($token)
  302. {
  303. if ($token !== null && $token !== '') {
  304. Cache::rm($this->mprocAuthCacheKey((string)$token));
  305. if (!$this->mprocIsSignedAuthToken((string)$token)) {
  306. Cache::rm('mproc_u_' . $token);
  307. }
  308. }
  309. Session::delete('mproc_token');
  310. Cookie::delete('mproc_token');
  311. Cookie::delete('mproc_remember');
  312. }
  313. /**
  314. * 登录成功后的回跳地址校验(仅允许本站「外发明细订单页」路径,防止开放重定向)
  315. *
  316. * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
  317. */
  318. protected function mprocSanitizeRedirectUrl($raw)
  319. {
  320. $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
  321. if ($s === '') {
  322. return '';
  323. }
  324. if (preg_match('#^https?://#i', $s)) {
  325. $h = parse_url($s, PHP_URL_HOST);
  326. if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
  327. return '';
  328. }
  329. $path = parse_url($s, PHP_URL_PATH);
  330. $query = parse_url($s, PHP_URL_QUERY);
  331. $s = (is_string($path) && $path !== '' ? $path : '/');
  332. if (is_string($query) && $query !== '') {
  333. $s .= '?' . $query;
  334. }
  335. }
  336. if (strpos($s, '://') !== false) {
  337. return '';
  338. }
  339. if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
  340. return '';
  341. }
  342. if ($s[0] !== '/') {
  343. $s = '/' . ltrim($s, '/');
  344. }
  345. if (strpos($s, '//') === 0) {
  346. return '';
  347. }
  348. if (stripos($s, 'index/index/index') === false) {
  349. return '';
  350. }
  351. if (stripos($s, 'index/index/login') !== false) {
  352. return '';
  353. }
  354. return $s;
  355. }
  356. /**
  357. * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI)
  358. */
  359. protected function mprocReadFocusEidFromRequest(): int
  360. {
  361. $fe = (int)$this->request->param('focus_eid', 0);
  362. if ($fe > 0) {
  363. return $fe;
  364. }
  365. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  366. if ($uri !== '' && stripos($uri, 'focus_eid') !== false) {
  367. $query = parse_url($uri, PHP_URL_QUERY);
  368. if (is_string($query) && $query !== '') {
  369. $q = [];
  370. parse_str($query, $q);
  371. if (is_array($q)) {
  372. $fe = (int)($q['focus_eid'] ?? 0);
  373. if ($fe > 0) {
  374. return $fe;
  375. }
  376. }
  377. }
  378. }
  379. return 0;
  380. }
  381. /**
  382. * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
  383. *
  384. * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
  385. */
  386. protected function mprocBuildLoginUrl($redirectPath = '')
  387. {
  388. $root = rtrim($this->request->root(), '/');
  389. $path = '/index/index/login';
  390. $rp = trim((string)$redirectPath);
  391. if ($rp === '') {
  392. return $root . $path;
  393. }
  394. return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
  395. }
  396. /**
  397. * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
  398. *
  399. * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
  400. */
  401. protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
  402. {
  403. $raw = trim((string)$redirectPathOrUrl);
  404. if ($raw === '') {
  405. return url('index/index/index', '', '', true);
  406. }
  407. $queryStr = '';
  408. if (preg_match('#^https?://#i', $raw)) {
  409. $pq = parse_url($raw);
  410. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  411. } elseif (isset($raw[0]) && $raw[0] === '/') {
  412. $pq = parse_url('http://127.0.0.1' . $raw);
  413. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  414. } else {
  415. $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
  416. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  417. }
  418. $q = [];
  419. if ($queryStr !== '') {
  420. parse_str($queryStr, $q);
  421. if (!is_array($q)) {
  422. $q = [];
  423. }
  424. }
  425. $allowed = [];
  426. if (isset($q['focus_eid'])) {
  427. $fe = (int)$q['focus_eid'];
  428. if ($fe > 0) {
  429. $allowed['focus_eid'] = $fe;
  430. }
  431. }
  432. $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
  433. if ($mt === 'me' || $mt === 'orders') {
  434. $allowed['main_tab'] = $mt;
  435. }
  436. $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
  437. if (in_array($tb, ['draft', 'submitted', 'done', 'me'], true)) {
  438. $allowed['tab'] = $tb;
  439. }
  440. if (isset($q['q']) && trim((string)$q['q']) !== '') {
  441. $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
  442. }
  443. if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
  444. $allowed['main_tab'] = 'orders';
  445. }
  446. $base = rtrim($this->request->root(true), '/');
  447. $path = '/index/index/index';
  448. $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
  449. return $base . $path . $qs;
  450. }
  451. /**
  452. * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
  453. *
  454. * @param string[] $candidatesLower 如 ['status','istatus']
  455. * @return string|null
  456. */
  457. protected function mprocResolveProcuremenColumn(array $candidatesLower)
  458. {
  459. if (self::$mprocProcuremenColumns === null) {
  460. self::$mprocProcuremenColumns = [];
  461. try {
  462. $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
  463. if (is_array($rows)) {
  464. foreach ($rows as $c) {
  465. $name = isset($c['Field']) ? (string)$c['Field'] : '';
  466. if ($name !== '') {
  467. self::$mprocProcuremenColumns[strtolower($name)] = $name;
  468. }
  469. }
  470. }
  471. } catch (\Throwable $e) {
  472. self::$mprocProcuremenColumns = [];
  473. }
  474. }
  475. foreach ($candidatesLower as $low) {
  476. $k = strtolower((string)$low);
  477. if (isset(self::$mprocProcuremenColumns[$k])) {
  478. return self::$mprocProcuremenColumns[$k];
  479. }
  480. }
  481. return null;
  482. }
  483. /**
  484. * 列表:非管理员按 company_name 与登录时解析的单位名一致;管理员不加条件
  485. *
  486. * @return array 可直接 $query->where($arr),空数组表示不加条件
  487. */
  488. protected function mprocListWhereForLoginUser(array $user)
  489. {
  490. if (!empty($user['is_admin'])) {
  491. return [];
  492. }
  493. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  494. if ($cCol === null || $cCol === '') {
  495. return ['id' => 0];
  496. }
  497. $cn = trim((string)($user['company_name'] ?? ''));
  498. if ($cn === '') {
  499. $phone = trim((string)($user['phone'] ?? ''));
  500. if ($phone !== '') {
  501. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  502. }
  503. }
  504. if ($cn === '') {
  505. return ['id' => 0];
  506. }
  507. return [$cCol => $cn];
  508. }
  509. /**
  510. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  511. */
  512. protected function mprocCustomerUserActive(array $row): bool
  513. {
  514. $st = $row['status'] ?? '';
  515. if ($st === '' || $st === null) {
  516. return true;
  517. }
  518. return $st === 1 || $st === '1';
  519. }
  520. /**
  521. * @return array<string, mixed>|null
  522. */
  523. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  524. {
  525. return $this->mprocFindCustomerRowByPhone($phone);
  526. }
  527. /**
  528. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  529. *
  530. * @return array<string, mixed>|null
  531. */
  532. protected function mprocFindCustomerUserByUsername(string $username): ?array
  533. {
  534. $username = trim($username);
  535. if ($username === '') {
  536. return null;
  537. }
  538. try {
  539. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  540. } catch (\Throwable $e) {
  541. $row = null;
  542. }
  543. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  544. $row = $this->mprocFindCustomerRowByPhone($username);
  545. }
  546. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  547. return null;
  548. }
  549. return $row;
  550. }
  551. /**
  552. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  553. */
  554. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  555. {
  556. $stored = (string)($row['password'] ?? '');
  557. if ($stored === '' || $password === '') {
  558. return false;
  559. }
  560. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  561. return password_verify($password, $stored);
  562. }
  563. return hash_equals($stored, md5(md5($password)));
  564. }
  565. /**
  566. * 生成 customer 登录密码密文
  567. */
  568. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  569. {
  570. unset($existingSalt);
  571. return md5(md5($password));
  572. }
  573. /**
  574. * @param array<string, mixed> $cu
  575. * @return array<string, mixed>
  576. */
  577. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  578. {
  579. $phone = trim((string)($cu['phone'] ?? ''));
  580. $account = trim((string)($cu['account'] ?? ''));
  581. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  582. $phone = $account;
  583. }
  584. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  585. $account = $phone;
  586. }
  587. $companyName = trim((string)($cu['company_name'] ?? ''));
  588. if ($companyName === '' && $phone !== '') {
  589. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  590. }
  591. $id = (int)($cu['id'] ?? 0);
  592. return [
  593. 'phone' => $phone,
  594. 'account' => $account,
  595. 'company_name' => $companyName,
  596. 'username' => trim((string)($cu['username'] ?? '')),
  597. 'customer_id' => $id,
  598. 'customer_user_id' => $id,
  599. 'login_type' => $loginType,
  600. 'is_admin' => 0,
  601. ];
  602. }
  603. /**
  604. * 写入手机端登录态并返回跳转 URL
  605. *
  606. * @param array<string, mixed> $userData
  607. */
  608. protected function mprocFinishLogin(array $userData): void
  609. {
  610. $old = Session::get('mproc_token');
  611. if ($old) {
  612. $this->mprocClearLogin((string)$old);
  613. }
  614. $userData['login_time'] = time();
  615. $token = $this->mprocPackSignedAuthToken($userData);
  616. $token = $this->mprocTouchLoginState($userData, $token);
  617. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  618. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  619. Session::delete('mproc_intended_url');
  620. $raw = $postR !== '' ? $postR : $sessR;
  621. $jump = $this->mprocBuildAfterLoginIndexUrl($raw);
  622. $this->success('登录成功', $jump, [
  623. 'mproc_token' => $token,
  624. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  625. ]);
  626. }
  627. /**
  628. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  629. */
  630. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  631. {
  632. $phone = trim($phone);
  633. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  634. return '';
  635. }
  636. $cust = $this->mprocFindCustomerRowByPhone($phone);
  637. if (is_array($cust) && $cust !== []) {
  638. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  639. if ($co !== '') {
  640. return $co;
  641. }
  642. }
  643. try {
  644. $one = Db::table('purchase_order_detail')
  645. ->where('phone', $phone)
  646. ->order('id', 'desc')
  647. ->find();
  648. if (is_array($one)) {
  649. $n = trim((string)($one['company_name'] ?? ''));
  650. if ($n !== '') {
  651. return $n;
  652. }
  653. }
  654. } catch (\Throwable $e) {
  655. }
  656. return '';
  657. }
  658. /**
  659. * 按手机号匹配 customer(phone 或 account 单值相等)
  660. *
  661. * @return array<string, mixed>|null
  662. */
  663. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  664. {
  665. $phone = trim($phone);
  666. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  667. return null;
  668. }
  669. try {
  670. $row = Db::table('customer')
  671. ->where(function ($q) use ($phone) {
  672. $q->where('phone', $phone)->whereOr('account', $phone);
  673. })
  674. ->order('id', 'asc')
  675. ->find();
  676. } catch (\Throwable $e) {
  677. return null;
  678. }
  679. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  680. return null;
  681. }
  682. return $row;
  683. }
  684. /**
  685. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  686. *
  687. * @return array<string, mixed>|null
  688. */
  689. protected function mprocAdminRowByMobile(string $phone): ?array
  690. {
  691. $phone = trim($phone);
  692. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  693. return null;
  694. }
  695. try {
  696. $row = Db::name('admin')
  697. ->where('mobile', $phone)
  698. ->where('status', '<>', 'hidden')
  699. ->order('id', 'asc')
  700. ->find();
  701. } catch (\Throwable $e) {
  702. return null;
  703. }
  704. return is_array($row) && $row !== [] ? $row : null;
  705. }
  706. /**
  707. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  708. *
  709. * @return array<string, mixed>|null
  710. */
  711. protected function mprocFindCustomerRowForUser(array $user): ?array
  712. {
  713. $phone = trim((string)($user['phone'] ?? ''));
  714. if ($phone === '') {
  715. $phone = trim((string)($user['account'] ?? ''));
  716. }
  717. $cn = trim((string)($user['company_name'] ?? ''));
  718. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  719. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  720. if ($byPhone !== null) {
  721. return $byPhone;
  722. }
  723. }
  724. if ($cn !== '') {
  725. try {
  726. $hit = Db::table('customer')
  727. ->where(function ($q) use ($cn) {
  728. $q->where('company_name', $cn)->whereOr('name', $cn);
  729. })
  730. ->order('id', 'desc')
  731. ->find();
  732. } catch (\Throwable $e) {
  733. $hit = null;
  734. }
  735. if (is_array($hit) && $hit !== []) {
  736. return $hit;
  737. }
  738. }
  739. return null;
  740. }
  741. /**
  742. * 从 customer 行取字段(兼容列名大小写)
  743. *
  744. * @param string[] $candidates
  745. */
  746. protected function mprocCustomerPickField(array $row, array $candidates): string
  747. {
  748. foreach ($candidates as $want) {
  749. $lw = strtolower($want);
  750. foreach ($row as $k => $v) {
  751. if (!is_string($k)) {
  752. continue;
  753. }
  754. if (strtolower($k) !== $lw) {
  755. continue;
  756. }
  757. $s = trim((string)$v);
  758. if ($s !== '') {
  759. return $s;
  760. }
  761. }
  762. }
  763. return '';
  764. }
  765. /**
  766. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  767. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  768. *
  769. * @param \think\db\Query $query
  770. */
  771. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  772. {
  773. $kw = trim((string)$search);
  774. if ($kw === '') {
  775. return;
  776. }
  777. $map = self::$mprocProcuremenColumns;
  778. if (!is_array($map) || $map === []) {
  779. return;
  780. }
  781. $like = '%' . addcslashes($kw, '%_\\') . '%';
  782. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  783. $detailCols = [];
  784. foreach ($wantLower as $low) {
  785. if (isset($map[$low])) {
  786. $detailCols[] = $map[$low];
  787. }
  788. }
  789. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  790. $idCol = isset($map['id']) ? $map['id'] : 'id';
  791. $poSidList = [];
  792. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  793. try {
  794. $col = Db::table('purchase_order')
  795. ->where(function ($sub) use ($like, $poWant) {
  796. $firstPo = true;
  797. foreach ($poWant as $pf) {
  798. if ($firstPo) {
  799. $sub->where($pf, 'like', $like);
  800. $firstPo = false;
  801. } else {
  802. $sub->whereOr($pf, 'like', $like);
  803. }
  804. }
  805. })
  806. ->column('scydgy_id');
  807. if (is_array($col)) {
  808. foreach ($col as $v) {
  809. $id = (int)$v;
  810. if ($this->mprocIsValidScydgyRowId($id)) {
  811. $poSidList[$id] = true;
  812. }
  813. }
  814. }
  815. $poSidList = array_keys($poSidList);
  816. } catch (\Throwable $e) {
  817. $poSidList = [];
  818. }
  819. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  820. $first = true;
  821. foreach ($detailCols as $col) {
  822. if ($first) {
  823. $q2->where($col, 'like', $like);
  824. $first = false;
  825. } else {
  826. $q2->whereOr($col, 'like', $like);
  827. }
  828. }
  829. if ($poSidList !== []) {
  830. if ($first) {
  831. $q2->where($scydgyCol, 'in', $poSidList);
  832. $first = false;
  833. } else {
  834. $q2->whereOr($scydgyCol, 'in', $poSidList);
  835. }
  836. }
  837. if ($first) {
  838. $q2->where($idCol, '=', 0);
  839. }
  840. });
  841. }
  842. /**
  843. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  844. * - draft:status_name = 未提交
  845. * - submitted:status_name = 已提交
  846. * - done:status_name = 已完成
  847. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  848. *
  849. * @param mixed $query
  850. * @param string $tab draft|submitted|done
  851. * @param string|null $statusNameCol 真实列名,如 status_name
  852. */
  853. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  854. {
  855. if ($statusNameCol === null) {
  856. return;
  857. }
  858. $map = [
  859. 'draft' => '未提交',
  860. 'submitted' => '已提交',
  861. 'done' => '已完成',
  862. ];
  863. $label = $map[$tab] ?? '未提交';
  864. $query->where($statusNameCol, '=', $label);
  865. }
  866. /**
  867. * 按登录态解析 customer 行
  868. *
  869. * @return array<string, mixed>|null
  870. */
  871. protected function mprocResolveCustomerUserForSession(array $user): ?array
  872. {
  873. if (!empty($user['is_admin'])) {
  874. return null;
  875. }
  876. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  877. if ($cuId > 0) {
  878. try {
  879. $row = Db::table('customer')->where('id', $cuId)->find();
  880. } catch (\Throwable $e) {
  881. $row = null;
  882. }
  883. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  884. return $row;
  885. }
  886. }
  887. $account = trim((string)($user['account'] ?? ''));
  888. if ($account !== '') {
  889. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  890. if ($byAcc !== null) {
  891. return $byAcc;
  892. }
  893. }
  894. $phone = trim((string)($user['phone'] ?? ''));
  895. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  896. return $this->mprocFindCustomerUserByMobile($phone);
  897. }
  898. $uname = trim((string)($user['username'] ?? ''));
  899. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  900. return $this->mprocFindCustomerUserByMobile($uname);
  901. }
  902. return null;
  903. }
  904. /**
  905. * customer 表字段 →「我的」展示结构
  906. *
  907. * @param array<string, mixed> $cu
  908. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  909. */
  910. protected function mprocProfileFromCustomerUserRow(array $cu): array
  911. {
  912. $nm = trim((string)($cu['username'] ?? ''));
  913. $phone = trim((string)($cu['phone'] ?? ''));
  914. if ($phone === '') {
  915. $phone = trim((string)($cu['account'] ?? ''));
  916. }
  917. return [
  918. 'company_name' => trim((string)($cu['company_name'] ?? '')),
  919. 'contact_name' => $nm,
  920. 'phone' => $phone,
  921. 'email' => trim((string)($cu['email'] ?? '')),
  922. ];
  923. }
  924. /**
  925. * 管理员「我的」:admin 表
  926. *
  927. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  928. */
  929. protected function mprocProfileForAdmin(array $user): array
  930. {
  931. $uname = trim((string)($user['username'] ?? ''));
  932. $out = [
  933. 'company_name' => '管理员',
  934. 'contact_name' => $uname !== '' ? $uname : '管理员',
  935. 'phone' => trim((string)($user['phone'] ?? '')),
  936. 'email' => '',
  937. ];
  938. if ($uname === '') {
  939. return $out;
  940. }
  941. try {
  942. $row = Db::name('admin')->where('username', $uname)->find();
  943. } catch (\Throwable $e) {
  944. $row = null;
  945. }
  946. if (!is_array($row) || $row === []) {
  947. return $out;
  948. }
  949. $nick = trim((string)($row['nickname'] ?? ''));
  950. if ($nick !== '') {
  951. $out['contact_name'] = $nick;
  952. }
  953. $mob = trim((string)($row['mobile'] ?? ''));
  954. if ($mob !== '') {
  955. $out['phone'] = $mob;
  956. }
  957. $em = trim((string)($row['email'] ?? ''));
  958. if ($em !== '') {
  959. $out['email'] = $em;
  960. }
  961. return $out;
  962. }
  963. /**
  964. * 旧会话补全 customer_id 等字段
  965. */
  966. protected function mprocSyncSessionCustomerUser(array $user): array
  967. {
  968. if (!empty($user['is_admin'])) {
  969. return $user;
  970. }
  971. $cu = $this->mprocResolveCustomerUserForSession($user);
  972. if (!$cu) {
  973. return $user;
  974. }
  975. $id = (int)($cu['id'] ?? 0);
  976. $user['customer_id'] = $id;
  977. $user['customer_user_id'] = $id;
  978. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  979. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  980. $user['account'] = trim((string)($cu['account'] ?? ''));
  981. $mob = trim((string)($cu['phone'] ?? ''));
  982. if ($mob === '') {
  983. $mob = trim((string)($cu['account'] ?? ''));
  984. }
  985. if ($mob !== '') {
  986. $user['phone'] = $mob;
  987. }
  988. $token = Session::get('mproc_token');
  989. if ($token) {
  990. $user['login_time'] = (int)($user['login_time'] ?? time());
  991. $tok = trim((string)$token);
  992. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  993. if (!$this->mprocIsSignedAuthToken($tok)) {
  994. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  995. }
  996. }
  997. return $user;
  998. }
  999. /**
  1000. * 「我的」:普通用户 customer;管理员 admin
  1001. */
  1002. protected function mprocProfileForUser(array $user)
  1003. {
  1004. if (!empty($user['is_admin'])) {
  1005. return $this->mprocProfileForAdmin($user);
  1006. }
  1007. $cu = $this->mprocResolveCustomerUserForSession($user);
  1008. if (is_array($cu) && $cu !== []) {
  1009. return $this->mprocProfileFromCustomerUserRow($cu);
  1010. }
  1011. $phone = trim((string)($user['phone'] ?? ''));
  1012. if ($phone === '') {
  1013. $phone = trim((string)($user['account'] ?? ''));
  1014. }
  1015. return [
  1016. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1017. 'contact_name' => trim((string)($user['username'] ?? '')),
  1018. 'phone' => $phone,
  1019. 'email' => '',
  1020. ];
  1021. }
  1022. protected function mprocIsValidScydgyRowId($id): bool
  1023. {
  1024. return (int)$id !== 0;
  1025. }
  1026. /**
  1027. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1028. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1029. *
  1030. * @param array $row 引用:明细行
  1031. * @param array $poRow purchase_order 一行
  1032. */
  1033. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1034. {
  1035. $pl = array_change_key_case($poRow, CASE_LOWER);
  1036. $hdr = [
  1037. 'ccydh' => 'CCYDH',
  1038. 'cyjmc' => 'CYJMC',
  1039. 'cdf' => 'CDF',
  1040. 'cgzzxmc' => 'cGzzxMc',
  1041. 'cgymc' => 'CGYMC',
  1042. 'cdxmc' => 'CDXMC',
  1043. 'ngzl' => 'NGZL',
  1044. 'cdw' => 'CDW',
  1045. 'cgybh' => 'CGYBH',
  1046. ];
  1047. foreach ($hdr as $lk => $out) {
  1048. if (!array_key_exists($lk, $pl)) {
  1049. continue;
  1050. }
  1051. $v = $pl[$lk];
  1052. if ($v !== null && $v !== '') {
  1053. $row[$out] = $v;
  1054. }
  1055. }
  1056. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1057. $qtyRaw = '';
  1058. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1059. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1060. $qtyRaw = trim((string)$pl[$qk]);
  1061. break;
  1062. }
  1063. }
  1064. if ($qtyRaw === '') {
  1065. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1066. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1067. $qtyRaw = trim((string)$poRow[$qk]);
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. if ($qtyRaw !== '') {
  1073. $row['This_quantity'] = $qtyRaw;
  1074. }
  1075. $ceilRaw = '';
  1076. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1077. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1078. $ceilRaw = trim((string)$pl[$ck]);
  1079. break;
  1080. }
  1081. }
  1082. if ($ceilRaw === '') {
  1083. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1084. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1085. $ceilRaw = trim((string)$poRow[$ck]);
  1086. break;
  1087. }
  1088. }
  1089. }
  1090. if ($ceilRaw !== '') {
  1091. $row['ceilingPrice'] = $ceilRaw;
  1092. }
  1093. }
  1094. /**
  1095. * 查询 purchase_order_detail 列表(订单页)
  1096. * 无搜索词时:左侧 Tab 按 status_name 筛选(未提交/已提交/已完成)
  1097. * 有搜索词时:不按 Tab 筛选,在本单位可见数据内全局关键字匹配
  1098. *
  1099. * @param string $tab draft|submitted|done
  1100. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  1101. * @return array{rows: array, done_no_status: int}
  1102. */
  1103. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  1104. {
  1105. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  1106. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  1107. $userWhere = $this->mprocListWhereForLoginUser($user);
  1108. if ($userWhere !== []) {
  1109. $query->where($userWhere);
  1110. }
  1111. if (trim((string)$q) === '' && $tab === 'done' && $statusNameCol !== null) {
  1112. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  1113. }
  1114. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  1115. // 有搜索词时不在此按 status_name 分栏筛选,全局匹配;无搜索词时仍按左侧 Tab(未提交/已提交/已完成)筛选
  1116. if (trim((string)$q) === '') {
  1117. $this->mprocApplyListTabConditions($query, $tab, $statusNameCol);
  1118. }
  1119. try {
  1120. $rows = $query->limit(500)->select();
  1121. } catch (\Throwable $e) {
  1122. $rows = [];
  1123. }
  1124. if (!is_array($rows)) {
  1125. $rows = [];
  1126. }
  1127. $poBySid = [];
  1128. $sidList = [];
  1129. foreach ($rows as $r0) {
  1130. if (!is_array($r0)) {
  1131. continue;
  1132. }
  1133. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  1134. if ($this->mprocIsValidScydgyRowId($sid0)) {
  1135. $sidList[$sid0] = true;
  1136. }
  1137. }
  1138. if ($sidList !== []) {
  1139. try {
  1140. $poRows = Db::table('purchase_order')
  1141. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  1142. ->select();
  1143. if (is_array($poRows)) {
  1144. foreach ($poRows as $pr) {
  1145. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1146. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1147. $poBySid[$sidk] = $pr;
  1148. }
  1149. }
  1150. }
  1151. } catch (\Throwable $e) {
  1152. }
  1153. }
  1154. foreach ($rows as &$row) {
  1155. if (!is_array($row)) {
  1156. continue;
  1157. }
  1158. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  1159. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1160. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  1161. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  1162. }
  1163. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  1164. $oldSn = trim((string)($row['status_name'] ?? ''));
  1165. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  1166. $row['status_name'] = $effectiveSn;
  1167. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  1168. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  1169. }
  1170. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  1171. if (!isset($row['status_name']) || $row['status_name'] === null) {
  1172. $row['status_name'] = '';
  1173. } else {
  1174. $row['status_name'] = trim((string)$row['status_name']);
  1175. }
  1176. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row) ? 1 : 0;
  1177. $am = $row['amount'] ?? null;
  1178. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  1179. $row['amount_display'] = '';
  1180. } else {
  1181. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  1182. }
  1183. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1184. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1185. $row['delivery_display'] = $m[1];
  1186. } elseif ($dv !== '') {
  1187. $row['delivery_display'] = $dv;
  1188. } else {
  1189. $row['delivery_display'] = '';
  1190. }
  1191. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1192. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1193. $row['mproc_fill_hint'] = '';
  1194. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1195. }
  1196. unset($row);
  1197. if (trim((string)$q) === '' && $statusNameCol !== null) {
  1198. $tabLabelMap = [
  1199. 'draft' => '未提交',
  1200. 'submitted' => '已提交',
  1201. 'done' => '已完成',
  1202. ];
  1203. $expectLabel = $tabLabelMap[$tab] ?? '未提交';
  1204. $rows = array_values(array_filter($rows, function ($r) use ($expectLabel) {
  1205. return is_array($r) && trim((string)($r['status_name'] ?? '')) === $expectLabel;
  1206. }));
  1207. }
  1208. return [
  1209. 'rows' => $rows ?: [],
  1210. 'done_no_status' => (int)($statusNameCol === null),
  1211. ];
  1212. }
  1213. /**
  1214. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  1215. *
  1216. * @param array<string, mixed> $bundle
  1217. * @param array<string, mixed> $user
  1218. * @return array<string, mixed>
  1219. */
  1220. protected function mprocEnsureFocusRowInList(array $bundle, int $focusEid, array $user, $statusNameCol): array
  1221. {
  1222. if ($focusEid <= 0) {
  1223. return $bundle;
  1224. }
  1225. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  1226. $foundIdx = -1;
  1227. foreach ($rows as $idx => $r) {
  1228. if (!is_array($r)) {
  1229. continue;
  1230. }
  1231. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  1232. $foundIdx = (int)$idx;
  1233. break;
  1234. }
  1235. }
  1236. if ($foundIdx > 0) {
  1237. $hit = $rows[$foundIdx];
  1238. array_splice($rows, $foundIdx, 1);
  1239. array_unshift($rows, $hit);
  1240. $bundle['rows'] = $rows;
  1241. return $bundle;
  1242. }
  1243. if ($foundIdx === 0) {
  1244. return $bundle;
  1245. }
  1246. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1247. if ($idCol === null) {
  1248. return $bundle;
  1249. }
  1250. try {
  1251. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  1252. $qw = $this->mprocListWhereForLoginUser($user);
  1253. if ($qw !== []) {
  1254. $qrow->where($qw);
  1255. }
  1256. $dr = $qrow->find();
  1257. } catch (\Throwable $e) {
  1258. $dr = null;
  1259. }
  1260. if (!is_array($dr) || $dr === []) {
  1261. return $bundle;
  1262. }
  1263. $row = $dr;
  1264. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  1265. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1266. $poRow = null;
  1267. if ($this->mprocIsValidScydgyRowId($sid)) {
  1268. try {
  1269. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1270. } catch (\Throwable $e) {
  1271. $poRow = null;
  1272. }
  1273. if (is_array($poRow)) {
  1274. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  1275. }
  1276. }
  1277. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  1278. $row['status_name'] = $effectiveSn;
  1279. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row) ? 1 : 0;
  1280. $am = $row['amount'] ?? null;
  1281. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  1282. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1283. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1284. $row['delivery_display'] = $m[1];
  1285. } elseif ($dv !== '') {
  1286. $row['delivery_display'] = $dv;
  1287. } else {
  1288. $row['delivery_display'] = '';
  1289. }
  1290. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1291. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1292. $row['mproc_fill_hint'] = '';
  1293. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1294. array_unshift($rows, $row);
  1295. $bundle['rows'] = $rows;
  1296. return $bundle;
  1297. }
  1298. /**
  1299. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  1300. *
  1301. * @param array<string, mixed> $row
  1302. */
  1303. protected function mprocResolveDisplayThisQuantity(array $row): string
  1304. {
  1305. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  1306. if ($qty !== '') {
  1307. return $qty;
  1308. }
  1309. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  1310. if ($gzl === null || $gzl === '') {
  1311. return '';
  1312. }
  1313. return is_scalar($gzl) ? trim((string)$gzl) : '';
  1314. }
  1315. /**
  1316. * 明细是否已填写单价或交货日期
  1317. *
  1318. * @param array<string, mixed> $row
  1319. */
  1320. protected function mprocDetailQuoteSubmitted(array $row): bool
  1321. {
  1322. $am = $row['amount'] ?? null;
  1323. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1324. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  1325. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  1326. return $amountFilled || $deliveryFilled;
  1327. }
  1328. /**
  1329. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  1330. *
  1331. * @param array<string, mixed> $row
  1332. * @param array<string, mixed>|null $po
  1333. */
  1334. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  1335. {
  1336. $sn = trim((string)($row['status_name'] ?? ''));
  1337. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  1338. return $sn;
  1339. }
  1340. if (!is_array($po)) {
  1341. if ($sn !== '') {
  1342. return $sn;
  1343. }
  1344. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  1345. }
  1346. $poStatus = (int)($po['status'] ?? $po['STATUS'] ?? 0);
  1347. if ($poStatus !== 1) {
  1348. if ($sn !== '') {
  1349. return $sn;
  1350. }
  1351. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  1352. }
  1353. $detailStatus = (int)($row['status'] ?? $row['STATUS'] ?? 0);
  1354. if ($detailStatus === 1) {
  1355. return '已完成';
  1356. }
  1357. if ($sn === '已提交') {
  1358. return '未通过';
  1359. }
  1360. return $sn !== '' ? $sn : '未提交';
  1361. }
  1362. /**
  1363. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  1364. */
  1365. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  1366. {
  1367. if ($detailId <= 0 || $statusNameCol === '') {
  1368. return;
  1369. }
  1370. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1371. if ($idCol === null || $idCol === '') {
  1372. return;
  1373. }
  1374. try {
  1375. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  1376. } catch (\Throwable $e) {
  1377. }
  1378. }
  1379. /**
  1380. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  1381. *
  1382. * @param array<string, mixed> $user
  1383. */
  1384. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  1385. {
  1386. $userWhere = $this->mprocListWhereForLoginUser($user);
  1387. try {
  1388. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  1389. if ($userWhere !== []) {
  1390. $query->where($userWhere);
  1391. }
  1392. $candidates = $query->limit(200)->select();
  1393. } catch (\Throwable $e) {
  1394. return;
  1395. }
  1396. if (!is_array($candidates) || $candidates === []) {
  1397. return;
  1398. }
  1399. $sidList = [];
  1400. foreach ($candidates as $cr) {
  1401. if (!is_array($cr)) {
  1402. continue;
  1403. }
  1404. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  1405. if ($this->mprocIsValidScydgyRowId($sid)) {
  1406. $sidList[$sid] = true;
  1407. }
  1408. }
  1409. if ($sidList === []) {
  1410. return;
  1411. }
  1412. $poBySid = [];
  1413. try {
  1414. $poRows = Db::table('purchase_order')
  1415. ->where('scydgy_id', 'in', array_keys($sidList))
  1416. ->where('status', 1)
  1417. ->select();
  1418. if (is_array($poRows)) {
  1419. foreach ($poRows as $pr) {
  1420. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1421. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1422. $poBySid[$sidk] = $pr;
  1423. }
  1424. }
  1425. }
  1426. } catch (\Throwable $e) {
  1427. return;
  1428. }
  1429. if ($poBySid === []) {
  1430. return;
  1431. }
  1432. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1433. if ($idCol === null || $idCol === '') {
  1434. return;
  1435. }
  1436. foreach ($candidates as $cr) {
  1437. if (!is_array($cr)) {
  1438. continue;
  1439. }
  1440. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  1441. if (!isset($poBySid[$sid])) {
  1442. continue;
  1443. }
  1444. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  1445. if ($detailId <= 0) {
  1446. continue;
  1447. }
  1448. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  1449. if ($targetSn === '已提交') {
  1450. continue;
  1451. }
  1452. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  1453. }
  1454. }
  1455. /**
  1456. * 外发明细首页(需登录)
  1457. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  1458. */
  1459. public function index()
  1460. {
  1461. $user = $this->mprocGetUser();
  1462. if (!$user) {
  1463. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  1464. $safe = $this->mprocSanitizeRedirectUrl($uri);
  1465. if ($safe !== '') {
  1466. Session::set('mproc_intended_url', $safe);
  1467. }
  1468. $this->redirect($this->mprocBuildLoginUrl($safe));
  1469. return;
  1470. }
  1471. $user = $this->mprocSyncSessionCustomerUser($user);
  1472. $tabParam = trim((string)$this->request->get('tab', 'draft'));
  1473. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  1474. // 旧地址 ?tab=me 表示「我的」
  1475. if ($tabParam === 'me') {
  1476. $mainTab = 'me';
  1477. }
  1478. if (!in_array($mainTab, ['orders', 'me'], true)) {
  1479. $mainTab = 'orders';
  1480. }
  1481. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  1482. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  1483. $tab = 'draft';
  1484. }
  1485. $q = trim((string)$this->request->get('q', ''));
  1486. $mprocFocusEid = 0;
  1487. $focusEid = $this->mprocReadFocusEidFromRequest();
  1488. if ($focusEid > 0 && $mainTab === 'orders') {
  1489. $mprocFocusEid = $focusEid;
  1490. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1491. if ($idCol) {
  1492. $qw = $this->mprocListWhereForLoginUser($user);
  1493. $dr = null;
  1494. try {
  1495. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  1496. if ($qw !== []) {
  1497. $qrow->where($qw);
  1498. }
  1499. $dr = $qrow->find();
  1500. } catch (\Throwable $e) {
  1501. $dr = null;
  1502. }
  1503. if (is_array($dr) && $dr !== []) {
  1504. $q = '';
  1505. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  1506. $po = null;
  1507. if ($this->mprocIsValidScydgyRowId($sid)) {
  1508. try {
  1509. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1510. } catch (\Throwable $e) {
  1511. $po = null;
  1512. }
  1513. }
  1514. $sn = $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null);
  1515. $mapTab = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done'];
  1516. if ($sn !== '' && isset($mapTab[$sn])) {
  1517. $tab = $mapTab[$sn];
  1518. }
  1519. }
  1520. }
  1521. }
  1522. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  1523. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1524. $profile = $this->mprocProfileForUser($user);
  1525. $this->view->assign('mprocMainTab', $mainTab);
  1526. $this->view->assign('mprocTab', $tab);
  1527. $this->view->assign('mprocSearchQ', $q);
  1528. $this->view->assign('mprocProfile', $profile);
  1529. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  1530. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1531. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  1532. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  1533. if ($mainTab === 'me') {
  1534. $this->view->assign('rows', []);
  1535. return $this->view->fetch();
  1536. }
  1537. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  1538. if ($mprocFocusEid > 0) {
  1539. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol);
  1540. }
  1541. $this->view->assign('rows', $bundle['rows']);
  1542. return $this->view->fetch();
  1543. }
  1544. /**
  1545. * 外发明细列表 JSON(需登录)
  1546. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  1547. */
  1548. public function mprocList()
  1549. {
  1550. $user = $this->mprocGetUser();
  1551. if (!$user) {
  1552. $this->error('请先登录', url('index/index/login'));
  1553. }
  1554. $user = $this->mprocSyncSessionCustomerUser($user);
  1555. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  1556. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  1557. if ($tabParam === 'me') {
  1558. $mainTab = 'me';
  1559. }
  1560. if (!in_array($mainTab, ['orders', 'me'], true)) {
  1561. $mainTab = 'orders';
  1562. }
  1563. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  1564. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  1565. $tab = 'draft';
  1566. }
  1567. $q = trim((string)$this->request->request('q', ''));
  1568. if ($mainTab === 'me') {
  1569. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  1570. $this->success('ok', '', [
  1571. 'main_tab' => 'me',
  1572. 'tab' => $tab,
  1573. 'rows' => [],
  1574. 'profile' => $this->mprocProfileForUser($user),
  1575. 'done_no_status' => 0,
  1576. ]);
  1577. }
  1578. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1579. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  1580. $focusEid = $this->mprocReadFocusEidFromRequest();
  1581. if ($focusEid > 0) {
  1582. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol);
  1583. }
  1584. $this->success('ok', '', array_merge([
  1585. 'main_tab' => 'orders',
  1586. 'tab' => $tab,
  1587. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  1588. 'focus_eid' => $focusEid,
  1589. ], $bundle));
  1590. }
  1591. /**
  1592. * 登录页(手机号验证码 / 账号密码)
  1593. */
  1594. public function login()
  1595. {
  1596. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  1597. if ($this->mprocGetUser()) {
  1598. $this->redirect($this->mprocBuildAfterLoginIndexUrl($redirect));
  1599. }
  1600. if ($redirect !== '') {
  1601. Session::set('mproc_intended_url', $redirect);
  1602. }
  1603. $this->view->assign('mprocLoginRedirect', $redirect);
  1604. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  1605. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  1606. return $this->view->fetch();
  1607. }
  1608. /**
  1609. * 图形验证码(手机号登录用)
  1610. */
  1611. public function captcha($id = '')
  1612. {
  1613. $captcha = new Captcha((array)Config::get('captcha'));
  1614. return $captcha->entry($id);
  1615. }
  1616. /**
  1617. * 发送登录验证码(POST:phone、captcha)
  1618. */
  1619. public function sendSms()
  1620. {
  1621. if (!$this->request->isPost()) {
  1622. $this->error('请使用 POST');
  1623. }
  1624. $phone = trim((string)$this->request->post('phone', ''));
  1625. $captcha = trim((string)$this->request->post('captcha', ''));
  1626. if (!preg_match('/^1\d{10}$/', $phone)) {
  1627. $this->error('请输入正确的11位手机号');
  1628. }
  1629. if ($captcha === '') {
  1630. $this->error('请输入图形验证码');
  1631. }
  1632. if (!$this->mprocFindCustomerUserByMobile($phone)) {
  1633. $this->error('该手机号未开通或已禁用,请联系管理员');
  1634. }
  1635. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  1636. if (Cache::get('mproc_sms_wait_' . $phone)) {
  1637. $this->error('发送过于频繁,请稍后再试');
  1638. }
  1639. if (!Validate::is($captcha, 'captcha')) {
  1640. $this->error('图形验证码不正确');
  1641. }
  1642. $code = (string)random_int(100000, 999999);
  1643. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  1644. $ttl = max(60, min(600, $ttl));
  1645. Cache::set('mproc_code_' . $phone, $code, $ttl);
  1646. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  1647. try {
  1648. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  1649. if ($tpl === '') {
  1650. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  1651. }
  1652. $content = str_replace('{code}', $code, $tpl);
  1653. $this->mprocSmsSend($phone, $content);
  1654. } catch (\Exception $e) {
  1655. Cache::rm('mproc_code_' . $phone);
  1656. Cache::rm('mproc_sms_wait_' . $phone);
  1657. $this->error($e->getMessage());
  1658. }
  1659. $this->success('验证码已发送');
  1660. }
  1661. /**
  1662. * 验证码登录(POST:phone、code)
  1663. */
  1664. public function doLogin()
  1665. {
  1666. if (!$this->request->isPost()) {
  1667. $this->error('请使用 POST');
  1668. }
  1669. $phone = trim((string)$this->request->post('phone', ''));
  1670. $code = trim((string)$this->request->post('code', ''));
  1671. if (!preg_match('/^1\d{10}$/', $phone)) {
  1672. $this->error('手机号格式不正确');
  1673. }
  1674. if (!preg_match('/^\d{6}$/', $code)) {
  1675. $this->error('请输入6位验证码');
  1676. }
  1677. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  1678. $mock = Config::get('mproc.mock_sms_code');
  1679. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  1680. Cache::rm('mproc_code_' . $phone);
  1681. } else {
  1682. $cached = Cache::get('mproc_code_' . $phone);
  1683. if ($cached === false || $cached === null || (string)$cached !== $code) {
  1684. $this->error('验证码错误或已过期');
  1685. }
  1686. Cache::rm('mproc_code_' . $phone);
  1687. }
  1688. $cu = $this->mprocFindCustomerUserByMobile($phone);
  1689. if (!$cu) {
  1690. $this->error('该手机号未开通或已禁用,请联系管理员');
  1691. }
  1692. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  1693. }
  1694. /**
  1695. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  1696. */
  1697. public function mprocRestore()
  1698. {
  1699. if (!$this->request->isPost()) {
  1700. $this->error('请使用 POST');
  1701. }
  1702. $token = $this->mprocReadTokenFromRequest();
  1703. $user = null;
  1704. if ($token !== '') {
  1705. $user = $this->mprocLoadUserByToken($token);
  1706. }
  1707. if (!$user) {
  1708. $user = $this->mprocUserFromRememberCookie();
  1709. if ($user) {
  1710. $token = $this->mprocPackSignedAuthToken($user);
  1711. }
  1712. }
  1713. if (!$user) {
  1714. $this->error('登录已过期,请重新登录', url('index/index/login'));
  1715. }
  1716. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  1717. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  1718. $jump = $this->mprocBuildAfterLoginIndexUrl($redirect);
  1719. $this->success('ok', $jump, [
  1720. 'mproc_token' => $token,
  1721. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  1722. ]);
  1723. }
  1724. /**
  1725. * 账号密码登录(POST:username、password)
  1726. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  1727. */
  1728. public function doLoginPwd()
  1729. {
  1730. if (!$this->request->isPost()) {
  1731. $this->error('请使用 POST');
  1732. }
  1733. $username = trim((string)$this->request->post('username', ''));
  1734. $password = (string)$this->request->post('password', '');
  1735. if ($username === '' || $password === '') {
  1736. $this->error('请输入账号和密码');
  1737. }
  1738. $cu = $this->mprocFindCustomerUserByUsername($username);
  1739. if ($cu) {
  1740. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  1741. $this->error('账号或密码错误');
  1742. }
  1743. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  1744. }
  1745. // 管理员:表 admin
  1746. $row = null;
  1747. try {
  1748. $row = Db::name('admin')
  1749. ->field('id,username,password,salt,status,loginfailure,updatetime')
  1750. ->where('username', $username)
  1751. ->find();
  1752. } catch (\Throwable $e) {
  1753. $row = null;
  1754. }
  1755. if (!$row || !is_array($row)) {
  1756. $this->error('账号或密码错误');
  1757. }
  1758. $id = (int)($row['id'] ?? 0);
  1759. if (($row['status'] ?? '') == 'hidden') {
  1760. $this->error('该账号已禁用');
  1761. }
  1762. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  1763. $this->error('登录失败次数过多,请24小时后再试');
  1764. }
  1765. $salt = (string)($row['salt'] ?? '');
  1766. $hashStored = (string)($row['password'] ?? '');
  1767. $hashInput = md5(md5($password) . $salt);
  1768. if ($hashStored === '' || $hashInput !== $hashStored) {
  1769. if ($id > 0) {
  1770. try {
  1771. Db::name('admin')->where('id', $id)->update([
  1772. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  1773. 'updatetime' => time(),
  1774. ]);
  1775. } catch (\Throwable $e) {
  1776. }
  1777. }
  1778. $this->error('账号或密码错误');
  1779. }
  1780. if ($id > 0) {
  1781. try {
  1782. Db::name('admin')->where('id', $id)->update([
  1783. 'loginfailure' => 0,
  1784. 'updatetime' => time(),
  1785. ]);
  1786. } catch (\Throwable $e) {
  1787. }
  1788. }
  1789. $this->mprocFinishLogin([
  1790. 'phone' => trim((string)($row['mobile'] ?? '')),
  1791. 'company_name' => '',
  1792. 'username' => $username,
  1793. 'customer_user_id' => 0,
  1794. 'login_type' => 'pwd',
  1795. 'is_admin' => 1,
  1796. ]);
  1797. }
  1798. /**
  1799. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  1800. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  1801. */
  1802. protected function mprocCanEditRow(array $user, array $row)
  1803. {
  1804. if (!empty($user['is_admin'])) {
  1805. return false;
  1806. }
  1807. $sn = trim((string)($row['status_name'] ?? ''));
  1808. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  1809. return false;
  1810. }
  1811. $uCo = trim((string)($user['company_name'] ?? ''));
  1812. if ($uCo === '') {
  1813. $uPhone = trim((string)($user['phone'] ?? ''));
  1814. if ($uPhone !== '') {
  1815. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  1816. }
  1817. }
  1818. $rCo = trim((string)($row['company_name'] ?? ''));
  1819. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  1820. return true;
  1821. }
  1822. $uPhone = trim((string)($user['phone'] ?? ''));
  1823. $rPhone = trim((string)($row['phone'] ?? ''));
  1824. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  1825. }
  1826. /**
  1827. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  1828. *
  1829. * @param array<string, mixed> $detailRow
  1830. */
  1831. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  1832. {
  1833. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  1834. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  1835. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  1836. try {
  1837. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1838. } catch (\Throwable $e) {
  1839. $po = null;
  1840. }
  1841. if (is_array($po)) {
  1842. $pl = array_change_key_case($po, CASE_LOWER);
  1843. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  1844. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1845. $raw = trim((string)$pl[$ck]);
  1846. break;
  1847. }
  1848. }
  1849. if ($raw === '') {
  1850. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  1851. }
  1852. }
  1853. }
  1854. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  1855. return null;
  1856. }
  1857. return (float)$raw;
  1858. }
  1859. protected function mprocFormatCeilingPriceDisplay(float $n): string
  1860. {
  1861. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  1862. return $s === '' ? '0' : $s;
  1863. }
  1864. /**
  1865. * 保存单条外发明细的金额、交期(POST:id、amount、delivery)
  1866. */
  1867. public function mprocSave()
  1868. {
  1869. if (!$this->request->isPost()) {
  1870. $this->error('请使用 POST');
  1871. }
  1872. $user = $this->mprocGetUser();
  1873. if (!$user) {
  1874. $this->error('请先登录', url('index/index/login'));
  1875. }
  1876. $id = (int)$this->request->post('id', 0);
  1877. if ($id <= 0) {
  1878. $this->error('参数错误');
  1879. }
  1880. $row = null;
  1881. try {
  1882. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  1883. if (!$row) {
  1884. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  1885. }
  1886. } catch (\Throwable $e) {
  1887. $row = null;
  1888. }
  1889. if (!$row || !is_array($row)) {
  1890. $this->error('记录不存在');
  1891. }
  1892. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1893. $po = null;
  1894. if ($this->mprocIsValidScydgyRowId($sid)) {
  1895. try {
  1896. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1897. } catch (\Throwable $e) {
  1898. $po = null;
  1899. }
  1900. }
  1901. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  1902. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1903. $this->error('订单已结束,不能再修改单价与交货日期');
  1904. }
  1905. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]))) {
  1906. if (!empty($user['is_admin'])) {
  1907. $this->error('当前账号仅可查看,不能修改单价与交货日期');
  1908. }
  1909. $this->error('无权修改该记录');
  1910. }
  1911. $amountRaw = trim((string)$this->request->post('amount', ''));
  1912. $deliveryRaw = trim((string)$this->request->post('delivery', ''));
  1913. $data = [];
  1914. if ($amountRaw === '') {
  1915. $data['amount'] = null;
  1916. } else {
  1917. if (!preg_match('/^-?\d+(\.\d{1,5})?$/', $amountRaw)) {
  1918. $this->error('单价格式不正确,最多五位小数');
  1919. }
  1920. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  1921. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  1922. $this->error('单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit));
  1923. }
  1924. $data['amount'] = $amountRaw;
  1925. }
  1926. if ($deliveryRaw === '') {
  1927. $data['delivery'] = null;
  1928. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  1929. // 仅选年月日:存 DATETIME,禁止写成 00:00:00——原记录有非零点时间则沿用,否则用当前服务器时分秒
  1930. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1931. $timePart = date('H:i:s');
  1932. if ($existingDel !== '') {
  1933. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  1934. if ($tsEx !== false) {
  1935. $hms = date('H:i:s', $tsEx);
  1936. if ($hms !== '00:00:00') {
  1937. $timePart = $hms;
  1938. }
  1939. }
  1940. }
  1941. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  1942. } else {
  1943. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  1944. $ts = strtotime($deliveryRaw);
  1945. if ($ts === false) {
  1946. $this->error('交期时间格式不正确');
  1947. }
  1948. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  1949. }
  1950. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  1951. if ($dcCol !== null && array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  1952. $data[$dcCol] = date('Y-m-d H:i:s');
  1953. }
  1954. // 同步 status_name(与列表 Tab 一致):金额或交期任一有有效数据 → 已提交,否则未提交;已是「已完成」不覆盖
  1955. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1956. if ($statusNameCol !== null) {
  1957. $curSn = '';
  1958. foreach ($row as $k => $v) {
  1959. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  1960. $curSn = trim((string)$v);
  1961. break;
  1962. }
  1963. }
  1964. if ($curSn !== '已完成') {
  1965. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  1966. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  1967. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  1968. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  1969. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  1970. }
  1971. }
  1972. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  1973. $pkVal = (int)($row[$pkField] ?? $id);
  1974. try {
  1975. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  1976. } catch (\Throwable $e) {
  1977. $msg = $e->getMessage();
  1978. if (stripos($msg, 'Unknown column') !== false) {
  1979. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery 字段';
  1980. }
  1981. $this->error('保存失败:' . $msg);
  1982. }
  1983. if ($aff === false) {
  1984. $this->error('保存失败');
  1985. }
  1986. $this->success('已保存');
  1987. }
  1988. /**
  1989. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  1990. */
  1991. public function mprocChangePwd()
  1992. {
  1993. if (!$this->request->isPost()) {
  1994. $this->error('请使用 POST');
  1995. }
  1996. $user = $this->mprocGetUser();
  1997. if (!$user) {
  1998. $this->error('请先登录', url('index/index/login'));
  1999. }
  2000. $user = $this->mprocSyncSessionCustomerUser($user);
  2001. if (!empty($user['is_admin'])) {
  2002. $this->error('当前账号不支持修改密码');
  2003. }
  2004. $cu = $this->mprocResolveCustomerUserForSession($user);
  2005. if (!$cu) {
  2006. $this->error('账号不存在或已禁用');
  2007. }
  2008. $oldPwd = (string)$this->request->post('old_password', '');
  2009. $newPwd = (string)$this->request->post('new_password', '');
  2010. $renewPwd = (string)$this->request->post('renew_password', '');
  2011. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  2012. $this->error('请填写完整');
  2013. }
  2014. if (strlen($newPwd) < 4) {
  2015. $this->error('新密码至少4位');
  2016. }
  2017. if ($newPwd !== $renewPwd) {
  2018. $this->error('两次输入的新密码不一致');
  2019. }
  2020. if ($oldPwd === $newPwd) {
  2021. $this->error('新密码不能与旧密码相同');
  2022. }
  2023. $cuId = (int)($cu['id'] ?? 0);
  2024. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  2025. $this->error('原密码不正确');
  2026. }
  2027. $data = [
  2028. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  2029. 'updatetime' => date('Y-m-d H:i:s'),
  2030. ];
  2031. try {
  2032. Db::table('customer')->where('id', $cuId)->update($data);
  2033. } catch (\Throwable $e) {
  2034. $this->error('修改失败:' . $e->getMessage());
  2035. }
  2036. $this->success('密码已修改');
  2037. }
  2038. /**
  2039. * 退出登录
  2040. */
  2041. public function logout()
  2042. {
  2043. $token = Session::get('mproc_token');
  2044. if ($token === null || $token === '') {
  2045. $token = Cookie::get('mproc_token');
  2046. }
  2047. if ($token) {
  2048. $this->mprocClearLogin(preg_replace('/[^a-f0-9]/i', '', (string)$token));
  2049. }
  2050. $this->redirect(url('index/index/login'));
  2051. }
  2052. /**
  2053. * 短信宝(与后台外发审核一致,便于复用账号)
  2054. *
  2055. * @throws \Exception
  2056. */
  2057. protected function mprocSmsSend($phone, $content)
  2058. {
  2059. $statusStr = [
  2060. '0' => '短信发送成功',
  2061. '-1' => '参数不全',
  2062. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  2063. '30' => '密码错误',
  2064. '40' => '账号不存在',
  2065. '41' => '余额不足',
  2066. '42' => '帐户已过期',
  2067. '43' => 'IP地址限制',
  2068. '50' => '内容含有敏感词',
  2069. ];
  2070. $smsapi = 'http://api.smsbao.com/';
  2071. $user = trim((string)Config::get('mproc.smsbao_user'));
  2072. if ($user === '') {
  2073. $user = 'zhuwei123';
  2074. }
  2075. $passPlain = Config::get('mproc.smsbao_pass');
  2076. $pass = ($passPlain !== null && $passPlain !== '')
  2077. ? md5((string)$passPlain)
  2078. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  2079. $phone = trim((string)$phone);
  2080. $content = trim((string)$content);
  2081. if ($phone === '' || $content === '') {
  2082. throw new \Exception('短信发送失败:参数不全');
  2083. }
  2084. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  2085. $result = @file_get_contents($sendurl);
  2086. if ($result === false) {
  2087. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  2088. throw new \Exception('短信发送失败:网络异常');
  2089. }
  2090. $result = trim((string)$result);
  2091. if ($result !== '0') {
  2092. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  2093. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  2094. throw new \Exception('短信发送失败:' . $msg);
  2095. }
  2096. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  2097. }
  2098. }