Index.php 65 KB

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