Index.php 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366
  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. $deliveryDeadline = '';
  1209. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1210. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1211. $deliveryDeadline = trim((string)$pl[$dk]);
  1212. break;
  1213. }
  1214. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1215. $deliveryDeadline = trim((string)$poRow[$dk]);
  1216. break;
  1217. }
  1218. }
  1219. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1220. $row['delivery_deadline'] = $deliveryDeadline;
  1221. }
  1222. }
  1223. /**
  1224. * 统一取年月日(无效则空串)
  1225. */
  1226. protected function mprocFormatYmdValue($raw): string
  1227. {
  1228. $s = trim((string)$raw);
  1229. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1230. return '';
  1231. }
  1232. $s = str_replace(['/', '.'], '-', $s);
  1233. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1234. return $m[1];
  1235. }
  1236. $ts = strtotime(str_replace('T', ' ', $s));
  1237. if ($ts === false || $ts <= 0) {
  1238. return '';
  1239. }
  1240. return date('Y-m-d', $ts);
  1241. }
  1242. /**
  1243. * 列表展示:招标截止 / 交货截止
  1244. *
  1245. * @param array<string, mixed> $row
  1246. */
  1247. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1248. {
  1249. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1250. $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
  1251. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1252. $row['mproc_bid_deadline_display'] = $bid;
  1253. // 完整截止时间供前端保存前校验(含时分秒)
  1254. $row['mproc_bid_deadline'] = $sysRqRaw;
  1255. $row['mproc_delivery_deadline_display'] = $del;
  1256. $row['mproc_delivery_deadline'] = $del;
  1257. }
  1258. /**
  1259. * 明细对应主表的交货截止日期 Y-m-d
  1260. *
  1261. * @param array<string, mixed> $row
  1262. */
  1263. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1264. {
  1265. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1266. if ($fromRow !== '') {
  1267. return $fromRow;
  1268. }
  1269. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1270. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1271. return '';
  1272. }
  1273. try {
  1274. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1275. } catch (\Throwable $e) {
  1276. $po = null;
  1277. }
  1278. if (!is_array($po)) {
  1279. return '';
  1280. }
  1281. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1282. }
  1283. /**
  1284. * 主表报价截止时间(未设置则视为未截止)
  1285. *
  1286. * @param array<string, mixed>|null $po
  1287. */
  1288. protected function mprocResolveSysRqFromPo(?array $po): string
  1289. {
  1290. if (!is_array($po)) {
  1291. return '';
  1292. }
  1293. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1294. if ($sr === '') {
  1295. $pl = array_change_key_case($po, CASE_LOWER);
  1296. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1297. }
  1298. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1299. }
  1300. /**
  1301. * 从主表/明细解析订单号
  1302. *
  1303. * @param array<string, mixed>|null $po
  1304. * @param array<string, mixed>|null $row
  1305. */
  1306. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1307. {
  1308. foreach ([$po, $row] as $src) {
  1309. if (!is_array($src)) {
  1310. continue;
  1311. }
  1312. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1313. if ($c !== '') {
  1314. return $c;
  1315. }
  1316. }
  1317. return '';
  1318. }
  1319. /**
  1320. * 批量:已开标验证的订单号集合(本请求内可复用)
  1321. *
  1322. * @var array<string, bool>|null
  1323. */
  1324. protected $mprocBidOpenVerifiedSet = null;
  1325. /**
  1326. * @param array<int, string> $ccydhs
  1327. * @return array<string, bool>
  1328. */
  1329. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1330. {
  1331. $set = [];
  1332. $list = [];
  1333. foreach ($ccydhs as $c) {
  1334. $c = trim((string)$c);
  1335. if ($c !== '') {
  1336. $list[$c] = true;
  1337. }
  1338. }
  1339. if ($list === []) {
  1340. return $set;
  1341. }
  1342. try {
  1343. $rows = Db::table('purchase_order_bid_open')
  1344. ->where('ccydh', 'in', array_keys($list))
  1345. ->field('ccydh')
  1346. ->select();
  1347. if (!is_array($rows)) {
  1348. return $set;
  1349. }
  1350. foreach ($rows as $row) {
  1351. if (!is_array($row)) {
  1352. continue;
  1353. }
  1354. $c = trim((string)($row['ccydh'] ?? ''));
  1355. if ($c !== '') {
  1356. $set[$c] = true;
  1357. }
  1358. }
  1359. } catch (\Throwable $e) {
  1360. return [];
  1361. }
  1362. return $set;
  1363. }
  1364. /**
  1365. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1366. */
  1367. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1368. {
  1369. $ccydh = trim($ccydh);
  1370. if ($ccydh === '') {
  1371. return false;
  1372. }
  1373. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1374. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1375. }
  1376. try {
  1377. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1378. return is_array($row);
  1379. } catch (\Throwable $e) {
  1380. return false;
  1381. }
  1382. }
  1383. /**
  1384. * @param array<string, mixed>|null $po
  1385. * @param array<string, mixed>|null $row
  1386. */
  1387. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1388. {
  1389. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1390. }
  1391. /**
  1392. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1393. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1394. *
  1395. * @param array<string, mixed>|null $po
  1396. */
  1397. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1398. {
  1399. $raw = $this->mprocResolveSysRqFromPo($po);
  1400. if ($raw === '') {
  1401. return false;
  1402. }
  1403. $ts = strtotime(str_replace('T', ' ', $raw));
  1404. if ($ts === false || $ts <= 0) {
  1405. return false;
  1406. }
  1407. return time() >= $ts;
  1408. }
  1409. /**
  1410. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1411. *
  1412. * @param array<string, mixed>|null $po
  1413. */
  1414. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1415. {
  1416. // 以库中最新主表为准,避免内存中旧快照
  1417. $freshPo = null;
  1418. if (is_array($po)) {
  1419. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1420. if ($this->mprocIsValidScydgyRowId($sid)) {
  1421. try {
  1422. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1423. } catch (\Throwable $e) {
  1424. $freshPo = null;
  1425. }
  1426. }
  1427. }
  1428. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1429. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1430. throw new \InvalidArgumentException(
  1431. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1432. );
  1433. }
  1434. }
  1435. /**
  1436. * 保存前:截止时间 + 已开标均不可再改
  1437. *
  1438. * @param array<string, mixed>|null $po
  1439. * @param array<string, mixed>|null $row
  1440. */
  1441. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1442. {
  1443. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1444. $freshPo = is_array($po) ? $po : null;
  1445. if (is_array($po)) {
  1446. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1447. if ($this->mprocIsValidScydgyRowId($sid)) {
  1448. try {
  1449. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1450. if (is_array($got)) {
  1451. $freshPo = $got;
  1452. }
  1453. } catch (\Throwable $e) {
  1454. }
  1455. }
  1456. }
  1457. // 保存场景不走列表缓存,直接查库
  1458. $prev = $this->mprocBidOpenVerifiedSet;
  1459. $this->mprocBidOpenVerifiedSet = null;
  1460. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1461. $this->mprocBidOpenVerifiedSet = $prev;
  1462. if ($opened) {
  1463. throw new \InvalidArgumentException(
  1464. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1465. );
  1466. }
  1467. }
  1468. /**
  1469. * 主单已完结后:中标 / 未中标
  1470. *
  1471. * @param array<string, mixed> $row
  1472. * @param array<string, mixed>|null $po
  1473. */
  1474. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1475. {
  1476. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1477. return '';
  1478. }
  1479. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1480. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1481. }
  1482. /**
  1483. * 手机端左侧 Tab:draft|submitted|done
  1484. *
  1485. * @param array<string, mixed> $row
  1486. * @param array<string, mixed>|null $po
  1487. */
  1488. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1489. {
  1490. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1491. return 'done';
  1492. }
  1493. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1494. return 'done';
  1495. }
  1496. if ($effectiveSn === '已提交') {
  1497. return 'submitted';
  1498. }
  1499. return 'draft';
  1500. }
  1501. /**
  1502. * 同一订单号 + 供应商合并为一张卡片
  1503. *
  1504. * @param array<int, array<string, mixed>> $rows
  1505. * @return array<int, array<string, mixed>>
  1506. */
  1507. protected function mprocGroupRowsByOrder(array $rows): array
  1508. {
  1509. $groups = [];
  1510. $order = [];
  1511. foreach ($rows as $row) {
  1512. if (!is_array($row)) {
  1513. continue;
  1514. }
  1515. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1516. $cname = trim((string)($row['company_name'] ?? ''));
  1517. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1518. if (!isset($groups[$key])) {
  1519. $groups[$key] = [
  1520. 'group_key' => $key,
  1521. 'CCYDH' => $ccydh,
  1522. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1523. 'company_name' => $cname,
  1524. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  1525. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  1526. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  1527. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  1528. 'lines' => [],
  1529. ];
  1530. $order[] = $key;
  1531. } else {
  1532. if ($groups[$key]['mproc_delivery_deadline'] === ''
  1533. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  1534. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  1535. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  1536. }
  1537. if ($groups[$key]['mproc_bid_deadline'] === ''
  1538. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  1539. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  1540. }
  1541. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  1542. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  1543. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  1544. }
  1545. }
  1546. $groups[$key]['lines'][] = $row;
  1547. }
  1548. $out = [];
  1549. foreach ($order as $key) {
  1550. $g = $groups[$key];
  1551. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1552. usort($lines, function ($a, $b) {
  1553. $sa = (int)($a['scydgy_id'] ?? 0);
  1554. $sb = (int)($b['scydgy_id'] ?? 0);
  1555. if ($sa !== $sb) {
  1556. return $sa <=> $sb;
  1557. }
  1558. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1559. });
  1560. $g['lines'] = $lines;
  1561. $g['line_count'] = count($lines);
  1562. $canEdit = false;
  1563. $bidOpen = false;
  1564. foreach ($lines as $ln) {
  1565. if (!is_array($ln)) {
  1566. continue;
  1567. }
  1568. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1569. $canEdit = true;
  1570. }
  1571. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  1572. $bidOpen = true;
  1573. }
  1574. }
  1575. $g['can_edit'] = $canEdit ? 1 : 0;
  1576. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  1577. $remark = '';
  1578. $doneLabel = '';
  1579. $pickResult = '';
  1580. $hasWin = false;
  1581. $hasLose = false;
  1582. $hasExpired = false;
  1583. foreach ($lines as $ln) {
  1584. if (!is_array($ln)) {
  1585. continue;
  1586. }
  1587. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1588. if ($rm !== '' && $remark === '') {
  1589. $remark = $rm;
  1590. }
  1591. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1592. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1593. if ($pr === '中标' || $dl === '中标') {
  1594. $hasWin = true;
  1595. } elseif ($pr === '未中标' || $dl === '未中标') {
  1596. $hasLose = true;
  1597. } elseif ($dl === '已截止') {
  1598. $hasExpired = true;
  1599. }
  1600. }
  1601. if ($hasWin) {
  1602. $doneLabel = '中标';
  1603. $pickResult = '中标';
  1604. } elseif ($hasLose) {
  1605. $doneLabel = '未中标';
  1606. $pickResult = '未中标';
  1607. } elseif ($hasExpired) {
  1608. $doneLabel = '已截止';
  1609. $pickResult = '';
  1610. }
  1611. $g['remark'] = $remark;
  1612. $g['mproc_done_label'] = $doneLabel;
  1613. $g['mproc_pick_result'] = $pickResult;
  1614. $out[] = $g;
  1615. }
  1616. return $out;
  1617. }
  1618. /**
  1619. * 查询 purchase_order_detail 列表(订单页)
  1620. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  1621. * 有搜索词时:在当前 Tab 内做关键字匹配
  1622. *
  1623. * @param string $tab draft|submitted|done
  1624. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  1625. * @return array{rows: array, done_no_status: int}
  1626. */
  1627. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  1628. {
  1629. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  1630. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  1631. $userWhere = $this->mprocListWhereForLoginUser($user);
  1632. if ($userWhere !== []) {
  1633. $query->where($userWhere);
  1634. }
  1635. if (trim((string)$q) === '' && $tab === 'done' && $statusNameCol !== null) {
  1636. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  1637. }
  1638. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  1639. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  1640. try {
  1641. $rows = $query->limit(500)->select();
  1642. } catch (\Throwable $e) {
  1643. $rows = [];
  1644. }
  1645. if (!is_array($rows)) {
  1646. $rows = [];
  1647. }
  1648. $poBySid = [];
  1649. $sidList = [];
  1650. foreach ($rows as $r0) {
  1651. if (!is_array($r0)) {
  1652. continue;
  1653. }
  1654. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  1655. if ($this->mprocIsValidScydgyRowId($sid0)) {
  1656. $sidList[$sid0] = true;
  1657. }
  1658. }
  1659. if ($sidList !== []) {
  1660. try {
  1661. $poRows = Db::table('purchase_order')
  1662. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  1663. ->select();
  1664. if (is_array($poRows)) {
  1665. foreach ($poRows as $pr) {
  1666. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1667. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1668. $poBySid[$sidk] = $pr;
  1669. }
  1670. }
  1671. }
  1672. } catch (\Throwable $e) {
  1673. }
  1674. }
  1675. $ccydhForBid = [];
  1676. foreach ($poBySid as $pr) {
  1677. if (!is_array($pr)) {
  1678. continue;
  1679. }
  1680. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  1681. if ($c !== '') {
  1682. $ccydhForBid[$c] = true;
  1683. }
  1684. }
  1685. foreach ($rows as $r0) {
  1686. if (!is_array($r0)) {
  1687. continue;
  1688. }
  1689. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  1690. if ($c !== '') {
  1691. $ccydhForBid[$c] = true;
  1692. }
  1693. }
  1694. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  1695. foreach ($rows as &$row) {
  1696. if (!is_array($row)) {
  1697. continue;
  1698. }
  1699. // 废弃明细不在手机端展示
  1700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
  1701. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
  1702. $row = null;
  1703. continue;
  1704. }
  1705. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  1706. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1707. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  1708. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  1709. }
  1710. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  1711. $oldSn = trim((string)($row['status_name'] ?? ''));
  1712. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  1713. $row['status_name'] = $effectiveSn;
  1714. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  1715. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  1716. }
  1717. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  1718. $row['mproc_list_tab'] = $listTab;
  1719. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  1720. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  1721. if ($row['mproc_pick_result'] === '' && $listTab === 'done' && $row['mproc_deadline_reached']) {
  1722. $row['mproc_done_label'] = '已截止';
  1723. } elseif ($row['mproc_pick_result'] !== '') {
  1724. $row['mproc_done_label'] = $row['mproc_pick_result'];
  1725. } else {
  1726. $row['mproc_done_label'] = '';
  1727. }
  1728. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  1729. if (!isset($row['status_name']) || $row['status_name'] === null) {
  1730. $row['status_name'] = '';
  1731. } else {
  1732. $row['status_name'] = trim((string)$row['status_name']);
  1733. }
  1734. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  1735. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  1736. $am = $row['amount'] ?? null;
  1737. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  1738. $row['amount_display'] = '';
  1739. } else {
  1740. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  1741. }
  1742. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1743. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1744. $row['delivery_display'] = $m[1];
  1745. } elseif ($dv !== '') {
  1746. $row['delivery_display'] = $dv;
  1747. } else {
  1748. $row['delivery_display'] = '';
  1749. }
  1750. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1751. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1752. $this->mprocEnrichLeadDaysDisplay($row);
  1753. $this->mprocEnrichOrderDeadlineDisplay($row);
  1754. $row['mproc_fill_hint'] = '';
  1755. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1756. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  1757. }
  1758. unset($row);
  1759. $rows = array_values(array_filter($rows, function ($r) {
  1760. return is_array($r);
  1761. }));
  1762. // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
  1763. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  1764. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  1765. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  1766. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  1767. }));
  1768. $groups = $this->mprocGroupRowsByOrder($rows);
  1769. return [
  1770. 'rows' => $rows ?: [],
  1771. 'groups' => $groups ?: [],
  1772. 'done_no_status' => (int)($statusNameCol === null),
  1773. ];
  1774. }
  1775. /**
  1776. * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
  1777. *
  1778. * @param array<int, array<string, mixed>> $rows
  1779. * @return array<int, array<string, mixed>>
  1780. */
  1781. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  1782. {
  1783. $best = [];
  1784. $orderKeys = [];
  1785. foreach ($rows as $row) {
  1786. if (!is_array($row)) {
  1787. continue;
  1788. }
  1789. $cn = trim((string)($row['company_name'] ?? ''));
  1790. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1791. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  1792. if ($this->mprocIsValidScydgyRowId($sid)) {
  1793. $key = $cn . '|sid:' . $sid;
  1794. } else {
  1795. $key = $cn . '|eid:' . $eid;
  1796. }
  1797. if (!isset($best[$key])) {
  1798. $best[$key] = $row;
  1799. $orderKeys[] = $key;
  1800. continue;
  1801. }
  1802. $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
  1803. if ($eid > $prevEid) {
  1804. $best[$key] = $row;
  1805. }
  1806. }
  1807. $out = [];
  1808. foreach ($orderKeys as $key) {
  1809. if (isset($best[$key])) {
  1810. $out[] = $best[$key];
  1811. }
  1812. }
  1813. return $out;
  1814. }
  1815. /**
  1816. * status_name → 手机端左侧 Tab
  1817. */
  1818. protected function mprocStatusNameToListTab(string $statusName): string
  1819. {
  1820. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  1821. $sn = trim($statusName);
  1822. return isset($map[$sn]) ? $map[$sn] : '';
  1823. }
  1824. /**
  1825. * 短信/邮件 focus_eid 应落在的列表 Tab
  1826. */
  1827. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  1828. {
  1829. if ($focusEid <= 0) {
  1830. return '';
  1831. }
  1832. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1833. if ($idCol === null) {
  1834. return '';
  1835. }
  1836. try {
  1837. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  1838. $qw = $this->mprocListWhereForLoginUser($user);
  1839. if ($qw !== []) {
  1840. $qrow->where($qw);
  1841. }
  1842. $dr = $qrow->find();
  1843. } catch (\Throwable $e) {
  1844. $dr = null;
  1845. }
  1846. if (!is_array($dr) || $dr === []) {
  1847. return '';
  1848. }
  1849. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  1850. $po = null;
  1851. if ($this->mprocIsValidScydgyRowId($sid)) {
  1852. try {
  1853. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1854. } catch (\Throwable $e) {
  1855. $po = null;
  1856. }
  1857. }
  1858. return $this->mprocResolveListTabForRow(
  1859. $dr,
  1860. is_array($po) ? $po : null,
  1861. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  1862. );
  1863. }
  1864. /**
  1865. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  1866. *
  1867. * @param array<string, mixed> $bundle
  1868. * @param array<string, mixed> $user
  1869. * @return array<string, mixed>
  1870. */
  1871. protected function mprocEnsureFocusRowInList(
  1872. array $bundle,
  1873. int $focusEid,
  1874. array $user,
  1875. $statusNameCol,
  1876. string $tab = 'draft',
  1877. string $q = ''
  1878. ): array {
  1879. if ($focusEid <= 0) {
  1880. return $bundle;
  1881. }
  1882. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  1883. $foundIdx = -1;
  1884. foreach ($rows as $idx => $r) {
  1885. if (!is_array($r)) {
  1886. continue;
  1887. }
  1888. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  1889. $foundIdx = (int)$idx;
  1890. break;
  1891. }
  1892. }
  1893. if ($foundIdx > 0) {
  1894. $hit = $rows[$foundIdx];
  1895. array_splice($rows, $foundIdx, 1);
  1896. array_unshift($rows, $hit);
  1897. $bundle['rows'] = $rows;
  1898. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  1899. return $bundle;
  1900. }
  1901. if ($foundIdx === 0) {
  1902. return $bundle;
  1903. }
  1904. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  1905. if ($idCol === null) {
  1906. return $bundle;
  1907. }
  1908. try {
  1909. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  1910. $qw = $this->mprocListWhereForLoginUser($user);
  1911. if ($qw !== []) {
  1912. $qrow->where($qw);
  1913. }
  1914. $dr = $qrow->find();
  1915. } catch (\Throwable $e) {
  1916. $dr = null;
  1917. }
  1918. if (!is_array($dr) || $dr === []) {
  1919. return $bundle;
  1920. }
  1921. $row = $dr;
  1922. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  1923. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1924. $poRow = null;
  1925. if ($this->mprocIsValidScydgyRowId($sid)) {
  1926. try {
  1927. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1928. } catch (\Throwable $e) {
  1929. $poRow = null;
  1930. }
  1931. if (is_array($poRow)) {
  1932. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  1933. }
  1934. }
  1935. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  1936. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  1937. if ($rowTab !== '' && $rowTab !== $tab) {
  1938. return $bundle;
  1939. }
  1940. $row['status_name'] = $effectiveSn;
  1941. $listTab = $rowTab;
  1942. $row['mproc_list_tab'] = $listTab;
  1943. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  1944. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  1945. if ($row['mproc_pick_result'] === '' && $listTab === 'done' && $row['mproc_deadline_reached']) {
  1946. $row['mproc_done_label'] = '已截止';
  1947. } elseif ($row['mproc_pick_result'] !== '') {
  1948. $row['mproc_done_label'] = $row['mproc_pick_result'];
  1949. } else {
  1950. $row['mproc_done_label'] = '';
  1951. }
  1952. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  1953. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  1954. $am = $row['amount'] ?? null;
  1955. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  1956. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1957. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1958. $row['delivery_display'] = $m[1];
  1959. } elseif ($dv !== '') {
  1960. $row['delivery_display'] = $dv;
  1961. } else {
  1962. $row['delivery_display'] = '';
  1963. }
  1964. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1965. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1966. $this->mprocEnrichLeadDaysDisplay($row);
  1967. $this->mprocEnrichOrderDeadlineDisplay($row);
  1968. $row['mproc_fill_hint'] = '';
  1969. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1970. array_unshift($rows, $row);
  1971. $bundle['rows'] = $rows;
  1972. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  1973. return $bundle;
  1974. }
  1975. /**
  1976. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  1977. *
  1978. * @param array<string, mixed> $row
  1979. */
  1980. protected function mprocResolveDisplayThisQuantity(array $row): string
  1981. {
  1982. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  1983. if ($qty !== '') {
  1984. return $qty;
  1985. }
  1986. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  1987. if ($gzl === null || $gzl === '') {
  1988. return '';
  1989. }
  1990. return is_scalar($gzl) ? trim((string)$gzl) : '';
  1991. }
  1992. /**
  1993. * 明细是否已填写单价或交货日期
  1994. *
  1995. * @param array<string, mixed> $row
  1996. */
  1997. protected function mprocDetailQuoteSubmitted(array $row): bool
  1998. {
  1999. $am = $row['amount'] ?? null;
  2000. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2001. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2002. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2003. return $amountFilled || $deliveryFilled;
  2004. }
  2005. /**
  2006. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2007. *
  2008. * @param array<string, mixed> $row
  2009. * @param array<string, mixed>|null $po
  2010. */
  2011. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2012. {
  2013. $sn = trim((string)($row['status_name'] ?? ''));
  2014. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2015. return $sn;
  2016. }
  2017. if (!is_array($po)) {
  2018. if ($sn !== '') {
  2019. return $sn;
  2020. }
  2021. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2022. }
  2023. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2024. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2025. if ($sn !== '') {
  2026. return $sn;
  2027. }
  2028. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2029. }
  2030. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2031. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2032. return '已完成';
  2033. }
  2034. if ($sn === '已提交') {
  2035. return '未通过';
  2036. }
  2037. return $sn !== '' ? $sn : '未提交';
  2038. }
  2039. /**
  2040. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2041. */
  2042. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2043. {
  2044. if ($detailId <= 0 || $statusNameCol === '') {
  2045. return;
  2046. }
  2047. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2048. if ($idCol === null || $idCol === '') {
  2049. return;
  2050. }
  2051. try {
  2052. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2053. } catch (\Throwable $e) {
  2054. }
  2055. }
  2056. /**
  2057. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2058. *
  2059. * @param array<string, mixed> $user
  2060. */
  2061. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2062. {
  2063. $userWhere = $this->mprocListWhereForLoginUser($user);
  2064. try {
  2065. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2066. if ($userWhere !== []) {
  2067. $query->where($userWhere);
  2068. }
  2069. $candidates = $query->limit(200)->select();
  2070. } catch (\Throwable $e) {
  2071. return;
  2072. }
  2073. if (!is_array($candidates) || $candidates === []) {
  2074. return;
  2075. }
  2076. $sidList = [];
  2077. foreach ($candidates as $cr) {
  2078. if (!is_array($cr)) {
  2079. continue;
  2080. }
  2081. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2082. if ($this->mprocIsValidScydgyRowId($sid)) {
  2083. $sidList[$sid] = true;
  2084. }
  2085. }
  2086. if ($sidList === []) {
  2087. return;
  2088. }
  2089. $poBySid = [];
  2090. try {
  2091. $poRows = Db::table('purchase_order')
  2092. ->where('scydgy_id', 'in', array_keys($sidList))
  2093. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2094. ->select();
  2095. if (is_array($poRows)) {
  2096. foreach ($poRows as $pr) {
  2097. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2098. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2099. $poBySid[$sidk] = $pr;
  2100. }
  2101. }
  2102. }
  2103. } catch (\Throwable $e) {
  2104. return;
  2105. }
  2106. if ($poBySid === []) {
  2107. return;
  2108. }
  2109. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2110. if ($idCol === null || $idCol === '') {
  2111. return;
  2112. }
  2113. foreach ($candidates as $cr) {
  2114. if (!is_array($cr)) {
  2115. continue;
  2116. }
  2117. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2118. if (!isset($poBySid[$sid])) {
  2119. continue;
  2120. }
  2121. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2122. if ($detailId <= 0) {
  2123. continue;
  2124. }
  2125. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2126. if ($targetSn === '已提交') {
  2127. continue;
  2128. }
  2129. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2130. }
  2131. }
  2132. /**
  2133. * 协助明细首页(需登录)
  2134. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2135. */
  2136. public function index()
  2137. {
  2138. $user = $this->mprocGetUser();
  2139. if (!$user) {
  2140. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2141. if ($pendingFocus > 0) {
  2142. $this->mprocRememberFocusEid($pendingFocus);
  2143. }
  2144. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2145. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2146. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2147. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2148. }
  2149. if ($safe !== '') {
  2150. Session::set('mproc_intended_url', $safe);
  2151. }
  2152. $this->redirect($this->mprocBuildLoginUrl($safe));
  2153. return;
  2154. }
  2155. $user = $this->mprocSyncSessionCustomerUser($user);
  2156. $tabParamRaw = $this->request->get('tab', null);
  2157. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2158. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2159. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2160. // 旧地址 ?tab=me 表示「我的」
  2161. if ($tabParam === 'me') {
  2162. $mainTab = 'me';
  2163. }
  2164. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2165. $mainTab = 'orders';
  2166. }
  2167. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  2168. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  2169. $tab = 'draft';
  2170. }
  2171. $q = trim((string)$this->request->get('q', ''));
  2172. $mprocFocusEid = 0;
  2173. $focusEid = $this->mprocReadFocusEidFromRequest();
  2174. if ($focusEid > 0 && $mainTab === 'orders') {
  2175. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2176. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2177. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2178. Session::delete('mproc_focus_eid');
  2179. $focusEid = 0;
  2180. } else {
  2181. $mprocFocusEid = $focusEid;
  2182. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2183. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2184. if (!$focusFromUrl) {
  2185. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2186. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2187. }
  2188. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2189. if ($resolvedTab !== '') {
  2190. $tab = $resolvedTab;
  2191. }
  2192. }
  2193. }
  2194. }
  2195. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2196. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2197. $profile = $this->mprocProfileForUser($user);
  2198. $this->view->assign('mprocMainTab', $mainTab);
  2199. $this->view->assign('mprocTab', $tab);
  2200. $this->view->assign('mprocSearchQ', $q);
  2201. $this->view->assign('mprocProfile', $profile);
  2202. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2203. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2204. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2205. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2206. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2207. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2208. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2209. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2210. if ($mainTab === 'me') {
  2211. $this->view->assign('rows', []);
  2212. return $this->view->fetch();
  2213. }
  2214. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2215. if ($mprocFocusEid > 0) {
  2216. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2217. }
  2218. $this->view->assign('rows', $bundle['rows']);
  2219. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2220. return $this->view->fetch();
  2221. }
  2222. /**
  2223. * 协助明细列表 JSON(需登录)
  2224. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2225. */
  2226. public function mprocList()
  2227. {
  2228. $user = $this->mprocGetUser();
  2229. if (!$user) {
  2230. $this->error('请先登录', url('index/index/login'));
  2231. }
  2232. $user = $this->mprocSyncSessionCustomerUser($user);
  2233. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  2234. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  2235. if ($tabParam === 'me') {
  2236. $mainTab = 'me';
  2237. }
  2238. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2239. $mainTab = 'orders';
  2240. }
  2241. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  2242. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  2243. $tab = 'draft';
  2244. }
  2245. $q = trim((string)$this->request->request('q', ''));
  2246. if ($mainTab === 'me') {
  2247. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  2248. $this->success('ok', '', [
  2249. 'main_tab' => 'me',
  2250. 'tab' => $tab,
  2251. 'rows' => [],
  2252. 'profile' => $this->mprocProfileForUser($user),
  2253. 'done_no_status' => 0,
  2254. ]);
  2255. }
  2256. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2257. if ((int)$this->request->request('clear_focus', 0) === 1) {
  2258. Session::delete('mproc_focus_eid');
  2259. $focusEid = 0;
  2260. $focusTab = '';
  2261. } else {
  2262. $focusEid = $this->mprocReadFocusEidFromRequest();
  2263. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  2264. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  2265. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  2266. Session::delete('mproc_focus_eid');
  2267. $focusEid = 0;
  2268. $focusTab = '';
  2269. }
  2270. }
  2271. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2272. if ($focusEid > 0) {
  2273. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  2274. }
  2275. $this->success('ok', '', array_merge([
  2276. 'main_tab' => 'orders',
  2277. 'tab' => $tab,
  2278. 'focus_tab' => $focusTab,
  2279. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  2280. 'focus_eid' => $focusEid,
  2281. ], $bundle));
  2282. }
  2283. /**
  2284. * 登录页(手机号验证码 / 账号密码)
  2285. */
  2286. public function login()
  2287. {
  2288. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  2289. if ($this->mprocGetUser()) {
  2290. $this->redirect($this->mprocBuildAfterLoginIndexUrl($redirect));
  2291. }
  2292. if ($redirect !== '') {
  2293. Session::set('mproc_intended_url', $redirect);
  2294. }
  2295. $this->view->assign('mprocLoginRedirect', $redirect);
  2296. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  2297. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  2298. return $this->view->fetch();
  2299. }
  2300. /**
  2301. * 图形验证码(手机号登录用)
  2302. */
  2303. public function captcha($id = '')
  2304. {
  2305. $captcha = new Captcha((array)Config::get('captcha'));
  2306. return $captcha->entry($id);
  2307. }
  2308. /**
  2309. * 发送登录验证码(POST:phone、captcha)
  2310. */
  2311. public function sendSms()
  2312. {
  2313. if (!$this->request->isPost()) {
  2314. $this->error('请使用 POST');
  2315. }
  2316. $phone = trim((string)$this->request->post('phone', ''));
  2317. $captcha = trim((string)$this->request->post('captcha', ''));
  2318. if (!preg_match('/^1\d{10}$/', $phone)) {
  2319. $this->error('请输入正确的11位手机号');
  2320. }
  2321. if ($captcha === '') {
  2322. $this->error('请输入图形验证码');
  2323. }
  2324. if (!$this->mprocFindCustomerUserByMobile($phone)) {
  2325. $this->error('该手机号未开通或已禁用,请联系管理员');
  2326. }
  2327. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  2328. if (Cache::get('mproc_sms_wait_' . $phone)) {
  2329. $this->error('发送过于频繁,请稍后再试');
  2330. }
  2331. if (!Validate::is($captcha, 'captcha')) {
  2332. $this->error('图形验证码不正确');
  2333. }
  2334. $code = (string)random_int(100000, 999999);
  2335. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  2336. $ttl = max(60, min(600, $ttl));
  2337. Cache::set('mproc_code_' . $phone, $code, $ttl);
  2338. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  2339. try {
  2340. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  2341. if ($tpl === '') {
  2342. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  2343. }
  2344. $content = str_replace('{code}', $code, $tpl);
  2345. $this->mprocSmsSend($phone, $content);
  2346. } catch (\Exception $e) {
  2347. Cache::rm('mproc_code_' . $phone);
  2348. Cache::rm('mproc_sms_wait_' . $phone);
  2349. $this->error($e->getMessage());
  2350. }
  2351. $this->success('验证码已发送');
  2352. }
  2353. /**
  2354. * 验证码登录(POST:phone、code)
  2355. */
  2356. public function doLogin()
  2357. {
  2358. if (!$this->request->isPost()) {
  2359. $this->error('请使用 POST');
  2360. }
  2361. $phone = trim((string)$this->request->post('phone', ''));
  2362. $code = trim((string)$this->request->post('code', ''));
  2363. if (!preg_match('/^1\d{10}$/', $phone)) {
  2364. $this->error('手机号格式不正确');
  2365. }
  2366. if (!preg_match('/^\d{6}$/', $code)) {
  2367. $this->error('请输入6位验证码');
  2368. }
  2369. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2370. $mock = Config::get('mproc.mock_sms_code');
  2371. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2372. Cache::rm('mproc_code_' . $phone);
  2373. } else {
  2374. $cached = Cache::get('mproc_code_' . $phone);
  2375. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2376. $this->error('验证码错误或已过期');
  2377. }
  2378. Cache::rm('mproc_code_' . $phone);
  2379. }
  2380. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2381. if (!$cu) {
  2382. $this->error('该手机号未开通或已禁用,请联系管理员');
  2383. }
  2384. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2385. }
  2386. /**
  2387. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2388. */
  2389. public function mprocRestore()
  2390. {
  2391. if (!$this->request->isPost()) {
  2392. $this->error('请使用 POST');
  2393. }
  2394. $token = $this->mprocReadTokenFromRequest();
  2395. $user = null;
  2396. if ($token !== '') {
  2397. $user = $this->mprocLoadUserByToken($token);
  2398. }
  2399. if (!$user) {
  2400. $user = $this->mprocUserFromRememberCookie();
  2401. if ($user) {
  2402. $token = $this->mprocPackSignedAuthToken($user);
  2403. }
  2404. }
  2405. if (!$user) {
  2406. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2407. }
  2408. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2409. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2410. $jump = $this->mprocBuildAfterLoginIndexUrl($redirect);
  2411. $this->success('ok', $jump, [
  2412. 'mproc_token' => $token,
  2413. 'keep_hours' => $this->mprocKeepHours(),
  2414. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2415. ]);
  2416. }
  2417. /**
  2418. * 账号密码登录(POST:username、password)
  2419. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2420. */
  2421. public function doLoginPwd()
  2422. {
  2423. if (!$this->request->isPost()) {
  2424. $this->error('请使用 POST');
  2425. }
  2426. $username = trim((string)$this->request->post('username', ''));
  2427. $password = (string)$this->request->post('password', '');
  2428. if ($username === '' || $password === '') {
  2429. $this->error('请输入账号和密码');
  2430. }
  2431. $cu = $this->mprocFindCustomerUserByUsername($username);
  2432. if ($cu) {
  2433. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2434. $this->error('账号或密码错误');
  2435. }
  2436. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2437. }
  2438. // 管理员:表 admin
  2439. $row = null;
  2440. try {
  2441. $row = Db::name('admin')
  2442. ->field('id,username,password,salt,status,loginfailure,updatetime')
  2443. ->where('username', $username)
  2444. ->find();
  2445. } catch (\Throwable $e) {
  2446. $row = null;
  2447. }
  2448. if (!$row || !is_array($row)) {
  2449. $this->error('账号或密码错误');
  2450. }
  2451. $id = (int)($row['id'] ?? 0);
  2452. if (($row['status'] ?? '') == 'hidden') {
  2453. $this->error('该账号已禁用');
  2454. }
  2455. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  2456. $this->error('登录失败次数过多,请24小时后再试');
  2457. }
  2458. $salt = (string)($row['salt'] ?? '');
  2459. $hashStored = (string)($row['password'] ?? '');
  2460. $hashInput = md5(md5($password) . $salt);
  2461. if ($hashStored === '' || $hashInput !== $hashStored) {
  2462. if ($id > 0) {
  2463. try {
  2464. Db::name('admin')->where('id', $id)->update([
  2465. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  2466. 'updatetime' => time(),
  2467. ]);
  2468. } catch (\Throwable $e) {
  2469. }
  2470. }
  2471. $this->error('账号或密码错误');
  2472. }
  2473. if ($id > 0) {
  2474. try {
  2475. Db::name('admin')->where('id', $id)->update([
  2476. 'loginfailure' => 0,
  2477. 'updatetime' => time(),
  2478. ]);
  2479. } catch (\Throwable $e) {
  2480. }
  2481. }
  2482. $this->mprocFinishLogin([
  2483. 'phone' => trim((string)($row['mobile'] ?? '')),
  2484. 'company_name' => '',
  2485. 'username' => $username,
  2486. 'customer_user_id' => 0,
  2487. 'login_type' => 'pwd',
  2488. 'is_admin' => 1,
  2489. ]);
  2490. }
  2491. /**
  2492. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  2493. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  2494. */
  2495. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  2496. {
  2497. if (!empty($user['is_admin'])) {
  2498. return false;
  2499. }
  2500. $sn = trim((string)($row['status_name'] ?? ''));
  2501. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2502. return false;
  2503. }
  2504. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  2505. return false;
  2506. }
  2507. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  2508. return false;
  2509. }
  2510. $uCo = trim((string)($user['company_name'] ?? ''));
  2511. if ($uCo === '') {
  2512. $uPhone = trim((string)($user['phone'] ?? ''));
  2513. if ($uPhone !== '') {
  2514. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  2515. }
  2516. }
  2517. $rCo = trim((string)($row['company_name'] ?? ''));
  2518. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  2519. return true;
  2520. }
  2521. $uPhone = trim((string)($user['phone'] ?? ''));
  2522. $rPhone = trim((string)($row['phone'] ?? ''));
  2523. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  2524. }
  2525. /**
  2526. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  2527. *
  2528. * @param array<string, mixed> $detailRow
  2529. */
  2530. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  2531. {
  2532. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  2533. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  2534. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  2535. try {
  2536. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2537. } catch (\Throwable $e) {
  2538. $po = null;
  2539. }
  2540. if (is_array($po)) {
  2541. $pl = array_change_key_case($po, CASE_LOWER);
  2542. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  2543. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  2544. $raw = trim((string)$pl[$ck]);
  2545. break;
  2546. }
  2547. }
  2548. if ($raw === '') {
  2549. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  2550. }
  2551. }
  2552. }
  2553. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  2554. return null;
  2555. }
  2556. return (float)$raw;
  2557. }
  2558. protected function mprocFormatCeilingPriceDisplay(float $n): string
  2559. {
  2560. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  2561. return $s === '' ? '0' : $s;
  2562. }
  2563. /**
  2564. * 确保 purchase_order_detail.lead_days 字段存在
  2565. */
  2566. protected function mprocEnsureLeadDaysColumn(): void
  2567. {
  2568. static $done = false;
  2569. if ($done) {
  2570. return;
  2571. }
  2572. $done = true;
  2573. try {
  2574. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  2575. if (empty($cols)) {
  2576. Db::execute(
  2577. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  2578. );
  2579. }
  2580. } catch (\Throwable $e) {
  2581. // 忽略:保存时再按列是否存在处理
  2582. }
  2583. }
  2584. /**
  2585. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  2586. */
  2587. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  2588. {
  2589. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  2590. return null;
  2591. }
  2592. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2593. $t2 = strtotime($m[1] . ' 00:00:00');
  2594. if ($t1 === false || $t2 === false) {
  2595. return null;
  2596. }
  2597. return (int)round(($t2 - $t1) / 86400);
  2598. }
  2599. protected function mprocAddDaysToToday(int $days): string
  2600. {
  2601. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  2602. if ($base === false) {
  2603. $base = time();
  2604. }
  2605. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  2606. }
  2607. /**
  2608. * @param array<string, mixed> $row
  2609. */
  2610. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  2611. {
  2612. $days = null;
  2613. $raw = $row['lead_days'] ?? null;
  2614. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  2615. $days = max(0, (int)$raw);
  2616. } else {
  2617. $dd = trim((string)($row['delivery_display'] ?? ''));
  2618. if ($dd === '') {
  2619. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2620. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2621. $dd = $m[1];
  2622. }
  2623. }
  2624. if ($dd !== '') {
  2625. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  2626. if ($calc !== null) {
  2627. $days = max(0, $calc);
  2628. }
  2629. }
  2630. }
  2631. if ($days !== null) {
  2632. $row['lead_days'] = $days;
  2633. $row['lead_days_display'] = (string)$days;
  2634. $row['lead_days_missing'] = 0;
  2635. } else {
  2636. $row['lead_days'] = '';
  2637. $row['lead_days_display'] = '';
  2638. $row['lead_days_missing'] = 1;
  2639. }
  2640. }
  2641. /**
  2642. * 保存单条协助明细的金额、交期、工期(内部)
  2643. *
  2644. * @param array<string, mixed> $user
  2645. * @param int $id
  2646. * @param string $amountRaw
  2647. * @param string $deliveryRaw
  2648. * @param string|int|null $leadDaysRaw
  2649. * @return string 工序名(用于批量错误提示)
  2650. */
  2651. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  2652. {
  2653. if ($id <= 0) {
  2654. throw new \InvalidArgumentException('参数错误');
  2655. }
  2656. $row = null;
  2657. try {
  2658. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  2659. if (!$row) {
  2660. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  2661. }
  2662. } catch (\Throwable $e) {
  2663. $row = null;
  2664. }
  2665. if (!$row || !is_array($row)) {
  2666. throw new \InvalidArgumentException('记录不存在');
  2667. }
  2668. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  2669. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2670. $po = null;
  2671. if ($this->mprocIsValidScydgyRowId($sid)) {
  2672. try {
  2673. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2674. } catch (\Throwable $e) {
  2675. $po = null;
  2676. }
  2677. if (is_array($po)) {
  2678. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  2679. if ($gymc === '') {
  2680. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2681. }
  2682. }
  2683. }
  2684. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  2685. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  2686. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  2687. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  2688. }
  2689. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  2690. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  2691. if (!empty($user['is_admin'])) {
  2692. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  2693. }
  2694. // 截止后 / 已开标 canEdit=false,统一给明确文案
  2695. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  2696. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  2697. }
  2698. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  2699. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  2700. }
  2701. throw new \InvalidArgumentException($label . '无权修改');
  2702. }
  2703. $this->mprocEnsureLeadDaysColumn();
  2704. $amountRaw = trim($amountRaw);
  2705. $deliveryRaw = trim($deliveryRaw);
  2706. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  2707. $hasAmt = $amountRaw !== '';
  2708. $hasLead = $leadRaw !== '';
  2709. $hasDel = $deliveryRaw !== '';
  2710. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  2711. if ($filledCount === 0) {
  2712. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  2713. }
  2714. if ($filledCount < 3) {
  2715. if (!$hasAmt) {
  2716. throw new \InvalidArgumentException($label . '请填写单价');
  2717. }
  2718. if (!$hasLead) {
  2719. throw new \InvalidArgumentException($label . '请填写工期');
  2720. }
  2721. throw new \InvalidArgumentException($label . '请填写交期');
  2722. }
  2723. $leadDays = null;
  2724. if ($leadRaw !== '') {
  2725. if (!preg_match('/^\d+$/', $leadRaw)) {
  2726. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  2727. }
  2728. $leadDays = (int)$leadRaw;
  2729. }
  2730. $data = [];
  2731. if ($amountRaw === '') {
  2732. $data['amount'] = null;
  2733. } else {
  2734. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  2735. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  2736. }
  2737. if ((float)$amountRaw <= 0) {
  2738. throw new \InvalidArgumentException($label . '单价必须大于0');
  2739. }
  2740. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  2741. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  2742. throw new \InvalidArgumentException(
  2743. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  2744. );
  2745. }
  2746. $data['amount'] = $amountRaw;
  2747. }
  2748. if ($deliveryRaw === '') {
  2749. $data['delivery'] = null;
  2750. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  2751. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2752. $timePart = date('H:i:s');
  2753. if ($existingDel !== '') {
  2754. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  2755. if ($tsEx !== false) {
  2756. $hms = date('H:i:s', $tsEx);
  2757. if ($hms !== '00:00:00') {
  2758. $timePart = $hms;
  2759. }
  2760. }
  2761. }
  2762. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  2763. } else {
  2764. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  2765. $ts = strtotime($deliveryRaw);
  2766. if ($ts === false) {
  2767. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  2768. }
  2769. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  2770. }
  2771. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  2772. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  2773. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  2774. }
  2775. if ($leadDays === null && !empty($data['delivery'])) {
  2776. $ymd = substr((string)$data['delivery'], 0, 10);
  2777. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  2778. if ($calc !== null) {
  2779. $leadDays = max(0, $calc);
  2780. }
  2781. }
  2782. $data['lead_days'] = $leadDays;
  2783. if (!empty($data['delivery'])) {
  2784. $deliveryYmd = substr((string)$data['delivery'], 0, 10);
  2785. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryYmd) && $deliveryYmd < date('Y-m-d')) {
  2786. throw new \InvalidArgumentException($label . '交货日期不能早于今天');
  2787. }
  2788. $orderDeliveryDeadline = $this->mprocResolveDeliveryDeadlineYmdForDetailRow($row);
  2789. if ($orderDeliveryDeadline !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryYmd)
  2790. && $deliveryYmd > $orderDeliveryDeadline) {
  2791. throw new \InvalidArgumentException($label . '交货日期不能超过交货截止日期 ' . $orderDeliveryDeadline);
  2792. }
  2793. }
  2794. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  2795. if ($dcCol !== null && array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  2796. $data[$dcCol] = date('Y-m-d H:i:s');
  2797. }
  2798. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2799. if ($upCol !== null) {
  2800. $data[$upCol] = date('Y-m-d H:i:s');
  2801. }
  2802. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2803. if ($statusNameCol !== null) {
  2804. $curSn = '';
  2805. foreach ($row as $k => $v) {
  2806. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  2807. $curSn = trim((string)$v);
  2808. break;
  2809. }
  2810. }
  2811. if ($curSn !== '已完成') {
  2812. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  2813. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  2814. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  2815. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  2816. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2817. }
  2818. }
  2819. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  2820. $pkVal = (int)($row[$pkField] ?? $id);
  2821. try {
  2822. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  2823. } catch (\Throwable $e) {
  2824. $msg = $e->getMessage();
  2825. if (stripos($msg, 'Unknown column') !== false) {
  2826. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  2827. }
  2828. throw new \RuntimeException('保存失败:' . $msg);
  2829. }
  2830. if ($aff === false) {
  2831. throw new \RuntimeException($label . '保存失败');
  2832. }
  2833. return $gymc;
  2834. }
  2835. /**
  2836. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  2837. *
  2838. * @param array<string, mixed> $user
  2839. * @param int[] $detailIds 本次保存涉及的明细 ID
  2840. * @param string $remarkRaw
  2841. */
  2842. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  2843. {
  2844. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  2845. if ($remarkCol === null) {
  2846. return;
  2847. }
  2848. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2849. if ($detailIds === []) {
  2850. return;
  2851. }
  2852. $anchorId = $detailIds[0];
  2853. $row = null;
  2854. try {
  2855. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  2856. if (!$row) {
  2857. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  2858. }
  2859. } catch (\Throwable $e) {
  2860. $row = null;
  2861. }
  2862. if (!$row || !is_array($row)) {
  2863. throw new \InvalidArgumentException('记录不存在');
  2864. }
  2865. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2866. $po = null;
  2867. if ($this->mprocIsValidScydgyRowId($sid)) {
  2868. try {
  2869. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2870. } catch (\Throwable $e) {
  2871. $po = null;
  2872. }
  2873. if (is_array($po)) {
  2874. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  2875. }
  2876. }
  2877. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  2878. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  2879. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  2880. }
  2881. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  2882. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  2883. if (!empty($user['is_admin'])) {
  2884. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  2885. }
  2886. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  2887. throw new \InvalidArgumentException('已开标验证,不可再提交');
  2888. }
  2889. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  2890. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  2891. }
  2892. throw new \InvalidArgumentException('无权修改备注');
  2893. }
  2894. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  2895. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  2896. if ($ccydhCol === null || $companyCol === null) {
  2897. return;
  2898. }
  2899. $ccydh = '';
  2900. $company = '';
  2901. foreach ($row as $k => $v) {
  2902. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  2903. $ccydh = trim((string)$v);
  2904. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  2905. $company = trim((string)$v);
  2906. }
  2907. }
  2908. if ($ccydh === '' || $company === '') {
  2909. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  2910. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  2911. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2912. if ($upCol !== null) {
  2913. $data[$upCol] = date('Y-m-d H:i:s');
  2914. }
  2915. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  2916. return;
  2917. }
  2918. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  2919. $data = [$remarkCol => $remarkVal];
  2920. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2921. if ($upCol !== null) {
  2922. $data[$upCol] = date('Y-m-d H:i:s');
  2923. }
  2924. $query = Db::table('purchase_order_detail')
  2925. ->where($ccydhCol, $ccydh)
  2926. ->where($companyCol, $company);
  2927. $userWhere = $this->mprocListWhereForLoginUser($user);
  2928. if ($userWhere !== []) {
  2929. $query->where($userWhere);
  2930. }
  2931. try {
  2932. $query->update($data);
  2933. } catch (\Throwable $e) {
  2934. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  2935. }
  2936. }
  2937. /**
  2938. * 保存协助明细金额、交期、工期
  2939. * 单条:POST id、amount、delivery、lead_days
  2940. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  2941. */
  2942. public function mprocSave()
  2943. {
  2944. if (!$this->request->isPost()) {
  2945. $this->error('请使用 POST');
  2946. }
  2947. $user = $this->mprocGetUser();
  2948. if (!$user) {
  2949. $this->error('请先登录', url('index/index/login'));
  2950. }
  2951. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  2952. $itemsRaw = $this->request->post('items', '', null);
  2953. if ($itemsRaw === '' || $itemsRaw === null) {
  2954. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  2955. }
  2956. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  2957. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  2958. }
  2959. $items = [];
  2960. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  2961. $decoded = json_decode($itemsRaw, true);
  2962. if (!is_array($decoded)) {
  2963. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  2964. }
  2965. if (is_array($decoded)) {
  2966. $items = $decoded;
  2967. }
  2968. } elseif (is_array($itemsRaw)) {
  2969. $items = $itemsRaw;
  2970. }
  2971. if ($items === []) {
  2972. $id = (int)$this->request->post('id', 0, null);
  2973. if ($id <= 0) {
  2974. $this->error('保存失败,请关闭弹窗后重试');
  2975. }
  2976. $items = [[
  2977. 'id' => $id,
  2978. 'amount' => (string)$this->request->post('amount', '', null),
  2979. 'delivery' => (string)$this->request->post('delivery', '', null),
  2980. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  2981. ]];
  2982. }
  2983. $saved = 0;
  2984. $savedIds = [];
  2985. $remarkRaw = $this->request->post('remark', '', null);
  2986. if ($remarkRaw === '' || $remarkRaw === null) {
  2987. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  2988. }
  2989. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  2990. Db::startTrans();
  2991. try {
  2992. foreach ($items as $it) {
  2993. if (!is_array($it)) {
  2994. continue;
  2995. }
  2996. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  2997. if ($id <= 0) {
  2998. continue;
  2999. }
  3000. $delivery = (string)($it['delivery'] ?? '');
  3001. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3002. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3003. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3004. }
  3005. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3006. $amount = trim((string)($it['amount'] ?? ''));
  3007. $leadDays = trim($leadDays);
  3008. $delivery = trim($delivery);
  3009. // 全空工序跳过:多工序时允许只保存已填全的
  3010. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3011. continue;
  3012. }
  3013. $this->mprocSaveDetailQuote(
  3014. $user,
  3015. $id,
  3016. $amount,
  3017. $delivery,
  3018. $leadDays
  3019. );
  3020. $saved++;
  3021. $savedIds[] = $id;
  3022. }
  3023. if ($saved < 1) {
  3024. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3025. }
  3026. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3027. Db::commit();
  3028. } catch (\InvalidArgumentException $e) {
  3029. Db::rollback();
  3030. $this->error($e->getMessage());
  3031. } catch (\Throwable $e) {
  3032. Db::rollback();
  3033. $this->error($e->getMessage());
  3034. }
  3035. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3036. }
  3037. /**
  3038. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  3039. */
  3040. public function mprocChangePwd()
  3041. {
  3042. if (!$this->request->isPost()) {
  3043. $this->error('请使用 POST');
  3044. }
  3045. $user = $this->mprocGetUser();
  3046. if (!$user) {
  3047. $this->error('请先登录', url('index/index/login'));
  3048. }
  3049. $user = $this->mprocSyncSessionCustomerUser($user);
  3050. if (!empty($user['is_admin'])) {
  3051. $this->error('当前账号不支持修改密码');
  3052. }
  3053. $cu = $this->mprocResolveCustomerUserForSession($user);
  3054. if (!$cu) {
  3055. $this->error('账号不存在或已禁用');
  3056. }
  3057. $oldPwd = (string)$this->request->post('old_password', '');
  3058. $newPwd = (string)$this->request->post('new_password', '');
  3059. $renewPwd = (string)$this->request->post('renew_password', '');
  3060. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3061. $this->error('请填写完整');
  3062. }
  3063. if (strlen($newPwd) < 4) {
  3064. $this->error('新密码至少4位');
  3065. }
  3066. if ($newPwd !== $renewPwd) {
  3067. $this->error('两次输入的新密码不一致');
  3068. }
  3069. if ($oldPwd === $newPwd) {
  3070. $this->error('新密码不能与旧密码相同');
  3071. }
  3072. $cuId = (int)($cu['id'] ?? 0);
  3073. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3074. $this->error('原密码不正确');
  3075. }
  3076. $data = [
  3077. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3078. 'updatetime' => date('Y-m-d H:i:s'),
  3079. ];
  3080. try {
  3081. Db::table('customer')->where('id', $cuId)->update($data);
  3082. } catch (\Throwable $e) {
  3083. $this->error('修改失败:' . $e->getMessage());
  3084. }
  3085. $this->success('密码已修改');
  3086. }
  3087. /**
  3088. * 退出登录
  3089. */
  3090. public function logout()
  3091. {
  3092. $token = Session::get('mproc_token');
  3093. if ($token === null || $token === '') {
  3094. $token = Cookie::get('mproc_token');
  3095. }
  3096. if ($token) {
  3097. $this->mprocClearLogin(preg_replace('/[^a-f0-9]/i', '', (string)$token));
  3098. }
  3099. $this->redirect(url('index/index/login'));
  3100. }
  3101. /**
  3102. * 短信宝(与后台协助审核一致,便于复用账号)
  3103. *
  3104. * @throws \Exception
  3105. */
  3106. protected function mprocSmsSend($phone, $content)
  3107. {
  3108. $statusStr = [
  3109. '0' => '短信发送成功',
  3110. '-1' => '参数不全',
  3111. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3112. '30' => '密码错误',
  3113. '40' => '账号不存在',
  3114. '41' => '余额不足',
  3115. '42' => '帐户已过期',
  3116. '43' => 'IP地址限制',
  3117. '50' => '内容含有敏感词',
  3118. ];
  3119. $smsapi = 'http://api.smsbao.com/';
  3120. $user = trim((string)Config::get('mproc.smsbao_user'));
  3121. if ($user === '') {
  3122. $user = 'zhuwei123';
  3123. }
  3124. $passPlain = Config::get('mproc.smsbao_pass');
  3125. $pass = ($passPlain !== null && $passPlain !== '')
  3126. ? md5((string)$passPlain)
  3127. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3128. $phone = trim((string)$phone);
  3129. $content = trim((string)$content);
  3130. if ($phone === '' || $content === '') {
  3131. throw new \Exception('短信发送失败:参数不全');
  3132. }
  3133. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3134. $result = @file_get_contents($sendurl);
  3135. if ($result === false) {
  3136. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3137. throw new \Exception('短信发送失败:网络异常');
  3138. }
  3139. $result = trim((string)$result);
  3140. if ($result !== '0') {
  3141. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3142. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3143. throw new \Exception('短信发送失败:' . $msg);
  3144. }
  3145. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3146. }
  3147. }