Index.php 72 KB

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