Index.php 85 KB

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