Index.php 58 KB

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