Index.php 116 KB

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