Index.php 78 KB

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