Index.php 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836
  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. * 供应商整单备注(purchase_order_detail.remark)
  567. *
  568. * @param array<string, mixed> $row
  569. */
  570. protected function mprocResolveDetailRemark(array $row): string
  571. {
  572. $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  573. if ($col === null) {
  574. return '';
  575. }
  576. foreach ($row as $k => $v) {
  577. if (strcasecmp((string)$k, $col) === 0) {
  578. return trim((string)$v);
  579. }
  580. }
  581. return '';
  582. }
  583. /**
  584. * 列表:非管理员按 company_name 与登录时解析的单位名一致;管理员不加条件
  585. *
  586. * @return array 可直接 $query->where($arr),空数组表示不加条件
  587. */
  588. protected function mprocListWhereForLoginUser(array $user)
  589. {
  590. if (!empty($user['is_admin'])) {
  591. return [];
  592. }
  593. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  594. if ($cCol === null || $cCol === '') {
  595. return ['id' => 0];
  596. }
  597. $cn = trim((string)($user['company_name'] ?? ''));
  598. if ($cn === '') {
  599. $phone = trim((string)($user['phone'] ?? ''));
  600. if ($phone !== '') {
  601. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  602. }
  603. }
  604. if ($cn === '') {
  605. return ['id' => 0];
  606. }
  607. return [$cCol => $cn];
  608. }
  609. /**
  610. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  611. */
  612. protected function mprocCustomerUserActive(array $row): bool
  613. {
  614. $st = $row['status'] ?? '';
  615. if ($st === '' || $st === null) {
  616. return true;
  617. }
  618. return $st === 1 || $st === '1';
  619. }
  620. /**
  621. * @return array<string, mixed>|null
  622. */
  623. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  624. {
  625. return $this->mprocFindCustomerRowByPhone($phone);
  626. }
  627. /**
  628. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  629. *
  630. * @return array<string, mixed>|null
  631. */
  632. protected function mprocFindCustomerUserByUsername(string $username): ?array
  633. {
  634. $username = trim($username);
  635. if ($username === '') {
  636. return null;
  637. }
  638. try {
  639. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  640. } catch (\Throwable $e) {
  641. $row = null;
  642. }
  643. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  644. $row = $this->mprocFindCustomerRowByPhone($username);
  645. }
  646. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  647. return null;
  648. }
  649. return $row;
  650. }
  651. /**
  652. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  653. */
  654. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  655. {
  656. $stored = (string)($row['password'] ?? '');
  657. if ($stored === '' || $password === '') {
  658. return false;
  659. }
  660. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  661. return password_verify($password, $stored);
  662. }
  663. return hash_equals($stored, md5(md5($password)));
  664. }
  665. /**
  666. * 生成 customer 登录密码密文
  667. */
  668. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  669. {
  670. unset($existingSalt);
  671. return md5(md5($password));
  672. }
  673. /**
  674. * @param array<string, mixed> $cu
  675. * @return array<string, mixed>
  676. */
  677. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  678. {
  679. $phone = trim((string)($cu['phone'] ?? ''));
  680. $account = trim((string)($cu['account'] ?? ''));
  681. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  682. $phone = $account;
  683. }
  684. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  685. $account = $phone;
  686. }
  687. $companyName = trim((string)($cu['company_name'] ?? ''));
  688. if ($companyName === '' && $phone !== '') {
  689. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  690. }
  691. $id = (int)($cu['id'] ?? 0);
  692. return [
  693. 'phone' => $phone,
  694. 'account' => $account,
  695. 'company_name' => $companyName,
  696. 'username' => trim((string)($cu['username'] ?? '')),
  697. 'customer_id' => $id,
  698. 'customer_user_id' => $id,
  699. 'login_type' => $loginType,
  700. 'is_admin' => 0,
  701. ];
  702. }
  703. /**
  704. * 写入手机端登录态并返回跳转 URL
  705. *
  706. * @param array<string, mixed> $userData
  707. */
  708. protected function mprocFinishLogin(array $userData): void
  709. {
  710. $old = Session::get('mproc_token');
  711. if ($old) {
  712. $this->mprocClearLogin((string)$old);
  713. }
  714. $userData['login_time'] = time();
  715. $token = $this->mprocPackSignedAuthToken($userData);
  716. $token = $this->mprocTouchLoginState($userData, $token);
  717. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  718. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  719. Session::delete('mproc_intended_url');
  720. $raw = $postR !== '' ? $postR : $sessR;
  721. $jump = $this->mprocBuildAfterLoginIndexUrl($raw);
  722. $this->success('登录成功', $jump, [
  723. 'mproc_token' => $token,
  724. 'keep_hours' => $this->mprocKeepHours(),
  725. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  726. ]);
  727. }
  728. /**
  729. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  730. */
  731. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  732. {
  733. $phone = trim($phone);
  734. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  735. return '';
  736. }
  737. $cust = $this->mprocFindCustomerRowByPhone($phone);
  738. if (is_array($cust) && $cust !== []) {
  739. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  740. if ($co !== '') {
  741. return $co;
  742. }
  743. }
  744. try {
  745. $one = Db::table('purchase_order_detail')
  746. ->where('phone', $phone)
  747. ->order('id', 'desc')
  748. ->find();
  749. if (is_array($one)) {
  750. $n = trim((string)($one['company_name'] ?? ''));
  751. if ($n !== '') {
  752. return $n;
  753. }
  754. }
  755. } catch (\Throwable $e) {
  756. }
  757. return '';
  758. }
  759. /**
  760. * 按手机号匹配 customer(phone 或 account 单值相等)
  761. *
  762. * @return array<string, mixed>|null
  763. */
  764. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  765. {
  766. $phone = trim($phone);
  767. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  768. return null;
  769. }
  770. try {
  771. $row = Db::table('customer')
  772. ->where(function ($q) use ($phone) {
  773. $q->where('phone', $phone)->whereOr('account', $phone);
  774. })
  775. ->order('id', 'asc')
  776. ->find();
  777. } catch (\Throwable $e) {
  778. return null;
  779. }
  780. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  781. return null;
  782. }
  783. return $row;
  784. }
  785. /**
  786. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  787. *
  788. * @return array<string, mixed>|null
  789. */
  790. protected function mprocAdminRowByMobile(string $phone): ?array
  791. {
  792. $phone = trim($phone);
  793. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  794. return null;
  795. }
  796. try {
  797. $row = Db::name('admin')
  798. ->where('mobile', $phone)
  799. ->where('status', '<>', 'hidden')
  800. ->order('id', 'asc')
  801. ->find();
  802. } catch (\Throwable $e) {
  803. return null;
  804. }
  805. return is_array($row) && $row !== [] ? $row : null;
  806. }
  807. /**
  808. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  809. *
  810. * @return array<string, mixed>|null
  811. */
  812. protected function mprocFindCustomerRowForUser(array $user): ?array
  813. {
  814. $phone = trim((string)($user['phone'] ?? ''));
  815. if ($phone === '') {
  816. $phone = trim((string)($user['account'] ?? ''));
  817. }
  818. $cn = trim((string)($user['company_name'] ?? ''));
  819. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  820. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  821. if ($byPhone !== null) {
  822. return $byPhone;
  823. }
  824. }
  825. if ($cn !== '') {
  826. try {
  827. $hit = Db::table('customer')
  828. ->where(function ($q) use ($cn) {
  829. $q->where('company_name', $cn)->whereOr('name', $cn);
  830. })
  831. ->order('id', 'desc')
  832. ->find();
  833. } catch (\Throwable $e) {
  834. $hit = null;
  835. }
  836. if (is_array($hit) && $hit !== []) {
  837. return $hit;
  838. }
  839. }
  840. return null;
  841. }
  842. /**
  843. * 从 customer 行取字段(兼容列名大小写)
  844. *
  845. * @param string[] $candidates
  846. */
  847. protected function mprocCustomerPickField(array $row, array $candidates): string
  848. {
  849. foreach ($candidates as $want) {
  850. $lw = strtolower($want);
  851. foreach ($row as $k => $v) {
  852. if (!is_string($k)) {
  853. continue;
  854. }
  855. if (strtolower($k) !== $lw) {
  856. continue;
  857. }
  858. $s = trim((string)$v);
  859. if ($s !== '') {
  860. return $s;
  861. }
  862. }
  863. }
  864. return '';
  865. }
  866. /**
  867. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  868. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  869. *
  870. * @param \think\db\Query $query
  871. */
  872. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  873. {
  874. $kw = trim((string)$search);
  875. if ($kw === '') {
  876. return;
  877. }
  878. $map = self::$mprocProcuremenColumns;
  879. if (!is_array($map) || $map === []) {
  880. return;
  881. }
  882. $like = '%' . addcslashes($kw, '%_\\') . '%';
  883. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  884. $detailCols = [];
  885. foreach ($wantLower as $low) {
  886. if (isset($map[$low])) {
  887. $detailCols[] = $map[$low];
  888. }
  889. }
  890. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  891. $idCol = isset($map['id']) ? $map['id'] : 'id';
  892. $poSidList = [];
  893. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  894. try {
  895. $col = Db::table('purchase_order')
  896. ->where(function ($sub) use ($like, $poWant) {
  897. $firstPo = true;
  898. foreach ($poWant as $pf) {
  899. if ($firstPo) {
  900. $sub->where($pf, 'like', $like);
  901. $firstPo = false;
  902. } else {
  903. $sub->whereOr($pf, 'like', $like);
  904. }
  905. }
  906. })
  907. ->column('scydgy_id');
  908. if (is_array($col)) {
  909. foreach ($col as $v) {
  910. $id = (int)$v;
  911. if ($this->mprocIsValidScydgyRowId($id)) {
  912. $poSidList[$id] = true;
  913. }
  914. }
  915. }
  916. $poSidList = array_keys($poSidList);
  917. } catch (\Throwable $e) {
  918. $poSidList = [];
  919. }
  920. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  921. $first = true;
  922. foreach ($detailCols as $col) {
  923. if ($first) {
  924. $q2->where($col, 'like', $like);
  925. $first = false;
  926. } else {
  927. $q2->whereOr($col, 'like', $like);
  928. }
  929. }
  930. if ($poSidList !== []) {
  931. if ($first) {
  932. $q2->where($scydgyCol, 'in', $poSidList);
  933. $first = false;
  934. } else {
  935. $q2->whereOr($scydgyCol, 'in', $poSidList);
  936. }
  937. }
  938. if ($first) {
  939. $q2->where($idCol, '=', 0);
  940. }
  941. });
  942. }
  943. /**
  944. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  945. * - draft:status_name = 未提交
  946. * - submitted:status_name = 已提交
  947. * - done:status_name = 已完成
  948. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  949. *
  950. * @param mixed $query
  951. * @param string $tab draft|submitted|done
  952. * @param string|null $statusNameCol 真实列名,如 status_name
  953. */
  954. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  955. {
  956. if ($statusNameCol === null) {
  957. return;
  958. }
  959. $map = [
  960. 'draft' => '未提交',
  961. 'submitted' => '已提交',
  962. 'done' => '已完成',
  963. ];
  964. $label = $map[$tab] ?? '未提交';
  965. $query->where($statusNameCol, '=', $label);
  966. }
  967. /**
  968. * 按登录态解析 customer 行
  969. *
  970. * @return array<string, mixed>|null
  971. */
  972. protected function mprocResolveCustomerUserForSession(array $user): ?array
  973. {
  974. if (!empty($user['is_admin'])) {
  975. return null;
  976. }
  977. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  978. if ($cuId > 0) {
  979. try {
  980. $row = Db::table('customer')->where('id', $cuId)->find();
  981. } catch (\Throwable $e) {
  982. $row = null;
  983. }
  984. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  985. return $row;
  986. }
  987. }
  988. $account = trim((string)($user['account'] ?? ''));
  989. if ($account !== '') {
  990. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  991. if ($byAcc !== null) {
  992. return $byAcc;
  993. }
  994. }
  995. $phone = trim((string)($user['phone'] ?? ''));
  996. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  997. return $this->mprocFindCustomerUserByMobile($phone);
  998. }
  999. $uname = trim((string)($user['username'] ?? ''));
  1000. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1001. return $this->mprocFindCustomerUserByMobile($uname);
  1002. }
  1003. return null;
  1004. }
  1005. /**
  1006. * customer 表字段 →「我的」展示结构
  1007. *
  1008. * @param array<string, mixed> $cu
  1009. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  1010. */
  1011. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1012. {
  1013. $nm = trim((string)($cu['username'] ?? ''));
  1014. $phone = trim((string)($cu['phone'] ?? ''));
  1015. if ($phone === '') {
  1016. $phone = trim((string)($cu['account'] ?? ''));
  1017. }
  1018. return [
  1019. 'company_name' => trim((string)($cu['company_name'] ?? '')),
  1020. 'contact_name' => $nm,
  1021. 'phone' => $phone,
  1022. 'email' => trim((string)($cu['email'] ?? '')),
  1023. ];
  1024. }
  1025. /**
  1026. * 管理员「我的」:admin 表
  1027. *
  1028. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  1029. */
  1030. protected function mprocProfileForAdmin(array $user): array
  1031. {
  1032. $uname = trim((string)($user['username'] ?? ''));
  1033. $out = [
  1034. 'company_name' => '管理员',
  1035. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1036. 'phone' => trim((string)($user['phone'] ?? '')),
  1037. 'email' => '',
  1038. ];
  1039. if ($uname === '') {
  1040. return $out;
  1041. }
  1042. try {
  1043. $row = Db::name('admin')->where('username', $uname)->find();
  1044. } catch (\Throwable $e) {
  1045. $row = null;
  1046. }
  1047. if (!is_array($row) || $row === []) {
  1048. return $out;
  1049. }
  1050. $nick = trim((string)($row['nickname'] ?? ''));
  1051. if ($nick !== '') {
  1052. $out['contact_name'] = $nick;
  1053. }
  1054. $mob = trim((string)($row['mobile'] ?? ''));
  1055. if ($mob !== '') {
  1056. $out['phone'] = $mob;
  1057. }
  1058. $em = trim((string)($row['email'] ?? ''));
  1059. if ($em !== '') {
  1060. $out['email'] = $em;
  1061. }
  1062. return $out;
  1063. }
  1064. /**
  1065. * 旧会话补全 customer_id 等字段
  1066. */
  1067. protected function mprocSyncSessionCustomerUser(array $user): array
  1068. {
  1069. if (!empty($user['is_admin'])) {
  1070. return $user;
  1071. }
  1072. $cu = $this->mprocResolveCustomerUserForSession($user);
  1073. if (!$cu) {
  1074. return $user;
  1075. }
  1076. $id = (int)($cu['id'] ?? 0);
  1077. $user['customer_id'] = $id;
  1078. $user['customer_user_id'] = $id;
  1079. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1080. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1081. $user['account'] = trim((string)($cu['account'] ?? ''));
  1082. $mob = trim((string)($cu['phone'] ?? ''));
  1083. if ($mob === '') {
  1084. $mob = trim((string)($cu['account'] ?? ''));
  1085. }
  1086. if ($mob !== '') {
  1087. $user['phone'] = $mob;
  1088. }
  1089. $token = Session::get('mproc_token');
  1090. if ($token) {
  1091. $user['login_time'] = (int)($user['login_time'] ?? time());
  1092. $tok = trim((string)$token);
  1093. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1094. if (!$this->mprocIsSignedAuthToken($tok)) {
  1095. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1096. }
  1097. }
  1098. return $user;
  1099. }
  1100. /**
  1101. * 「我的」:普通用户 customer;管理员 admin
  1102. */
  1103. protected function mprocProfileForUser(array $user)
  1104. {
  1105. if (!empty($user['is_admin'])) {
  1106. return $this->mprocProfileForAdmin($user);
  1107. }
  1108. $cu = $this->mprocResolveCustomerUserForSession($user);
  1109. if (is_array($cu) && $cu !== []) {
  1110. return $this->mprocProfileFromCustomerUserRow($cu);
  1111. }
  1112. $phone = trim((string)($user['phone'] ?? ''));
  1113. if ($phone === '') {
  1114. $phone = trim((string)($user['account'] ?? ''));
  1115. }
  1116. return [
  1117. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1118. 'contact_name' => trim((string)($user['username'] ?? '')),
  1119. 'phone' => $phone,
  1120. 'email' => '',
  1121. ];
  1122. }
  1123. protected function mprocIsValidScydgyRowId($id): bool
  1124. {
  1125. return (int)$id !== 0;
  1126. }
  1127. /**
  1128. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1129. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1130. *
  1131. * @param array $row 引用:明细行
  1132. * @param array $poRow purchase_order 一行
  1133. */
  1134. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1135. {
  1136. $pl = array_change_key_case($poRow, CASE_LOWER);
  1137. $hdr = [
  1138. 'ccydh' => 'CCYDH',
  1139. 'cyjmc' => 'CYJMC',
  1140. 'cdf' => 'CDF',
  1141. 'cgzzxmc' => 'cGzzxMc',
  1142. 'cgymc' => 'CGYMC',
  1143. 'cdxmc' => 'CDXMC',
  1144. 'ngzl' => 'NGZL',
  1145. 'cdw' => 'CDW',
  1146. 'cgybh' => 'CGYBH',
  1147. ];
  1148. foreach ($hdr as $lk => $out) {
  1149. if (!array_key_exists($lk, $pl)) {
  1150. continue;
  1151. }
  1152. $v = $pl[$lk];
  1153. if ($v !== null && $v !== '') {
  1154. $row[$out] = $v;
  1155. }
  1156. }
  1157. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1158. $qtyRaw = '';
  1159. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1160. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1161. $qtyRaw = trim((string)$pl[$qk]);
  1162. break;
  1163. }
  1164. }
  1165. if ($qtyRaw === '') {
  1166. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1167. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1168. $qtyRaw = trim((string)$poRow[$qk]);
  1169. break;
  1170. }
  1171. }
  1172. }
  1173. if ($qtyRaw !== '') {
  1174. $row['This_quantity'] = $qtyRaw;
  1175. }
  1176. $ceilRaw = '';
  1177. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1178. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1179. $ceilRaw = trim((string)$pl[$ck]);
  1180. break;
  1181. }
  1182. }
  1183. if ($ceilRaw === '') {
  1184. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1185. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1186. $ceilRaw = trim((string)$poRow[$ck]);
  1187. break;
  1188. }
  1189. }
  1190. }
  1191. if ($ceilRaw !== '') {
  1192. $row['ceilingPrice'] = $ceilRaw;
  1193. }
  1194. $sysRq = '';
  1195. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1196. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1197. $sysRq = trim((string)$pl[$sk]);
  1198. break;
  1199. }
  1200. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1201. $sysRq = trim((string)$poRow[$sk]);
  1202. break;
  1203. }
  1204. }
  1205. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1206. $row['sys_rq'] = $sysRq;
  1207. }
  1208. }
  1209. /**
  1210. * 主表报价截止时间(未设置则视为未截止)
  1211. *
  1212. * @param array<string, mixed>|null $po
  1213. */
  1214. protected function mprocResolveSysRqFromPo(?array $po): string
  1215. {
  1216. if (!is_array($po)) {
  1217. return '';
  1218. }
  1219. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1220. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1221. }
  1222. /**
  1223. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1224. *
  1225. * @param array<string, mixed>|null $po
  1226. */
  1227. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1228. {
  1229. $raw = $this->mprocResolveSysRqFromPo($po);
  1230. if ($raw === '') {
  1231. return false;
  1232. }
  1233. $ts = strtotime(str_replace('T', ' ', $raw));
  1234. if ($ts === false || $ts <= 0) {
  1235. return false;
  1236. }
  1237. return time() >= $ts;
  1238. }
  1239. /**
  1240. * 主单已完结后:中标 / 未中标
  1241. *
  1242. * @param array<string, mixed> $row
  1243. * @param array<string, mixed>|null $po
  1244. */
  1245. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1246. {
  1247. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1248. return '';
  1249. }
  1250. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1251. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1252. }
  1253. /**
  1254. * 手机端左侧 Tab:draft|submitted|done
  1255. *
  1256. * @param array<string, mixed> $row
  1257. * @param array<string, mixed>|null $po
  1258. */
  1259. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1260. {
  1261. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1262. return 'done';
  1263. }
  1264. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1265. return 'done';
  1266. }
  1267. if ($effectiveSn === '已提交') {
  1268. return 'submitted';
  1269. }
  1270. return 'draft';
  1271. }
  1272. /**
  1273. * 同一订单号 + 供应商合并为一张卡片
  1274. *
  1275. * @param array<int, array<string, mixed>> $rows
  1276. * @return array<int, array<string, mixed>>
  1277. */
  1278. protected function mprocGroupRowsByOrder(array $rows): array
  1279. {
  1280. $groups = [];
  1281. $order = [];
  1282. foreach ($rows as $row) {
  1283. if (!is_array($row)) {
  1284. continue;
  1285. }
  1286. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1287. $cname = trim((string)($row['company_name'] ?? ''));
  1288. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1289. if (!isset($groups[$key])) {
  1290. $groups[$key] = [
  1291. 'group_key' => $key,
  1292. 'CCYDH' => $ccydh,
  1293. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1294. 'company_name' => $cname,
  1295. 'lines' => [],
  1296. ];
  1297. $order[] = $key;
  1298. }
  1299. $groups[$key]['lines'][] = $row;
  1300. }
  1301. $out = [];
  1302. foreach ($order as $key) {
  1303. $g = $groups[$key];
  1304. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1305. usort($lines, function ($a, $b) {
  1306. $sa = (int)($a['scydgy_id'] ?? 0);
  1307. $sb = (int)($b['scydgy_id'] ?? 0);
  1308. if ($sa !== $sb) {
  1309. return $sa <=> $sb;
  1310. }
  1311. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1312. });
  1313. $g['lines'] = $lines;
  1314. $g['line_count'] = count($lines);
  1315. $canEdit = false;
  1316. foreach ($lines as $ln) {
  1317. if (is_array($ln) && (int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1318. $canEdit = true;
  1319. break;
  1320. }
  1321. }
  1322. $g['can_edit'] = $canEdit ? 1 : 0;
  1323. $remark = '';
  1324. $doneLabel = '';
  1325. $pickResult = '';
  1326. $hasWin = false;
  1327. $hasLose = false;
  1328. $hasExpired = false;
  1329. foreach ($lines as $ln) {
  1330. if (!is_array($ln)) {
  1331. continue;
  1332. }
  1333. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1334. if ($rm !== '' && $remark === '') {
  1335. $remark = $rm;
  1336. }
  1337. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1338. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1339. if ($pr === '中标' || $dl === '中标') {
  1340. $hasWin = true;
  1341. } elseif ($pr === '未中标' || $dl === '未中标') {
  1342. $hasLose = true;
  1343. } elseif ($dl === '已截止') {
  1344. $hasExpired = true;
  1345. }
  1346. }
  1347. if ($hasWin) {
  1348. $doneLabel = '中标';
  1349. $pickResult = '中标';
  1350. } elseif ($hasLose) {
  1351. $doneLabel = '未中标';
  1352. $pickResult = '未中标';
  1353. } elseif ($hasExpired) {
  1354. $doneLabel = '已截止';
  1355. $pickResult = '';
  1356. }
  1357. $g['remark'] = $remark;
  1358. $g['mproc_done_label'] = $doneLabel;
  1359. $g['mproc_pick_result'] = $pickResult;
  1360. $out[] = $g;
  1361. }
  1362. return $out;
  1363. }
  1364. /**
  1365. * 查询 purchase_order_detail 列表(订单页)
  1366. * 无搜索词时:左侧 Tab 按 status_name 筛选(未提交/已提交/已完成)
  1367. * 有搜索词时:不按 Tab 筛选,在本单位可见数据内全局关键字匹配
  1368. *
  1369. * @param string $tab draft|submitted|done
  1370. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  1371. * @return array{rows: array, done_no_status: int}
  1372. */
  1373. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  1374. {
  1375. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  1376. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  1377. $userWhere = $this->mprocListWhereForLoginUser($user);
  1378. if ($userWhere !== []) {
  1379. $query->where($userWhere);
  1380. }
  1381. if (trim((string)$q) === '' && $tab === 'done' && $statusNameCol !== null) {
  1382. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  1383. }
  1384. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  1385. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  1386. try {
  1387. $rows = $query->limit(500)->select();
  1388. } catch (\Throwable $e) {
  1389. $rows = [];
  1390. }
  1391. if (!is_array($rows)) {
  1392. $rows = [];
  1393. }
  1394. $poBySid = [];
  1395. $sidList = [];
  1396. foreach ($rows as $r0) {
  1397. if (!is_array($r0)) {
  1398. continue;
  1399. }
  1400. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  1401. if ($this->mprocIsValidScydgyRowId($sid0)) {
  1402. $sidList[$sid0] = true;
  1403. }
  1404. }
  1405. if ($sidList !== []) {
  1406. try {
  1407. $poRows = Db::table('purchase_order')
  1408. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  1409. ->select();
  1410. if (is_array($poRows)) {
  1411. foreach ($poRows as $pr) {
  1412. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1413. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1414. $poBySid[$sidk] = $pr;
  1415. }
  1416. }
  1417. }
  1418. } catch (\Throwable $e) {
  1419. }
  1420. }
  1421. foreach ($rows as &$row) {
  1422. if (!is_array($row)) {
  1423. continue;
  1424. }
  1425. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  1426. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1427. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  1428. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  1429. }
  1430. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  1431. $oldSn = trim((string)($row['status_name'] ?? ''));
  1432. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  1433. $row['status_name'] = $effectiveSn;
  1434. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  1435. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  1436. }
  1437. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  1438. $row['mproc_list_tab'] = $listTab;
  1439. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  1440. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  1441. if ($row['mproc_pick_result'] === '' && $listTab === 'done' && $row['mproc_deadline_reached']) {
  1442. $row['mproc_done_label'] = '已截止';
  1443. } elseif ($row['mproc_pick_result'] !== '') {
  1444. $row['mproc_done_label'] = $row['mproc_pick_result'];
  1445. } else {
  1446. $row['mproc_done_label'] = '';
  1447. }
  1448. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  1449. if (!isset($row['status_name']) || $row['status_name'] === null) {
  1450. $row['status_name'] = '';
  1451. } else {
  1452. $row['status_name'] = trim((string)$row['status_name']);
  1453. }
  1454. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  1455. $am = $row['amount'] ?? null;
  1456. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  1457. $row['amount_display'] = '';
  1458. } else {
  1459. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  1460. }
  1461. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1462. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1463. $row['delivery_display'] = $m[1];
  1464. } elseif ($dv !== '') {
  1465. $row['delivery_display'] = $dv;
  1466. } else {
  1467. $row['delivery_display'] = '';
  1468. }
  1469. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1470. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1471. $row['mproc_fill_hint'] = '';
  1472. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1473. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  1474. }
  1475. unset($row);
  1476. if (trim((string)$q) === '') {
  1477. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  1478. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  1479. }));
  1480. }
  1481. $groups = $this->mprocGroupRowsByOrder($rows);
  1482. return [
  1483. 'rows' => $rows ?: [],
  1484. 'groups' => $groups ?: [],
  1485. 'done_no_status' => (int)($statusNameCol === null),
  1486. ];
  1487. }
  1488. /**
  1489. * status_name → 手机端左侧 Tab
  1490. */
  1491. protected function mprocStatusNameToListTab(string $statusName): string
  1492. {
  1493. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  1494. $sn = trim($statusName);
  1495. return isset($map[$sn]) ? $map[$sn] : '';
  1496. }
  1497. /**
  1498. * 短信/邮件 focus_eid 应落在的列表 Tab
  1499. */
  1500. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  1501. {
  1502. if ($focusEid <= 0) {
  1503. return '';
  1504. }
  1505. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1506. if ($idCol === null) {
  1507. return '';
  1508. }
  1509. try {
  1510. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  1511. $qw = $this->mprocListWhereForLoginUser($user);
  1512. if ($qw !== []) {
  1513. $qrow->where($qw);
  1514. }
  1515. $dr = $qrow->find();
  1516. } catch (\Throwable $e) {
  1517. $dr = null;
  1518. }
  1519. if (!is_array($dr) || $dr === []) {
  1520. return '';
  1521. }
  1522. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  1523. $po = null;
  1524. if ($this->mprocIsValidScydgyRowId($sid)) {
  1525. try {
  1526. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1527. } catch (\Throwable $e) {
  1528. $po = null;
  1529. }
  1530. }
  1531. return $this->mprocResolveListTabForRow(
  1532. $dr,
  1533. is_array($po) ? $po : null,
  1534. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  1535. );
  1536. }
  1537. /**
  1538. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  1539. *
  1540. * @param array<string, mixed> $bundle
  1541. * @param array<string, mixed> $user
  1542. * @return array<string, mixed>
  1543. */
  1544. protected function mprocEnsureFocusRowInList(
  1545. array $bundle,
  1546. int $focusEid,
  1547. array $user,
  1548. $statusNameCol,
  1549. string $tab = 'draft',
  1550. string $q = ''
  1551. ): array {
  1552. if ($focusEid <= 0) {
  1553. return $bundle;
  1554. }
  1555. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  1556. $foundIdx = -1;
  1557. foreach ($rows as $idx => $r) {
  1558. if (!is_array($r)) {
  1559. continue;
  1560. }
  1561. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  1562. $foundIdx = (int)$idx;
  1563. break;
  1564. }
  1565. }
  1566. if ($foundIdx > 0) {
  1567. $hit = $rows[$foundIdx];
  1568. array_splice($rows, $foundIdx, 1);
  1569. array_unshift($rows, $hit);
  1570. $bundle['rows'] = $rows;
  1571. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  1572. return $bundle;
  1573. }
  1574. if ($foundIdx === 0) {
  1575. return $bundle;
  1576. }
  1577. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1578. if ($idCol === null) {
  1579. return $bundle;
  1580. }
  1581. try {
  1582. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  1583. $qw = $this->mprocListWhereForLoginUser($user);
  1584. if ($qw !== []) {
  1585. $qrow->where($qw);
  1586. }
  1587. $dr = $qrow->find();
  1588. } catch (\Throwable $e) {
  1589. $dr = null;
  1590. }
  1591. if (!is_array($dr) || $dr === []) {
  1592. return $bundle;
  1593. }
  1594. $row = $dr;
  1595. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  1596. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1597. $poRow = null;
  1598. if ($this->mprocIsValidScydgyRowId($sid)) {
  1599. try {
  1600. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1601. } catch (\Throwable $e) {
  1602. $poRow = null;
  1603. }
  1604. if (is_array($poRow)) {
  1605. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  1606. }
  1607. }
  1608. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  1609. if (trim((string)$q) === '') {
  1610. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  1611. if ($rowTab !== '' && $rowTab !== $tab) {
  1612. return $bundle;
  1613. }
  1614. }
  1615. $row['status_name'] = $effectiveSn;
  1616. $listTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  1617. $row['mproc_list_tab'] = $listTab;
  1618. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  1619. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  1620. if ($row['mproc_pick_result'] === '' && $listTab === 'done' && $row['mproc_deadline_reached']) {
  1621. $row['mproc_done_label'] = '已截止';
  1622. } elseif ($row['mproc_pick_result'] !== '') {
  1623. $row['mproc_done_label'] = $row['mproc_pick_result'];
  1624. } else {
  1625. $row['mproc_done_label'] = '';
  1626. }
  1627. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  1628. $am = $row['amount'] ?? null;
  1629. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  1630. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1631. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1632. $row['delivery_display'] = $m[1];
  1633. } elseif ($dv !== '') {
  1634. $row['delivery_display'] = $dv;
  1635. } else {
  1636. $row['delivery_display'] = '';
  1637. }
  1638. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1639. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1640. $row['mproc_fill_hint'] = '';
  1641. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1642. array_unshift($rows, $row);
  1643. $bundle['rows'] = $rows;
  1644. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  1645. return $bundle;
  1646. }
  1647. /**
  1648. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  1649. *
  1650. * @param array<string, mixed> $row
  1651. */
  1652. protected function mprocResolveDisplayThisQuantity(array $row): string
  1653. {
  1654. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  1655. if ($qty !== '') {
  1656. return $qty;
  1657. }
  1658. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  1659. if ($gzl === null || $gzl === '') {
  1660. return '';
  1661. }
  1662. return is_scalar($gzl) ? trim((string)$gzl) : '';
  1663. }
  1664. /**
  1665. * 明细是否已填写单价或交货日期
  1666. *
  1667. * @param array<string, mixed> $row
  1668. */
  1669. protected function mprocDetailQuoteSubmitted(array $row): bool
  1670. {
  1671. $am = $row['amount'] ?? null;
  1672. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1673. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  1674. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  1675. return $amountFilled || $deliveryFilled;
  1676. }
  1677. /**
  1678. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  1679. *
  1680. * @param array<string, mixed> $row
  1681. * @param array<string, mixed>|null $po
  1682. */
  1683. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  1684. {
  1685. $sn = trim((string)($row['status_name'] ?? ''));
  1686. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  1687. return $sn;
  1688. }
  1689. if (!is_array($po)) {
  1690. if ($sn !== '') {
  1691. return $sn;
  1692. }
  1693. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  1694. }
  1695. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  1696. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  1697. if ($sn !== '') {
  1698. return $sn;
  1699. }
  1700. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  1701. }
  1702. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1703. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  1704. return '已完成';
  1705. }
  1706. if ($sn === '已提交') {
  1707. return '未通过';
  1708. }
  1709. return $sn !== '' ? $sn : '未提交';
  1710. }
  1711. /**
  1712. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  1713. */
  1714. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  1715. {
  1716. if ($detailId <= 0 || $statusNameCol === '') {
  1717. return;
  1718. }
  1719. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1720. if ($idCol === null || $idCol === '') {
  1721. return;
  1722. }
  1723. try {
  1724. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  1725. } catch (\Throwable $e) {
  1726. }
  1727. }
  1728. /**
  1729. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  1730. *
  1731. * @param array<string, mixed> $user
  1732. */
  1733. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  1734. {
  1735. $userWhere = $this->mprocListWhereForLoginUser($user);
  1736. try {
  1737. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  1738. if ($userWhere !== []) {
  1739. $query->where($userWhere);
  1740. }
  1741. $candidates = $query->limit(200)->select();
  1742. } catch (\Throwable $e) {
  1743. return;
  1744. }
  1745. if (!is_array($candidates) || $candidates === []) {
  1746. return;
  1747. }
  1748. $sidList = [];
  1749. foreach ($candidates as $cr) {
  1750. if (!is_array($cr)) {
  1751. continue;
  1752. }
  1753. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  1754. if ($this->mprocIsValidScydgyRowId($sid)) {
  1755. $sidList[$sid] = true;
  1756. }
  1757. }
  1758. if ($sidList === []) {
  1759. return;
  1760. }
  1761. $poBySid = [];
  1762. try {
  1763. $poRows = Db::table('purchase_order')
  1764. ->where('scydgy_id', 'in', array_keys($sidList))
  1765. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  1766. ->select();
  1767. if (is_array($poRows)) {
  1768. foreach ($poRows as $pr) {
  1769. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1770. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1771. $poBySid[$sidk] = $pr;
  1772. }
  1773. }
  1774. }
  1775. } catch (\Throwable $e) {
  1776. return;
  1777. }
  1778. if ($poBySid === []) {
  1779. return;
  1780. }
  1781. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1782. if ($idCol === null || $idCol === '') {
  1783. return;
  1784. }
  1785. foreach ($candidates as $cr) {
  1786. if (!is_array($cr)) {
  1787. continue;
  1788. }
  1789. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  1790. if (!isset($poBySid[$sid])) {
  1791. continue;
  1792. }
  1793. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  1794. if ($detailId <= 0) {
  1795. continue;
  1796. }
  1797. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  1798. if ($targetSn === '已提交') {
  1799. continue;
  1800. }
  1801. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  1802. }
  1803. }
  1804. /**
  1805. * 协助明细首页(需登录)
  1806. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  1807. */
  1808. public function index()
  1809. {
  1810. $user = $this->mprocGetUser();
  1811. if (!$user) {
  1812. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  1813. if ($pendingFocus > 0) {
  1814. $this->mprocRememberFocusEid($pendingFocus);
  1815. }
  1816. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  1817. $safe = $this->mprocSanitizeRedirectUrl($uri);
  1818. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  1819. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  1820. }
  1821. if ($safe !== '') {
  1822. Session::set('mproc_intended_url', $safe);
  1823. }
  1824. $this->redirect($this->mprocBuildLoginUrl($safe));
  1825. return;
  1826. }
  1827. $user = $this->mprocSyncSessionCustomerUser($user);
  1828. $tabParam = trim((string)$this->request->get('tab', 'draft'));
  1829. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  1830. // 旧地址 ?tab=me 表示「我的」
  1831. if ($tabParam === 'me') {
  1832. $mainTab = 'me';
  1833. }
  1834. if (!in_array($mainTab, ['orders', 'me'], true)) {
  1835. $mainTab = 'orders';
  1836. }
  1837. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  1838. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  1839. $tab = 'draft';
  1840. }
  1841. $q = trim((string)$this->request->get('q', ''));
  1842. $mprocFocusEid = 0;
  1843. $focusEid = $this->mprocReadFocusEidFromRequest();
  1844. if ($focusEid > 0 && $mainTab === 'orders') {
  1845. $mprocFocusEid = $focusEid;
  1846. // 仅邮件/短信直链(URL 带 focus_eid)时自动切 Tab;Session 记忆不覆盖用户手动点的状态
  1847. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  1848. if (!$focusFromUrl) {
  1849. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  1850. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  1851. }
  1852. if ($focusFromUrl && trim((string)$q) === '') {
  1853. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  1854. if ($resolvedTab !== '') {
  1855. $tab = $resolvedTab;
  1856. }
  1857. }
  1858. }
  1859. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  1860. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1861. $profile = $this->mprocProfileForUser($user);
  1862. $this->view->assign('mprocMainTab', $mainTab);
  1863. $this->view->assign('mprocTab', $tab);
  1864. $this->view->assign('mprocSearchQ', $q);
  1865. $this->view->assign('mprocProfile', $profile);
  1866. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  1867. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1868. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  1869. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  1870. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  1871. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  1872. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  1873. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  1874. if ($mainTab === 'me') {
  1875. $this->view->assign('rows', []);
  1876. return $this->view->fetch();
  1877. }
  1878. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  1879. if ($mprocFocusEid > 0) {
  1880. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  1881. }
  1882. $this->view->assign('rows', $bundle['rows']);
  1883. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  1884. return $this->view->fetch();
  1885. }
  1886. /**
  1887. * 协助明细列表 JSON(需登录)
  1888. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  1889. */
  1890. public function mprocList()
  1891. {
  1892. $user = $this->mprocGetUser();
  1893. if (!$user) {
  1894. $this->error('请先登录', url('index/index/login'));
  1895. }
  1896. $user = $this->mprocSyncSessionCustomerUser($user);
  1897. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  1898. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  1899. if ($tabParam === 'me') {
  1900. $mainTab = 'me';
  1901. }
  1902. if (!in_array($mainTab, ['orders', 'me'], true)) {
  1903. $mainTab = 'orders';
  1904. }
  1905. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  1906. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  1907. $tab = 'draft';
  1908. }
  1909. $q = trim((string)$this->request->request('q', ''));
  1910. if ($mainTab === 'me') {
  1911. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  1912. $this->success('ok', '', [
  1913. 'main_tab' => 'me',
  1914. 'tab' => $tab,
  1915. 'rows' => [],
  1916. 'profile' => $this->mprocProfileForUser($user),
  1917. 'done_no_status' => 0,
  1918. ]);
  1919. }
  1920. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  1921. $focusEid = $this->mprocReadFocusEidFromRequest();
  1922. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  1923. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  1924. if ($focusEid > 0) {
  1925. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  1926. }
  1927. $this->success('ok', '', array_merge([
  1928. 'main_tab' => 'orders',
  1929. 'tab' => $tab,
  1930. 'focus_tab' => $focusTab,
  1931. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  1932. 'focus_eid' => $focusEid,
  1933. ], $bundle));
  1934. }
  1935. /**
  1936. * 登录页(手机号验证码 / 账号密码)
  1937. */
  1938. public function login()
  1939. {
  1940. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  1941. if ($this->mprocGetUser()) {
  1942. $this->redirect($this->mprocBuildAfterLoginIndexUrl($redirect));
  1943. }
  1944. if ($redirect !== '') {
  1945. Session::set('mproc_intended_url', $redirect);
  1946. }
  1947. $this->view->assign('mprocLoginRedirect', $redirect);
  1948. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  1949. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  1950. return $this->view->fetch();
  1951. }
  1952. /**
  1953. * 图形验证码(手机号登录用)
  1954. */
  1955. public function captcha($id = '')
  1956. {
  1957. $captcha = new Captcha((array)Config::get('captcha'));
  1958. return $captcha->entry($id);
  1959. }
  1960. /**
  1961. * 发送登录验证码(POST:phone、captcha)
  1962. */
  1963. public function sendSms()
  1964. {
  1965. if (!$this->request->isPost()) {
  1966. $this->error('请使用 POST');
  1967. }
  1968. $phone = trim((string)$this->request->post('phone', ''));
  1969. $captcha = trim((string)$this->request->post('captcha', ''));
  1970. if (!preg_match('/^1\d{10}$/', $phone)) {
  1971. $this->error('请输入正确的11位手机号');
  1972. }
  1973. if ($captcha === '') {
  1974. $this->error('请输入图形验证码');
  1975. }
  1976. if (!$this->mprocFindCustomerUserByMobile($phone)) {
  1977. $this->error('该手机号未开通或已禁用,请联系管理员');
  1978. }
  1979. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  1980. if (Cache::get('mproc_sms_wait_' . $phone)) {
  1981. $this->error('发送过于频繁,请稍后再试');
  1982. }
  1983. if (!Validate::is($captcha, 'captcha')) {
  1984. $this->error('图形验证码不正确');
  1985. }
  1986. $code = (string)random_int(100000, 999999);
  1987. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  1988. $ttl = max(60, min(600, $ttl));
  1989. Cache::set('mproc_code_' . $phone, $code, $ttl);
  1990. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  1991. try {
  1992. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  1993. if ($tpl === '') {
  1994. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  1995. }
  1996. $content = str_replace('{code}', $code, $tpl);
  1997. $this->mprocSmsSend($phone, $content);
  1998. } catch (\Exception $e) {
  1999. Cache::rm('mproc_code_' . $phone);
  2000. Cache::rm('mproc_sms_wait_' . $phone);
  2001. $this->error($e->getMessage());
  2002. }
  2003. $this->success('验证码已发送');
  2004. }
  2005. /**
  2006. * 验证码登录(POST:phone、code)
  2007. */
  2008. public function doLogin()
  2009. {
  2010. if (!$this->request->isPost()) {
  2011. $this->error('请使用 POST');
  2012. }
  2013. $phone = trim((string)$this->request->post('phone', ''));
  2014. $code = trim((string)$this->request->post('code', ''));
  2015. if (!preg_match('/^1\d{10}$/', $phone)) {
  2016. $this->error('手机号格式不正确');
  2017. }
  2018. if (!preg_match('/^\d{6}$/', $code)) {
  2019. $this->error('请输入6位验证码');
  2020. }
  2021. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2022. $mock = Config::get('mproc.mock_sms_code');
  2023. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2024. Cache::rm('mproc_code_' . $phone);
  2025. } else {
  2026. $cached = Cache::get('mproc_code_' . $phone);
  2027. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2028. $this->error('验证码错误或已过期');
  2029. }
  2030. Cache::rm('mproc_code_' . $phone);
  2031. }
  2032. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2033. if (!$cu) {
  2034. $this->error('该手机号未开通或已禁用,请联系管理员');
  2035. }
  2036. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2037. }
  2038. /**
  2039. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2040. */
  2041. public function mprocRestore()
  2042. {
  2043. if (!$this->request->isPost()) {
  2044. $this->error('请使用 POST');
  2045. }
  2046. $token = $this->mprocReadTokenFromRequest();
  2047. $user = null;
  2048. if ($token !== '') {
  2049. $user = $this->mprocLoadUserByToken($token);
  2050. }
  2051. if (!$user) {
  2052. $user = $this->mprocUserFromRememberCookie();
  2053. if ($user) {
  2054. $token = $this->mprocPackSignedAuthToken($user);
  2055. }
  2056. }
  2057. if (!$user) {
  2058. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2059. }
  2060. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2061. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2062. $jump = $this->mprocBuildAfterLoginIndexUrl($redirect);
  2063. $this->success('ok', $jump, [
  2064. 'mproc_token' => $token,
  2065. 'keep_hours' => $this->mprocKeepHours(),
  2066. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2067. ]);
  2068. }
  2069. /**
  2070. * 账号密码登录(POST:username、password)
  2071. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2072. */
  2073. public function doLoginPwd()
  2074. {
  2075. if (!$this->request->isPost()) {
  2076. $this->error('请使用 POST');
  2077. }
  2078. $username = trim((string)$this->request->post('username', ''));
  2079. $password = (string)$this->request->post('password', '');
  2080. if ($username === '' || $password === '') {
  2081. $this->error('请输入账号和密码');
  2082. }
  2083. $cu = $this->mprocFindCustomerUserByUsername($username);
  2084. if ($cu) {
  2085. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2086. $this->error('账号或密码错误');
  2087. }
  2088. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2089. }
  2090. // 管理员:表 admin
  2091. $row = null;
  2092. try {
  2093. $row = Db::name('admin')
  2094. ->field('id,username,password,salt,status,loginfailure,updatetime')
  2095. ->where('username', $username)
  2096. ->find();
  2097. } catch (\Throwable $e) {
  2098. $row = null;
  2099. }
  2100. if (!$row || !is_array($row)) {
  2101. $this->error('账号或密码错误');
  2102. }
  2103. $id = (int)($row['id'] ?? 0);
  2104. if (($row['status'] ?? '') == 'hidden') {
  2105. $this->error('该账号已禁用');
  2106. }
  2107. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  2108. $this->error('登录失败次数过多,请24小时后再试');
  2109. }
  2110. $salt = (string)($row['salt'] ?? '');
  2111. $hashStored = (string)($row['password'] ?? '');
  2112. $hashInput = md5(md5($password) . $salt);
  2113. if ($hashStored === '' || $hashInput !== $hashStored) {
  2114. if ($id > 0) {
  2115. try {
  2116. Db::name('admin')->where('id', $id)->update([
  2117. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  2118. 'updatetime' => time(),
  2119. ]);
  2120. } catch (\Throwable $e) {
  2121. }
  2122. }
  2123. $this->error('账号或密码错误');
  2124. }
  2125. if ($id > 0) {
  2126. try {
  2127. Db::name('admin')->where('id', $id)->update([
  2128. 'loginfailure' => 0,
  2129. 'updatetime' => time(),
  2130. ]);
  2131. } catch (\Throwable $e) {
  2132. }
  2133. }
  2134. $this->mprocFinishLogin([
  2135. 'phone' => trim((string)($row['mobile'] ?? '')),
  2136. 'company_name' => '',
  2137. 'username' => $username,
  2138. 'customer_user_id' => 0,
  2139. 'login_type' => 'pwd',
  2140. 'is_admin' => 1,
  2141. ]);
  2142. }
  2143. /**
  2144. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  2145. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  2146. */
  2147. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  2148. {
  2149. if (!empty($user['is_admin'])) {
  2150. return false;
  2151. }
  2152. $sn = trim((string)($row['status_name'] ?? ''));
  2153. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2154. return false;
  2155. }
  2156. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  2157. return false;
  2158. }
  2159. $uCo = trim((string)($user['company_name'] ?? ''));
  2160. if ($uCo === '') {
  2161. $uPhone = trim((string)($user['phone'] ?? ''));
  2162. if ($uPhone !== '') {
  2163. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  2164. }
  2165. }
  2166. $rCo = trim((string)($row['company_name'] ?? ''));
  2167. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  2168. return true;
  2169. }
  2170. $uPhone = trim((string)($user['phone'] ?? ''));
  2171. $rPhone = trim((string)($row['phone'] ?? ''));
  2172. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  2173. }
  2174. /**
  2175. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  2176. *
  2177. * @param array<string, mixed> $detailRow
  2178. */
  2179. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  2180. {
  2181. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  2182. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  2183. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  2184. try {
  2185. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2186. } catch (\Throwable $e) {
  2187. $po = null;
  2188. }
  2189. if (is_array($po)) {
  2190. $pl = array_change_key_case($po, CASE_LOWER);
  2191. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  2192. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  2193. $raw = trim((string)$pl[$ck]);
  2194. break;
  2195. }
  2196. }
  2197. if ($raw === '') {
  2198. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  2199. }
  2200. }
  2201. }
  2202. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  2203. return null;
  2204. }
  2205. return (float)$raw;
  2206. }
  2207. protected function mprocFormatCeilingPriceDisplay(float $n): string
  2208. {
  2209. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  2210. return $s === '' ? '0' : $s;
  2211. }
  2212. /**
  2213. * 保存单条协助明细的金额、交期(内部)
  2214. *
  2215. * @param array<string, mixed> $user
  2216. * @param int $id
  2217. * @param string $amountRaw
  2218. * @param string $deliveryRaw
  2219. * @return string 工序名(用于批量错误提示)
  2220. */
  2221. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw): string
  2222. {
  2223. if ($id <= 0) {
  2224. throw new \InvalidArgumentException('参数错误');
  2225. }
  2226. $row = null;
  2227. try {
  2228. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  2229. if (!$row) {
  2230. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  2231. }
  2232. } catch (\Throwable $e) {
  2233. $row = null;
  2234. }
  2235. if (!$row || !is_array($row)) {
  2236. throw new \InvalidArgumentException('记录不存在');
  2237. }
  2238. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  2239. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2240. $po = null;
  2241. if ($this->mprocIsValidScydgyRowId($sid)) {
  2242. try {
  2243. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2244. } catch (\Throwable $e) {
  2245. $po = null;
  2246. }
  2247. if (is_array($po)) {
  2248. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  2249. if ($gymc === '') {
  2250. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2251. }
  2252. }
  2253. }
  2254. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  2255. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  2256. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  2257. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  2258. }
  2259. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  2260. throw new \InvalidArgumentException($label . '报价已截止,不能再修改');
  2261. }
  2262. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  2263. if (!empty($user['is_admin'])) {
  2264. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  2265. }
  2266. throw new \InvalidArgumentException($label . '无权修改');
  2267. }
  2268. $amountRaw = trim($amountRaw);
  2269. $deliveryRaw = trim($deliveryRaw);
  2270. $data = [];
  2271. if ($amountRaw === '') {
  2272. $data['amount'] = null;
  2273. } else {
  2274. if (!preg_match('/^-?\d+(\.\d{1,5})?$/', $amountRaw)) {
  2275. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  2276. }
  2277. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  2278. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  2279. throw new \InvalidArgumentException(
  2280. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  2281. );
  2282. }
  2283. $data['amount'] = $amountRaw;
  2284. }
  2285. if ($deliveryRaw === '') {
  2286. $data['delivery'] = null;
  2287. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  2288. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2289. $timePart = date('H:i:s');
  2290. if ($existingDel !== '') {
  2291. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  2292. if ($tsEx !== false) {
  2293. $hms = date('H:i:s', $tsEx);
  2294. if ($hms !== '00:00:00') {
  2295. $timePart = $hms;
  2296. }
  2297. }
  2298. }
  2299. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  2300. } else {
  2301. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  2302. $ts = strtotime($deliveryRaw);
  2303. if ($ts === false) {
  2304. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  2305. }
  2306. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  2307. }
  2308. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  2309. if ($dcCol !== null && array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  2310. $data[$dcCol] = date('Y-m-d H:i:s');
  2311. }
  2312. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2313. if ($upCol !== null) {
  2314. $data[$upCol] = date('Y-m-d H:i:s');
  2315. }
  2316. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2317. if ($statusNameCol !== null) {
  2318. $curSn = '';
  2319. foreach ($row as $k => $v) {
  2320. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  2321. $curSn = trim((string)$v);
  2322. break;
  2323. }
  2324. }
  2325. if ($curSn !== '已完成') {
  2326. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  2327. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  2328. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  2329. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  2330. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2331. }
  2332. }
  2333. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  2334. $pkVal = (int)($row[$pkField] ?? $id);
  2335. try {
  2336. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  2337. } catch (\Throwable $e) {
  2338. $msg = $e->getMessage();
  2339. if (stripos($msg, 'Unknown column') !== false) {
  2340. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery 字段';
  2341. }
  2342. throw new \RuntimeException('保存失败:' . $msg);
  2343. }
  2344. if ($aff === false) {
  2345. throw new \RuntimeException($label . '保存失败');
  2346. }
  2347. return $gymc;
  2348. }
  2349. /**
  2350. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  2351. *
  2352. * @param array<string, mixed> $user
  2353. * @param int[] $detailIds 本次保存涉及的明细 ID
  2354. * @param string $remarkRaw
  2355. */
  2356. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  2357. {
  2358. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  2359. if ($remarkCol === null) {
  2360. return;
  2361. }
  2362. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2363. if ($detailIds === []) {
  2364. return;
  2365. }
  2366. $anchorId = $detailIds[0];
  2367. $row = null;
  2368. try {
  2369. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  2370. if (!$row) {
  2371. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  2372. }
  2373. } catch (\Throwable $e) {
  2374. $row = null;
  2375. }
  2376. if (!$row || !is_array($row)) {
  2377. throw new \InvalidArgumentException('记录不存在');
  2378. }
  2379. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2380. $po = null;
  2381. if ($this->mprocIsValidScydgyRowId($sid)) {
  2382. try {
  2383. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2384. } catch (\Throwable $e) {
  2385. $po = null;
  2386. }
  2387. if (is_array($po)) {
  2388. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  2389. }
  2390. }
  2391. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  2392. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  2393. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  2394. }
  2395. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  2396. throw new \InvalidArgumentException('报价已截止,不能再修改备注');
  2397. }
  2398. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  2399. if (!empty($user['is_admin'])) {
  2400. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  2401. }
  2402. throw new \InvalidArgumentException('无权修改备注');
  2403. }
  2404. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  2405. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  2406. if ($ccydhCol === null || $companyCol === null) {
  2407. return;
  2408. }
  2409. $ccydh = '';
  2410. $company = '';
  2411. foreach ($row as $k => $v) {
  2412. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  2413. $ccydh = trim((string)$v);
  2414. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  2415. $company = trim((string)$v);
  2416. }
  2417. }
  2418. if ($ccydh === '' || $company === '') {
  2419. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  2420. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  2421. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2422. if ($upCol !== null) {
  2423. $data[$upCol] = date('Y-m-d H:i:s');
  2424. }
  2425. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  2426. return;
  2427. }
  2428. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  2429. $data = [$remarkCol => $remarkVal];
  2430. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2431. if ($upCol !== null) {
  2432. $data[$upCol] = date('Y-m-d H:i:s');
  2433. }
  2434. $query = Db::table('purchase_order_detail')
  2435. ->where($ccydhCol, $ccydh)
  2436. ->where($companyCol, $company);
  2437. $userWhere = $this->mprocListWhereForLoginUser($user);
  2438. if ($userWhere !== []) {
  2439. $query->where($userWhere);
  2440. }
  2441. try {
  2442. $query->update($data);
  2443. } catch (\Throwable $e) {
  2444. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  2445. }
  2446. }
  2447. /**
  2448. * 保存协助明细金额、交期
  2449. * 单条:POST id、amount、delivery
  2450. * 批量:POST items=[{id,amount,delivery},...] JSON
  2451. */
  2452. public function mprocSave()
  2453. {
  2454. if (!$this->request->isPost()) {
  2455. $this->error('请使用 POST');
  2456. }
  2457. $user = $this->mprocGetUser();
  2458. if (!$user) {
  2459. $this->error('请先登录', url('index/index/login'));
  2460. }
  2461. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  2462. $itemsRaw = $this->request->post('items', '', null);
  2463. if ($itemsRaw === '' || $itemsRaw === null) {
  2464. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  2465. }
  2466. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  2467. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  2468. }
  2469. $items = [];
  2470. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  2471. $decoded = json_decode($itemsRaw, true);
  2472. if (!is_array($decoded)) {
  2473. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  2474. }
  2475. if (is_array($decoded)) {
  2476. $items = $decoded;
  2477. }
  2478. } elseif (is_array($itemsRaw)) {
  2479. $items = $itemsRaw;
  2480. }
  2481. if ($items === []) {
  2482. $id = (int)$this->request->post('id', 0, null);
  2483. if ($id <= 0) {
  2484. $this->error('保存失败,请关闭弹窗后重试');
  2485. }
  2486. $items = [[
  2487. 'id' => $id,
  2488. 'amount' => (string)$this->request->post('amount', '', null),
  2489. 'delivery' => (string)$this->request->post('delivery', '', null),
  2490. ]];
  2491. }
  2492. $saved = 0;
  2493. $savedIds = [];
  2494. $remarkRaw = $this->request->post('remark', '', null);
  2495. if ($remarkRaw === '' || $remarkRaw === null) {
  2496. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  2497. }
  2498. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  2499. Db::startTrans();
  2500. try {
  2501. foreach ($items as $it) {
  2502. if (!is_array($it)) {
  2503. continue;
  2504. }
  2505. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  2506. if ($id <= 0) {
  2507. continue;
  2508. }
  2509. $delivery = (string)($it['delivery'] ?? '');
  2510. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  2511. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  2512. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  2513. }
  2514. $this->mprocSaveDetailQuote(
  2515. $user,
  2516. $id,
  2517. (string)($it['amount'] ?? ''),
  2518. $delivery
  2519. );
  2520. $saved++;
  2521. $savedIds[] = $id;
  2522. }
  2523. if ($saved < 1) {
  2524. throw new \InvalidArgumentException('没有可保存的工序,请刷新后重试');
  2525. }
  2526. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  2527. Db::commit();
  2528. } catch (\InvalidArgumentException $e) {
  2529. Db::rollback();
  2530. $this->error($e->getMessage());
  2531. } catch (\Throwable $e) {
  2532. Db::rollback();
  2533. $this->error($e->getMessage());
  2534. }
  2535. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  2536. }
  2537. /**
  2538. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  2539. */
  2540. public function mprocChangePwd()
  2541. {
  2542. if (!$this->request->isPost()) {
  2543. $this->error('请使用 POST');
  2544. }
  2545. $user = $this->mprocGetUser();
  2546. if (!$user) {
  2547. $this->error('请先登录', url('index/index/login'));
  2548. }
  2549. $user = $this->mprocSyncSessionCustomerUser($user);
  2550. if (!empty($user['is_admin'])) {
  2551. $this->error('当前账号不支持修改密码');
  2552. }
  2553. $cu = $this->mprocResolveCustomerUserForSession($user);
  2554. if (!$cu) {
  2555. $this->error('账号不存在或已禁用');
  2556. }
  2557. $oldPwd = (string)$this->request->post('old_password', '');
  2558. $newPwd = (string)$this->request->post('new_password', '');
  2559. $renewPwd = (string)$this->request->post('renew_password', '');
  2560. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  2561. $this->error('请填写完整');
  2562. }
  2563. if (strlen($newPwd) < 4) {
  2564. $this->error('新密码至少4位');
  2565. }
  2566. if ($newPwd !== $renewPwd) {
  2567. $this->error('两次输入的新密码不一致');
  2568. }
  2569. if ($oldPwd === $newPwd) {
  2570. $this->error('新密码不能与旧密码相同');
  2571. }
  2572. $cuId = (int)($cu['id'] ?? 0);
  2573. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  2574. $this->error('原密码不正确');
  2575. }
  2576. $data = [
  2577. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  2578. 'updatetime' => date('Y-m-d H:i:s'),
  2579. ];
  2580. try {
  2581. Db::table('customer')->where('id', $cuId)->update($data);
  2582. } catch (\Throwable $e) {
  2583. $this->error('修改失败:' . $e->getMessage());
  2584. }
  2585. $this->success('密码已修改');
  2586. }
  2587. /**
  2588. * 退出登录
  2589. */
  2590. public function logout()
  2591. {
  2592. $token = Session::get('mproc_token');
  2593. if ($token === null || $token === '') {
  2594. $token = Cookie::get('mproc_token');
  2595. }
  2596. if ($token) {
  2597. $this->mprocClearLogin(preg_replace('/[^a-f0-9]/i', '', (string)$token));
  2598. }
  2599. $this->redirect(url('index/index/login'));
  2600. }
  2601. /**
  2602. * 短信宝(与后台协助审核一致,便于复用账号)
  2603. *
  2604. * @throws \Exception
  2605. */
  2606. protected function mprocSmsSend($phone, $content)
  2607. {
  2608. $statusStr = [
  2609. '0' => '短信发送成功',
  2610. '-1' => '参数不全',
  2611. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  2612. '30' => '密码错误',
  2613. '40' => '账号不存在',
  2614. '41' => '余额不足',
  2615. '42' => '帐户已过期',
  2616. '43' => 'IP地址限制',
  2617. '50' => '内容含有敏感词',
  2618. ];
  2619. $smsapi = 'http://api.smsbao.com/';
  2620. $user = trim((string)Config::get('mproc.smsbao_user'));
  2621. if ($user === '') {
  2622. $user = 'zhuwei123';
  2623. }
  2624. $passPlain = Config::get('mproc.smsbao_pass');
  2625. $pass = ($passPlain !== null && $passPlain !== '')
  2626. ? md5((string)$passPlain)
  2627. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  2628. $phone = trim((string)$phone);
  2629. $content = trim((string)$content);
  2630. if ($phone === '' || $content === '') {
  2631. throw new \Exception('短信发送失败:参数不全');
  2632. }
  2633. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  2634. $result = @file_get_contents($sendurl);
  2635. if ($result === false) {
  2636. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  2637. throw new \Exception('短信发送失败:网络异常');
  2638. }
  2639. $result = trim((string)$result);
  2640. if ($result !== '0') {
  2641. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  2642. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  2643. throw new \Exception('短信发送失败:' . $msg);
  2644. }
  2645. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  2646. }
  2647. }