Index.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  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 ($id > 0) {
  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. /**
  754. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  755. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  756. *
  757. * @param array $row 引用:明细行
  758. * @param array $poRow purchase_order 一行
  759. */
  760. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  761. {
  762. $pl = array_change_key_case($poRow, CASE_LOWER);
  763. $hdr = [
  764. 'ccydh' => 'CCYDH',
  765. 'cyjmc' => 'CYJMC',
  766. 'cdf' => 'CDF',
  767. 'cgzzxmc' => 'cGzzxMc',
  768. 'cgymc' => 'CGYMC',
  769. 'cdxmc' => 'CDXMC',
  770. 'ngzl' => 'NGZL',
  771. 'cdw' => 'CDW',
  772. 'cgybh' => 'CGYBH',
  773. ];
  774. foreach ($hdr as $lk => $out) {
  775. if (!array_key_exists($lk, $pl)) {
  776. continue;
  777. }
  778. $v = $pl[$lk];
  779. if ($v !== null && $v !== '') {
  780. $row[$out] = $v;
  781. }
  782. }
  783. // 本次数量、最高限价:仅存在于主表;PDO 列名可能为小写 ceilingprice
  784. if (array_key_exists('this_quantity', $pl)) {
  785. $row['This_quantity'] = $pl['this_quantity'];
  786. }
  787. if (array_key_exists('ceilingprice', $pl)) {
  788. $row['ceilingPrice'] = $pl['ceilingprice'];
  789. } elseif (array_key_exists('ceiling_price', $pl)) {
  790. $row['ceilingPrice'] = $pl['ceiling_price'];
  791. }
  792. }
  793. /**
  794. * 查询 purchase_order_detail 列表(订单页)
  795. * 无搜索词时:左侧 Tab 按 status_name 筛选(未提交/已提交/已完成)
  796. * 有搜索词时:不按 Tab 筛选,在本单位可见数据内全局关键字匹配
  797. *
  798. * @param string $tab draft|submitted|done
  799. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  800. * @return array{rows: array, done_no_status: int}
  801. */
  802. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  803. {
  804. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  805. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  806. $userWhere = $this->mprocListWhereForLoginUser($user);
  807. if ($userWhere !== []) {
  808. $query->where($userWhere);
  809. }
  810. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  811. // 有搜索词时不在此按 status_name 分栏筛选,全局匹配;无搜索词时仍按左侧 Tab(未提交/已提交/已完成)筛选
  812. if (trim((string)$q) === '') {
  813. $this->mprocApplyListTabConditions($query, $tab, $statusNameCol);
  814. }
  815. try {
  816. $rows = $query->limit(500)->select();
  817. } catch (\Throwable $e) {
  818. $rows = [];
  819. }
  820. if (!is_array($rows)) {
  821. $rows = [];
  822. }
  823. $poBySid = [];
  824. $sidList = [];
  825. foreach ($rows as $r0) {
  826. if (!is_array($r0)) {
  827. continue;
  828. }
  829. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  830. if ($sid0 > 0) {
  831. $sidList[$sid0] = true;
  832. }
  833. }
  834. if ($sidList !== []) {
  835. try {
  836. $poRows = Db::table('purchase_order')
  837. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  838. ->select();
  839. if (is_array($poRows)) {
  840. foreach ($poRows as $pr) {
  841. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  842. if ($sidk > 0) {
  843. $poBySid[$sidk] = $pr;
  844. }
  845. }
  846. }
  847. } catch (\Throwable $e) {
  848. }
  849. }
  850. foreach ($rows as &$row) {
  851. if (!is_array($row)) {
  852. continue;
  853. }
  854. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  855. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  856. if ($sid > 0 && isset($poBySid[$sid])) {
  857. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  858. }
  859. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  860. if (!isset($row['status_name']) || $row['status_name'] === null) {
  861. $row['status_name'] = '';
  862. } else {
  863. $row['status_name'] = trim((string)$row['status_name']);
  864. }
  865. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row) ? 1 : 0;
  866. $am = $row['amount'] ?? null;
  867. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  868. $row['amount_display'] = '';
  869. } else {
  870. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  871. }
  872. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  873. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  874. $row['delivery_display'] = $m[1];
  875. } elseif ($dv !== '') {
  876. $row['delivery_display'] = $dv;
  877. } else {
  878. $row['delivery_display'] = '';
  879. }
  880. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  881. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  882. $row['mproc_fill_hint'] = '';
  883. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  884. }
  885. unset($row);
  886. return [
  887. 'rows' => $rows ?: [],
  888. 'done_no_status' => (int)($statusNameCol === null),
  889. ];
  890. }
  891. /**
  892. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  893. *
  894. * @param array<string, mixed> $row
  895. */
  896. protected function mprocResolveDisplayThisQuantity(array $row): string
  897. {
  898. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  899. if ($qty !== '') {
  900. return $qty;
  901. }
  902. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  903. if ($gzl === null || $gzl === '') {
  904. return '';
  905. }
  906. return is_scalar($gzl) ? trim((string)$gzl) : '';
  907. }
  908. /**
  909. * 外发明细首页(需登录)
  910. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  911. */
  912. public function index()
  913. {
  914. $user = $this->mprocGetUser();
  915. if (!$user) {
  916. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  917. $safe = $this->mprocSanitizeRedirectUrl($uri);
  918. if ($safe !== '') {
  919. Session::set('mproc_intended_url', $safe);
  920. }
  921. $this->redirect($this->mprocBuildLoginUrl(''));
  922. return;
  923. }
  924. $user = $this->mprocSyncSessionCustomerUser($user);
  925. $tabParam = trim((string)$this->request->get('tab', 'draft'));
  926. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  927. // 旧地址 ?tab=me 表示「我的」
  928. if ($tabParam === 'me') {
  929. $mainTab = 'me';
  930. }
  931. if (!in_array($mainTab, ['orders', 'me'], true)) {
  932. $mainTab = 'orders';
  933. }
  934. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  935. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  936. $tab = 'draft';
  937. }
  938. $q = trim((string)$this->request->get('q', ''));
  939. $mprocFocusEid = 0;
  940. $focusEid = (int)$this->request->get('focus_eid', 0);
  941. if ($focusEid > 0 && $mainTab === 'orders') {
  942. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  943. if ($idCol) {
  944. $qw = $this->mprocListWhereForLoginUser($user);
  945. $dr = null;
  946. try {
  947. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  948. if ($qw !== []) {
  949. $qrow->where($qw);
  950. }
  951. $dr = $qrow->find();
  952. } catch (\Throwable $e) {
  953. $dr = null;
  954. }
  955. if (is_array($dr) && $dr !== []) {
  956. $mprocFocusEid = $focusEid;
  957. $q = '';
  958. $sn = trim((string)($dr['status_name'] ?? $dr['STATUS_NAME'] ?? ''));
  959. $mapTab = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done'];
  960. if ($sn !== '' && isset($mapTab[$sn])) {
  961. $tab = $mapTab[$sn];
  962. }
  963. }
  964. }
  965. }
  966. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  967. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  968. $profile = $this->mprocProfileForUser($user);
  969. $this->view->assign('mprocMainTab', $mainTab);
  970. $this->view->assign('mprocTab', $tab);
  971. $this->view->assign('mprocSearchQ', $q);
  972. $this->view->assign('mprocProfile', $profile);
  973. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  974. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  975. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  976. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  977. if ($mainTab === 'me') {
  978. $this->view->assign('rows', []);
  979. return $this->view->fetch();
  980. }
  981. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  982. $this->view->assign('rows', $bundle['rows']);
  983. return $this->view->fetch();
  984. }
  985. /**
  986. * 外发明细列表 JSON(需登录)
  987. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  988. */
  989. public function mprocList()
  990. {
  991. $user = $this->mprocGetUser();
  992. if (!$user) {
  993. $this->error('请先登录', url('index/index/login'));
  994. }
  995. $user = $this->mprocSyncSessionCustomerUser($user);
  996. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  997. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  998. if ($tabParam === 'me') {
  999. $mainTab = 'me';
  1000. }
  1001. if (!in_array($mainTab, ['orders', 'me'], true)) {
  1002. $mainTab = 'orders';
  1003. }
  1004. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  1005. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  1006. $tab = 'draft';
  1007. }
  1008. $q = trim((string)$this->request->request('q', ''));
  1009. if ($mainTab === 'me') {
  1010. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  1011. $this->success('ok', '', [
  1012. 'main_tab' => 'me',
  1013. 'tab' => $tab,
  1014. 'rows' => [],
  1015. 'profile' => $this->mprocProfileForUser($user),
  1016. 'done_no_status' => 0,
  1017. ]);
  1018. }
  1019. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1020. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  1021. $this->success('ok', '', array_merge([
  1022. 'main_tab' => 'orders',
  1023. 'tab' => $tab,
  1024. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  1025. ], $bundle));
  1026. }
  1027. /**
  1028. * 登录页(手机号验证码 / 账号密码)
  1029. */
  1030. public function login()
  1031. {
  1032. if ($this->mprocGetUser()) {
  1033. $this->redirect(url('index/index/index'));
  1034. }
  1035. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  1036. if ($redirect !== '') {
  1037. Session::set('mproc_intended_url', $redirect);
  1038. }
  1039. $this->view->assign('mprocLoginRedirect', $redirect);
  1040. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  1041. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  1042. return $this->view->fetch();
  1043. }
  1044. /**
  1045. * 图形验证码(手机号登录用)
  1046. */
  1047. public function captcha($id = '')
  1048. {
  1049. $captcha = new Captcha((array)Config::get('captcha'));
  1050. return $captcha->entry($id);
  1051. }
  1052. /**
  1053. * 发送登录验证码(POST:phone、captcha)
  1054. */
  1055. public function sendSms()
  1056. {
  1057. if (!$this->request->isPost()) {
  1058. $this->error('请使用 POST');
  1059. }
  1060. $phone = trim((string)$this->request->post('phone', ''));
  1061. $captcha = trim((string)$this->request->post('captcha', ''));
  1062. if (!preg_match('/^1\d{10}$/', $phone)) {
  1063. $this->error('请输入正确的11位手机号');
  1064. }
  1065. if ($captcha === '') {
  1066. $this->error('请输入图形验证码');
  1067. }
  1068. if (!$this->mprocFindCustomerUserByMobile($phone)) {
  1069. $this->error('该手机号未开通或已禁用,请联系管理员');
  1070. }
  1071. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  1072. if (Cache::get('mproc_sms_wait_' . $phone)) {
  1073. $this->error('发送过于频繁,请稍后再试');
  1074. }
  1075. if (!Validate::is($captcha, 'captcha')) {
  1076. $this->error('图形验证码不正确');
  1077. }
  1078. $code = (string)random_int(100000, 999999);
  1079. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  1080. $ttl = max(60, min(600, $ttl));
  1081. Cache::set('mproc_code_' . $phone, $code, $ttl);
  1082. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  1083. try {
  1084. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  1085. if ($tpl === '') {
  1086. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  1087. }
  1088. $content = str_replace('{code}', $code, $tpl);
  1089. $this->mprocSmsSend($phone, $content);
  1090. } catch (\Exception $e) {
  1091. Cache::rm('mproc_code_' . $phone);
  1092. Cache::rm('mproc_sms_wait_' . $phone);
  1093. $this->error($e->getMessage());
  1094. }
  1095. $this->success('验证码已发送');
  1096. }
  1097. /**
  1098. * 验证码登录(POST:phone、code)
  1099. */
  1100. public function doLogin()
  1101. {
  1102. if (!$this->request->isPost()) {
  1103. $this->error('请使用 POST');
  1104. }
  1105. $phone = trim((string)$this->request->post('phone', ''));
  1106. $code = trim((string)$this->request->post('code', ''));
  1107. if (!preg_match('/^1\d{10}$/', $phone)) {
  1108. $this->error('手机号格式不正确');
  1109. }
  1110. if (!preg_match('/^\d{6}$/', $code)) {
  1111. $this->error('请输入6位验证码');
  1112. }
  1113. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  1114. $mock = Config::get('mproc.mock_sms_code');
  1115. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  1116. Cache::rm('mproc_code_' . $phone);
  1117. } else {
  1118. $cached = Cache::get('mproc_code_' . $phone);
  1119. if ($cached === false || $cached === null || (string)$cached !== $code) {
  1120. $this->error('验证码错误或已过期');
  1121. }
  1122. Cache::rm('mproc_code_' . $phone);
  1123. }
  1124. $cu = $this->mprocFindCustomerUserByMobile($phone);
  1125. if (!$cu) {
  1126. $this->error('该手机号未开通或已禁用,请联系管理员');
  1127. }
  1128. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  1129. }
  1130. /**
  1131. * 账号密码登录(POST:username、password)
  1132. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  1133. */
  1134. public function doLoginPwd()
  1135. {
  1136. if (!$this->request->isPost()) {
  1137. $this->error('请使用 POST');
  1138. }
  1139. $username = trim((string)$this->request->post('username', ''));
  1140. $password = (string)$this->request->post('password', '');
  1141. if ($username === '' || $password === '') {
  1142. $this->error('请输入账号和密码');
  1143. }
  1144. $cu = $this->mprocFindCustomerUserByUsername($username);
  1145. if ($cu) {
  1146. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  1147. $this->error('账号或密码错误');
  1148. }
  1149. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  1150. }
  1151. // 管理员:表 admin
  1152. $row = null;
  1153. try {
  1154. $row = Db::name('admin')
  1155. ->field('id,username,password,salt,status,loginfailure,updatetime')
  1156. ->where('username', $username)
  1157. ->find();
  1158. } catch (\Throwable $e) {
  1159. $row = null;
  1160. }
  1161. if (!$row || !is_array($row)) {
  1162. $this->error('账号或密码错误');
  1163. }
  1164. $id = (int)($row['id'] ?? 0);
  1165. if (($row['status'] ?? '') == 'hidden') {
  1166. $this->error('该账号已禁用');
  1167. }
  1168. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  1169. $this->error('登录失败次数过多,请24小时后再试');
  1170. }
  1171. $salt = (string)($row['salt'] ?? '');
  1172. $hashStored = (string)($row['password'] ?? '');
  1173. $hashInput = md5(md5($password) . $salt);
  1174. if ($hashStored === '' || $hashInput !== $hashStored) {
  1175. if ($id > 0) {
  1176. try {
  1177. Db::name('admin')->where('id', $id)->update([
  1178. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  1179. 'updatetime' => time(),
  1180. ]);
  1181. } catch (\Throwable $e) {
  1182. }
  1183. }
  1184. $this->error('账号或密码错误');
  1185. }
  1186. if ($id > 0) {
  1187. try {
  1188. Db::name('admin')->where('id', $id)->update([
  1189. 'loginfailure' => 0,
  1190. 'updatetime' => time(),
  1191. ]);
  1192. } catch (\Throwable $e) {
  1193. }
  1194. }
  1195. $this->mprocFinishLogin([
  1196. 'phone' => trim((string)($row['mobile'] ?? '')),
  1197. 'company_name' => '',
  1198. 'username' => $username,
  1199. 'customer_user_id' => 0,
  1200. 'login_type' => 'pwd',
  1201. 'is_admin' => 1,
  1202. ]);
  1203. }
  1204. /**
  1205. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  1206. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  1207. */
  1208. protected function mprocCanEditRow(array $user, array $row)
  1209. {
  1210. if (!empty($user['is_admin'])) {
  1211. return false;
  1212. }
  1213. $uCo = trim((string)($user['company_name'] ?? ''));
  1214. if ($uCo === '') {
  1215. $uPhone = trim((string)($user['phone'] ?? ''));
  1216. if ($uPhone !== '') {
  1217. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  1218. }
  1219. }
  1220. $rCo = trim((string)($row['company_name'] ?? ''));
  1221. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  1222. return true;
  1223. }
  1224. $uPhone = trim((string)($user['phone'] ?? ''));
  1225. $rPhone = trim((string)($row['phone'] ?? ''));
  1226. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  1227. }
  1228. /**
  1229. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  1230. *
  1231. * @param array<string, mixed> $detailRow
  1232. */
  1233. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  1234. {
  1235. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  1236. $raw = '';
  1237. if ($sid !== 0) {
  1238. try {
  1239. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1240. } catch (\Throwable $e) {
  1241. $po = null;
  1242. }
  1243. if (is_array($po)) {
  1244. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  1245. }
  1246. }
  1247. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  1248. return null;
  1249. }
  1250. return (float)$raw;
  1251. }
  1252. protected function mprocFormatCeilingPriceDisplay(float $n): string
  1253. {
  1254. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  1255. return $s === '' ? '0' : $s;
  1256. }
  1257. /**
  1258. * 保存单条外发明细的金额、交期(POST:id、amount、delivery)
  1259. */
  1260. public function mprocSave()
  1261. {
  1262. if (!$this->request->isPost()) {
  1263. $this->error('请使用 POST');
  1264. }
  1265. $user = $this->mprocGetUser();
  1266. if (!$user) {
  1267. $this->error('请先登录', url('index/index/login'));
  1268. }
  1269. $id = (int)$this->request->post('id', 0);
  1270. if ($id <= 0) {
  1271. $this->error('参数错误');
  1272. }
  1273. $row = null;
  1274. try {
  1275. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  1276. if (!$row) {
  1277. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  1278. }
  1279. } catch (\Throwable $e) {
  1280. $row = null;
  1281. }
  1282. if (!$row || !is_array($row)) {
  1283. $this->error('记录不存在');
  1284. }
  1285. if (!$this->mprocCanEditRow($user, $row)) {
  1286. if (!empty($user['is_admin'])) {
  1287. $this->error('当前账号仅可查看,不能修改单价与交货日期');
  1288. }
  1289. $this->error('无权修改该记录');
  1290. }
  1291. $amountRaw = trim((string)$this->request->post('amount', ''));
  1292. $deliveryRaw = trim((string)$this->request->post('delivery', ''));
  1293. $data = [];
  1294. if ($amountRaw === '') {
  1295. $data['amount'] = null;
  1296. } else {
  1297. if (!preg_match('/^-?\d+(\.\d{1,5})?$/', $amountRaw)) {
  1298. $this->error('单价格式不正确,最多五位小数');
  1299. }
  1300. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  1301. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  1302. $this->error('单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit));
  1303. }
  1304. $data['amount'] = $amountRaw;
  1305. }
  1306. if ($deliveryRaw === '') {
  1307. $data['delivery'] = null;
  1308. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  1309. // 仅选年月日:存 DATETIME,禁止写成 00:00:00——原记录有非零点时间则沿用,否则用当前服务器时分秒
  1310. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1311. $timePart = date('H:i:s');
  1312. if ($existingDel !== '') {
  1313. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  1314. if ($tsEx !== false) {
  1315. $hms = date('H:i:s', $tsEx);
  1316. if ($hms !== '00:00:00') {
  1317. $timePart = $hms;
  1318. }
  1319. }
  1320. }
  1321. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  1322. } else {
  1323. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  1324. $ts = strtotime($deliveryRaw);
  1325. if ($ts === false) {
  1326. $this->error('交期时间格式不正确');
  1327. }
  1328. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  1329. }
  1330. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  1331. if ($dcCol !== null && array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  1332. $data[$dcCol] = date('Y-m-d H:i:s');
  1333. }
  1334. // 同步 status_name(与列表 Tab 一致):金额或交期任一有有效数据 → 已提交,否则未提交;已是「已完成」不覆盖
  1335. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1336. if ($statusNameCol !== null) {
  1337. $curSn = '';
  1338. foreach ($row as $k => $v) {
  1339. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  1340. $curSn = trim((string)$v);
  1341. break;
  1342. }
  1343. }
  1344. if ($curSn !== '已完成') {
  1345. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  1346. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  1347. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  1348. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  1349. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  1350. }
  1351. }
  1352. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  1353. $pkVal = (int)($row[$pkField] ?? $id);
  1354. try {
  1355. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  1356. } catch (\Throwable $e) {
  1357. $msg = $e->getMessage();
  1358. if (stripos($msg, 'Unknown column') !== false) {
  1359. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery 字段';
  1360. }
  1361. $this->error('保存失败:' . $msg);
  1362. }
  1363. if ($aff === false) {
  1364. $this->error('保存失败');
  1365. }
  1366. $this->success('已保存');
  1367. }
  1368. /**
  1369. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  1370. */
  1371. public function mprocChangePwd()
  1372. {
  1373. if (!$this->request->isPost()) {
  1374. $this->error('请使用 POST');
  1375. }
  1376. $user = $this->mprocGetUser();
  1377. if (!$user) {
  1378. $this->error('请先登录', url('index/index/login'));
  1379. }
  1380. $user = $this->mprocSyncSessionCustomerUser($user);
  1381. if (!empty($user['is_admin'])) {
  1382. $this->error('当前账号不支持修改密码');
  1383. }
  1384. $cu = $this->mprocResolveCustomerUserForSession($user);
  1385. if (!$cu) {
  1386. $this->error('账号不存在或已禁用');
  1387. }
  1388. $oldPwd = (string)$this->request->post('old_password', '');
  1389. $newPwd = (string)$this->request->post('new_password', '');
  1390. $renewPwd = (string)$this->request->post('renew_password', '');
  1391. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  1392. $this->error('请填写完整');
  1393. }
  1394. if (strlen($newPwd) < 4) {
  1395. $this->error('新密码至少4位');
  1396. }
  1397. if ($newPwd !== $renewPwd) {
  1398. $this->error('两次输入的新密码不一致');
  1399. }
  1400. if ($oldPwd === $newPwd) {
  1401. $this->error('新密码不能与旧密码相同');
  1402. }
  1403. $cuId = (int)($cu['id'] ?? 0);
  1404. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  1405. $this->error('原密码不正确');
  1406. }
  1407. $data = [
  1408. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  1409. 'updatetime' => date('Y-m-d H:i:s'),
  1410. ];
  1411. try {
  1412. Db::table('customer')->where('id', $cuId)->update($data);
  1413. } catch (\Throwable $e) {
  1414. $this->error('修改失败:' . $e->getMessage());
  1415. }
  1416. $this->success('密码已修改');
  1417. }
  1418. /**
  1419. * 退出登录
  1420. */
  1421. public function logout()
  1422. {
  1423. $token = Session::get('mproc_token');
  1424. if ($token === null || $token === '') {
  1425. $token = Cookie::get('mproc_token');
  1426. }
  1427. if ($token) {
  1428. $this->mprocClearLogin(preg_replace('/[^a-f0-9]/i', '', (string)$token));
  1429. }
  1430. $this->redirect(url('index/index/login'));
  1431. }
  1432. /**
  1433. * 短信宝(与后台外发审核一致,便于复用账号)
  1434. *
  1435. * @throws \Exception
  1436. */
  1437. protected function mprocSmsSend($phone, $content)
  1438. {
  1439. $statusStr = [
  1440. '0' => '短信发送成功',
  1441. '-1' => '参数不全',
  1442. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  1443. '30' => '密码错误',
  1444. '40' => '账号不存在',
  1445. '41' => '余额不足',
  1446. '42' => '帐户已过期',
  1447. '43' => 'IP地址限制',
  1448. '50' => '内容含有敏感词',
  1449. ];
  1450. $smsapi = 'http://api.smsbao.com/';
  1451. $user = trim((string)Config::get('mproc.smsbao_user'));
  1452. if ($user === '') {
  1453. $user = 'zhuwei123';
  1454. }
  1455. $passPlain = Config::get('mproc.smsbao_pass');
  1456. $pass = ($passPlain !== null && $passPlain !== '')
  1457. ? md5((string)$passPlain)
  1458. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  1459. $phone = trim((string)$phone);
  1460. $content = trim((string)$content);
  1461. if ($phone === '' || $content === '') {
  1462. throw new \Exception('短信发送失败:参数不全');
  1463. }
  1464. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  1465. $result = @file_get_contents($sendurl);
  1466. if ($result === false) {
  1467. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  1468. throw new \Exception('短信发送失败:网络异常');
  1469. }
  1470. $result = trim((string)$result);
  1471. if ($result !== '0') {
  1472. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  1473. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  1474. throw new \Exception('短信发送失败:' . $msg);
  1475. }
  1476. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  1477. }
  1478. }