Index.php 83 KB

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