Index.php 83 KB

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