Index.php 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563
  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 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
  585. *
  586. * @return array|callable 可直接 $query->where(...);空数组表示不加条件
  587. */
  588. protected function mprocListWhereForLoginUser(array $user)
  589. {
  590. if (!empty($user['is_admin'])) {
  591. return [];
  592. }
  593. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  594. $pCol = $this->mprocResolveProcuremenColumn(['phone']);
  595. if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
  596. return ['id' => 0];
  597. }
  598. $cn = trim((string)($user['company_name'] ?? ''));
  599. $phone = trim((string)($user['phone'] ?? ''));
  600. if ($cn === '' && $phone !== '') {
  601. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  602. }
  603. if ($cn === '' && $phone === '') {
  604. return ['id' => 0];
  605. }
  606. return function ($q) use ($cCol, $pCol, $cn, $phone) {
  607. $first = true;
  608. if ($cCol !== null && $cCol !== '' && $cn !== '') {
  609. $q->where($cCol, $cn);
  610. $first = false;
  611. }
  612. if ($pCol !== null && $pCol !== '' && $phone !== '') {
  613. if ($first) {
  614. $q->where($pCol, $phone);
  615. } else {
  616. $q->whereOr($pCol, $phone);
  617. }
  618. }
  619. if ($first) {
  620. $q->where('id', 0);
  621. }
  622. };
  623. }
  624. /**
  625. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  626. */
  627. protected function mprocCustomerUserActive(array $row): bool
  628. {
  629. $st = $row['status'] ?? '';
  630. if ($st === '' || $st === null) {
  631. return true;
  632. }
  633. return $st === 1 || $st === '1';
  634. }
  635. /**
  636. * @return array<string, mixed>|null
  637. */
  638. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  639. {
  640. return $this->mprocFindCustomerRowByPhone($phone);
  641. }
  642. /**
  643. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  644. *
  645. * @return array<string, mixed>|null
  646. */
  647. protected function mprocFindCustomerUserByUsername(string $username): ?array
  648. {
  649. $username = trim($username);
  650. if ($username === '') {
  651. return null;
  652. }
  653. try {
  654. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  655. } catch (\Throwable $e) {
  656. $row = null;
  657. }
  658. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  659. $row = $this->mprocFindCustomerRowByPhone($username);
  660. }
  661. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  662. return null;
  663. }
  664. return $row;
  665. }
  666. /**
  667. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  668. */
  669. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  670. {
  671. $stored = (string)($row['password'] ?? '');
  672. if ($stored === '' || $password === '') {
  673. return false;
  674. }
  675. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  676. return password_verify($password, $stored);
  677. }
  678. return hash_equals($stored, md5(md5($password)));
  679. }
  680. /**
  681. * 生成 customer 登录密码密文
  682. */
  683. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  684. {
  685. unset($existingSalt);
  686. return md5(md5($password));
  687. }
  688. /**
  689. * 手机端强密码校验:通过返回空字符串,否则返回错误提示
  690. */
  691. protected function mprocValidateStrongPassword(string $password): string
  692. {
  693. $len = strlen($password);
  694. if ($len < 8 || $len > 20) {
  695. return '密码长度须为8~20位';
  696. }
  697. if (preg_match('/\s/', $password)) {
  698. return '密码不能包含空格';
  699. }
  700. if (preg_match('/^\d+$/', $password)) {
  701. return '密码不能为纯数字,请同时包含字母';
  702. }
  703. if (preg_match('/^[a-zA-Z]+$/', $password)) {
  704. return '密码不能为纯字母,请同时包含数字';
  705. }
  706. if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
  707. return '密码须同时包含字母和数字';
  708. }
  709. if (preg_match('/(.)\1{3,}/', $password)) {
  710. return '密码不能包含过多重复字符(如1111、aaaa)';
  711. }
  712. if ($this->mprocPasswordHasSequentialRun($password, 4)) {
  713. return '密码不能包含连续字符(如1234、abcd)';
  714. }
  715. $weak = [
  716. '12345678', '123456789', '1234567890', '87654321', '01234567',
  717. 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
  718. 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
  719. '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
  720. ];
  721. if (in_array(strtolower($password), $weak, true)) {
  722. return '密码过于简单,请重新设置';
  723. }
  724. return '';
  725. }
  726. /**
  727. * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
  728. */
  729. protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
  730. {
  731. $runLen = max(3, $runLen);
  732. $lower = strtolower($password);
  733. $n = strlen($lower);
  734. if ($n < $runLen) {
  735. return false;
  736. }
  737. for ($i = 0; $i <= $n - $runLen; $i++) {
  738. $asc = true;
  739. $desc = true;
  740. for ($j = 1; $j < $runLen; $j++) {
  741. $prev = ord($lower[$i + $j - 1]);
  742. $cur = ord($lower[$i + $j]);
  743. if ($cur !== $prev + 1) {
  744. $asc = false;
  745. }
  746. if ($cur !== $prev - 1) {
  747. $desc = false;
  748. }
  749. if (!$asc && !$desc) {
  750. break;
  751. }
  752. }
  753. if ($asc || $desc) {
  754. return true;
  755. }
  756. }
  757. return false;
  758. }
  759. /**
  760. * @param array<string, mixed> $cu
  761. * @return array<string, mixed>
  762. */
  763. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  764. {
  765. $phone = trim((string)($cu['phone'] ?? ''));
  766. $account = trim((string)($cu['account'] ?? ''));
  767. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  768. $phone = $account;
  769. }
  770. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  771. $account = $phone;
  772. }
  773. $companyName = trim((string)($cu['company_name'] ?? ''));
  774. if ($companyName === '' && $phone !== '') {
  775. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  776. }
  777. $id = (int)($cu['id'] ?? 0);
  778. return [
  779. 'phone' => $phone,
  780. 'account' => $account,
  781. 'company_name' => $companyName,
  782. 'username' => trim((string)($cu['username'] ?? '')),
  783. 'customer_id' => $id,
  784. 'customer_user_id' => $id,
  785. 'login_type' => $loginType,
  786. 'is_admin' => 0,
  787. ];
  788. }
  789. /**
  790. * 写入手机端登录态并返回跳转 URL
  791. *
  792. * @param array<string, mixed> $userData
  793. */
  794. protected function mprocFinishLogin(array $userData): void
  795. {
  796. $old = Session::get('mproc_token');
  797. if ($old) {
  798. $this->mprocClearLogin((string)$old);
  799. }
  800. $userData['login_time'] = time();
  801. $token = $this->mprocPackSignedAuthToken($userData);
  802. $token = $this->mprocTouchLoginState($userData, $token);
  803. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  804. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  805. Session::delete('mproc_intended_url');
  806. $raw = $postR !== '' ? $postR : $sessR;
  807. $jump = $this->mprocBuildAfterLoginIndexUrl($raw);
  808. $this->success('登录成功', $jump, [
  809. 'mproc_token' => $token,
  810. 'keep_hours' => $this->mprocKeepHours(),
  811. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  812. ]);
  813. }
  814. /**
  815. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  816. */
  817. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  818. {
  819. $phone = trim($phone);
  820. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  821. return '';
  822. }
  823. $cust = $this->mprocFindCustomerRowByPhone($phone);
  824. if (is_array($cust) && $cust !== []) {
  825. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  826. if ($co !== '') {
  827. return $co;
  828. }
  829. }
  830. try {
  831. $one = Db::table('purchase_order_detail')
  832. ->where('phone', $phone)
  833. ->order('id', 'desc')
  834. ->find();
  835. if (is_array($one)) {
  836. $n = trim((string)($one['company_name'] ?? ''));
  837. if ($n !== '') {
  838. return $n;
  839. }
  840. }
  841. } catch (\Throwable $e) {
  842. }
  843. return '';
  844. }
  845. /**
  846. * 按手机号匹配 customer(phone 或 account 单值相等)
  847. *
  848. * @return array<string, mixed>|null
  849. */
  850. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  851. {
  852. $phone = trim($phone);
  853. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  854. return null;
  855. }
  856. try {
  857. $row = Db::table('customer')
  858. ->where(function ($q) use ($phone) {
  859. $q->where('phone', $phone)->whereOr('account', $phone);
  860. })
  861. ->order('id', 'asc')
  862. ->find();
  863. } catch (\Throwable $e) {
  864. return null;
  865. }
  866. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  867. return null;
  868. }
  869. return $row;
  870. }
  871. /**
  872. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  873. *
  874. * @return array<string, mixed>|null
  875. */
  876. protected function mprocAdminRowByMobile(string $phone): ?array
  877. {
  878. $phone = trim($phone);
  879. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  880. return null;
  881. }
  882. try {
  883. $row = Db::name('admin')
  884. ->where('mobile', $phone)
  885. ->where('status', '<>', 'hidden')
  886. ->order('id', 'asc')
  887. ->find();
  888. } catch (\Throwable $e) {
  889. return null;
  890. }
  891. return is_array($row) && $row !== [] ? $row : null;
  892. }
  893. /**
  894. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  895. *
  896. * @return array<string, mixed>|null
  897. */
  898. protected function mprocFindCustomerRowForUser(array $user): ?array
  899. {
  900. $phone = trim((string)($user['phone'] ?? ''));
  901. if ($phone === '') {
  902. $phone = trim((string)($user['account'] ?? ''));
  903. }
  904. $cn = trim((string)($user['company_name'] ?? ''));
  905. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  906. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  907. if ($byPhone !== null) {
  908. return $byPhone;
  909. }
  910. }
  911. if ($cn !== '') {
  912. try {
  913. $hit = Db::table('customer')
  914. ->where(function ($q) use ($cn) {
  915. $q->where('company_name', $cn)->whereOr('name', $cn);
  916. })
  917. ->order('id', 'desc')
  918. ->find();
  919. } catch (\Throwable $e) {
  920. $hit = null;
  921. }
  922. if (is_array($hit) && $hit !== []) {
  923. return $hit;
  924. }
  925. }
  926. return null;
  927. }
  928. /**
  929. * 从 customer 行取字段(兼容列名大小写)
  930. *
  931. * @param string[] $candidates
  932. */
  933. protected function mprocCustomerPickField(array $row, array $candidates): string
  934. {
  935. foreach ($candidates as $want) {
  936. $lw = strtolower($want);
  937. foreach ($row as $k => $v) {
  938. if (!is_string($k)) {
  939. continue;
  940. }
  941. if (strtolower($k) !== $lw) {
  942. continue;
  943. }
  944. $s = trim((string)$v);
  945. if ($s !== '') {
  946. return $s;
  947. }
  948. }
  949. }
  950. return '';
  951. }
  952. /**
  953. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  954. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  955. *
  956. * @param \think\db\Query $query
  957. */
  958. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  959. {
  960. $kw = trim((string)$search);
  961. if ($kw === '') {
  962. return;
  963. }
  964. $map = self::$mprocProcuremenColumns;
  965. if (!is_array($map) || $map === []) {
  966. return;
  967. }
  968. $like = '%' . addcslashes($kw, '%_\\') . '%';
  969. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  970. $detailCols = [];
  971. foreach ($wantLower as $low) {
  972. if (isset($map[$low])) {
  973. $detailCols[] = $map[$low];
  974. }
  975. }
  976. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  977. $idCol = isset($map['id']) ? $map['id'] : 'id';
  978. $poSidList = [];
  979. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  980. try {
  981. $col = Db::table('purchase_order')
  982. ->where(function ($sub) use ($like, $poWant) {
  983. $firstPo = true;
  984. foreach ($poWant as $pf) {
  985. if ($firstPo) {
  986. $sub->where($pf, 'like', $like);
  987. $firstPo = false;
  988. } else {
  989. $sub->whereOr($pf, 'like', $like);
  990. }
  991. }
  992. })
  993. ->column('scydgy_id');
  994. if (is_array($col)) {
  995. foreach ($col as $v) {
  996. $id = (int)$v;
  997. if ($this->mprocIsValidScydgyRowId($id)) {
  998. $poSidList[$id] = true;
  999. }
  1000. }
  1001. }
  1002. $poSidList = array_keys($poSidList);
  1003. } catch (\Throwable $e) {
  1004. $poSidList = [];
  1005. }
  1006. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  1007. $first = true;
  1008. foreach ($detailCols as $col) {
  1009. if ($first) {
  1010. $q2->where($col, 'like', $like);
  1011. $first = false;
  1012. } else {
  1013. $q2->whereOr($col, 'like', $like);
  1014. }
  1015. }
  1016. if ($poSidList !== []) {
  1017. if ($first) {
  1018. $q2->where($scydgyCol, 'in', $poSidList);
  1019. $first = false;
  1020. } else {
  1021. $q2->whereOr($scydgyCol, 'in', $poSidList);
  1022. }
  1023. }
  1024. if ($first) {
  1025. $q2->where($idCol, '=', 0);
  1026. }
  1027. });
  1028. }
  1029. /**
  1030. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  1031. * - draft:status_name = 未提交
  1032. * - submitted:status_name = 已提交
  1033. * - done:status_name = 已完成
  1034. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  1035. *
  1036. * @param mixed $query
  1037. * @param string $tab draft|submitted|done
  1038. * @param string|null $statusNameCol 真实列名,如 status_name
  1039. */
  1040. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  1041. {
  1042. if ($statusNameCol === null) {
  1043. return;
  1044. }
  1045. $map = [
  1046. 'draft' => '未提交',
  1047. 'submitted' => '已提交',
  1048. 'done' => '已完成',
  1049. ];
  1050. $label = $map[$tab] ?? '未提交';
  1051. $query->where($statusNameCol, '=', $label);
  1052. }
  1053. /**
  1054. * 按登录态解析 customer 行
  1055. *
  1056. * @return array<string, mixed>|null
  1057. */
  1058. protected function mprocResolveCustomerUserForSession(array $user): ?array
  1059. {
  1060. if (!empty($user['is_admin'])) {
  1061. return null;
  1062. }
  1063. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1064. if ($cuId > 0) {
  1065. try {
  1066. $row = Db::table('customer')->where('id', $cuId)->find();
  1067. } catch (\Throwable $e) {
  1068. $row = null;
  1069. }
  1070. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  1071. return $row;
  1072. }
  1073. }
  1074. $account = trim((string)($user['account'] ?? ''));
  1075. if ($account !== '') {
  1076. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  1077. if ($byAcc !== null) {
  1078. return $byAcc;
  1079. }
  1080. }
  1081. $phone = trim((string)($user['phone'] ?? ''));
  1082. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1083. return $this->mprocFindCustomerUserByMobile($phone);
  1084. }
  1085. $uname = trim((string)($user['username'] ?? ''));
  1086. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1087. return $this->mprocFindCustomerUserByMobile($uname);
  1088. }
  1089. return null;
  1090. }
  1091. /**
  1092. * customer 表字段 →「我的」展示结构
  1093. *
  1094. * @param array<string, mixed> $cu
  1095. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  1096. */
  1097. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1098. {
  1099. $nm = trim((string)($cu['username'] ?? ''));
  1100. $phone = trim((string)($cu['phone'] ?? ''));
  1101. if ($phone === '') {
  1102. $phone = trim((string)($cu['account'] ?? ''));
  1103. }
  1104. return [
  1105. 'company_name' => trim((string)($cu['company_name'] ?? '')),
  1106. 'contact_name' => $nm,
  1107. 'phone' => $phone,
  1108. 'email' => trim((string)($cu['email'] ?? '')),
  1109. ];
  1110. }
  1111. /**
  1112. * 管理员「我的」:admin 表
  1113. *
  1114. * @return array{company_name:string,contact_name:string,phone:string,email:string}
  1115. */
  1116. protected function mprocProfileForAdmin(array $user): array
  1117. {
  1118. $uname = trim((string)($user['username'] ?? ''));
  1119. $out = [
  1120. 'company_name' => '管理员',
  1121. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1122. 'phone' => trim((string)($user['phone'] ?? '')),
  1123. 'email' => '',
  1124. ];
  1125. if ($uname === '') {
  1126. return $out;
  1127. }
  1128. try {
  1129. $row = Db::name('admin')->where('username', $uname)->find();
  1130. } catch (\Throwable $e) {
  1131. $row = null;
  1132. }
  1133. if (!is_array($row) || $row === []) {
  1134. return $out;
  1135. }
  1136. $nick = trim((string)($row['nickname'] ?? ''));
  1137. if ($nick !== '') {
  1138. $out['contact_name'] = $nick;
  1139. }
  1140. $mob = trim((string)($row['mobile'] ?? ''));
  1141. if ($mob !== '') {
  1142. $out['phone'] = $mob;
  1143. }
  1144. $em = trim((string)($row['email'] ?? ''));
  1145. if ($em !== '') {
  1146. $out['email'] = $em;
  1147. }
  1148. return $out;
  1149. }
  1150. /**
  1151. * 旧会话补全 customer_id 等字段
  1152. */
  1153. protected function mprocSyncSessionCustomerUser(array $user): array
  1154. {
  1155. if (!empty($user['is_admin'])) {
  1156. return $user;
  1157. }
  1158. $cu = $this->mprocResolveCustomerUserForSession($user);
  1159. if (!$cu) {
  1160. return $user;
  1161. }
  1162. $id = (int)($cu['id'] ?? 0);
  1163. $user['customer_id'] = $id;
  1164. $user['customer_user_id'] = $id;
  1165. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1166. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1167. $user['account'] = trim((string)($cu['account'] ?? ''));
  1168. $mob = trim((string)($cu['phone'] ?? ''));
  1169. if ($mob === '') {
  1170. $mob = trim((string)($cu['account'] ?? ''));
  1171. }
  1172. if ($mob !== '') {
  1173. $user['phone'] = $mob;
  1174. }
  1175. $token = Session::get('mproc_token');
  1176. if ($token) {
  1177. $user['login_time'] = (int)($user['login_time'] ?? time());
  1178. $tok = trim((string)$token);
  1179. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1180. if (!$this->mprocIsSignedAuthToken($tok)) {
  1181. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1182. }
  1183. }
  1184. return $user;
  1185. }
  1186. /**
  1187. * 「我的」:普通用户 customer;管理员 admin
  1188. */
  1189. protected function mprocProfileForUser(array $user)
  1190. {
  1191. if (!empty($user['is_admin'])) {
  1192. return $this->mprocProfileForAdmin($user);
  1193. }
  1194. $cu = $this->mprocResolveCustomerUserForSession($user);
  1195. if (is_array($cu) && $cu !== []) {
  1196. return $this->mprocProfileFromCustomerUserRow($cu);
  1197. }
  1198. $phone = trim((string)($user['phone'] ?? ''));
  1199. if ($phone === '') {
  1200. $phone = trim((string)($user['account'] ?? ''));
  1201. }
  1202. return [
  1203. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1204. 'contact_name' => trim((string)($user['username'] ?? '')),
  1205. 'phone' => $phone,
  1206. 'email' => '',
  1207. ];
  1208. }
  1209. protected function mprocIsValidScydgyRowId($id): bool
  1210. {
  1211. return (int)$id !== 0;
  1212. }
  1213. /**
  1214. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1215. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1216. *
  1217. * @param array $row 引用:明细行
  1218. * @param array $poRow purchase_order 一行
  1219. */
  1220. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1221. {
  1222. $pl = array_change_key_case($poRow, CASE_LOWER);
  1223. $hdr = [
  1224. 'ccydh' => 'CCYDH',
  1225. 'cyjmc' => 'CYJMC',
  1226. 'cdf' => 'CDF',
  1227. 'cgzzxmc' => 'cGzzxMc',
  1228. 'cgymc' => 'CGYMC',
  1229. 'cdxmc' => 'CDXMC',
  1230. 'ngzl' => 'NGZL',
  1231. 'cdw' => 'CDW',
  1232. 'cgybh' => 'CGYBH',
  1233. ];
  1234. foreach ($hdr as $lk => $out) {
  1235. if (!array_key_exists($lk, $pl)) {
  1236. continue;
  1237. }
  1238. $v = $pl[$lk];
  1239. if ($v !== null && $v !== '') {
  1240. $row[$out] = $v;
  1241. }
  1242. }
  1243. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1244. $qtyRaw = '';
  1245. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1246. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1247. $qtyRaw = trim((string)$pl[$qk]);
  1248. break;
  1249. }
  1250. }
  1251. if ($qtyRaw === '') {
  1252. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1253. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1254. $qtyRaw = trim((string)$poRow[$qk]);
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. if ($qtyRaw !== '') {
  1260. $row['This_quantity'] = $qtyRaw;
  1261. }
  1262. $ceilRaw = '';
  1263. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1264. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1265. $ceilRaw = trim((string)$pl[$ck]);
  1266. break;
  1267. }
  1268. }
  1269. if ($ceilRaw === '') {
  1270. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1271. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1272. $ceilRaw = trim((string)$poRow[$ck]);
  1273. break;
  1274. }
  1275. }
  1276. }
  1277. if ($ceilRaw !== '') {
  1278. $row['ceilingPrice'] = $ceilRaw;
  1279. }
  1280. $sysRq = '';
  1281. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1282. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1283. $sysRq = trim((string)$pl[$sk]);
  1284. break;
  1285. }
  1286. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1287. $sysRq = trim((string)$poRow[$sk]);
  1288. break;
  1289. }
  1290. }
  1291. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1292. $row['sys_rq'] = $sysRq;
  1293. }
  1294. $deliveryDeadline = '';
  1295. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1296. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1297. $deliveryDeadline = trim((string)$pl[$dk]);
  1298. break;
  1299. }
  1300. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1301. $deliveryDeadline = trim((string)$poRow[$dk]);
  1302. break;
  1303. }
  1304. }
  1305. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1306. $row['delivery_deadline'] = $deliveryDeadline;
  1307. }
  1308. }
  1309. /**
  1310. * 统一取年月日(无效则空串)
  1311. */
  1312. protected function mprocFormatYmdValue($raw): string
  1313. {
  1314. $s = trim((string)$raw);
  1315. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1316. return '';
  1317. }
  1318. $s = str_replace(['/', '.'], '-', $s);
  1319. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1320. return $m[1];
  1321. }
  1322. $ts = strtotime(str_replace('T', ' ', $s));
  1323. if ($ts === false || $ts <= 0) {
  1324. return '';
  1325. }
  1326. return date('Y-m-d', $ts);
  1327. }
  1328. /**
  1329. * 列表展示:招标截止 / 交货截止
  1330. *
  1331. * @param array<string, mixed> $row
  1332. */
  1333. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1334. {
  1335. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1336. $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
  1337. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1338. $row['mproc_bid_deadline_display'] = $bid;
  1339. // 完整截止时间供前端保存前校验(含时分秒)
  1340. $row['mproc_bid_deadline'] = $sysRqRaw;
  1341. $row['mproc_delivery_deadline_display'] = $del;
  1342. $row['mproc_delivery_deadline'] = $del;
  1343. }
  1344. /**
  1345. * 明细对应主表的交货截止日期 Y-m-d
  1346. *
  1347. * @param array<string, mixed> $row
  1348. */
  1349. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1350. {
  1351. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1352. if ($fromRow !== '') {
  1353. return $fromRow;
  1354. }
  1355. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1356. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1357. return '';
  1358. }
  1359. try {
  1360. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1361. } catch (\Throwable $e) {
  1362. $po = null;
  1363. }
  1364. if (!is_array($po)) {
  1365. return '';
  1366. }
  1367. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1368. }
  1369. /**
  1370. * 主表报价截止时间(未设置则视为未截止)
  1371. *
  1372. * @param array<string, mixed>|null $po
  1373. */
  1374. protected function mprocResolveSysRqFromPo(?array $po): string
  1375. {
  1376. if (!is_array($po)) {
  1377. return '';
  1378. }
  1379. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1380. if ($sr === '') {
  1381. $pl = array_change_key_case($po, CASE_LOWER);
  1382. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1383. }
  1384. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1385. }
  1386. /**
  1387. * 从主表/明细解析订单号
  1388. *
  1389. * @param array<string, mixed>|null $po
  1390. * @param array<string, mixed>|null $row
  1391. */
  1392. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1393. {
  1394. foreach ([$po, $row] as $src) {
  1395. if (!is_array($src)) {
  1396. continue;
  1397. }
  1398. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1399. if ($c !== '') {
  1400. return $c;
  1401. }
  1402. }
  1403. return '';
  1404. }
  1405. /**
  1406. * 批量:已开标验证的订单号集合(本请求内可复用)
  1407. *
  1408. * @var array<string, bool>|null
  1409. */
  1410. protected $mprocBidOpenVerifiedSet = null;
  1411. /**
  1412. * @param array<int, string> $ccydhs
  1413. * @return array<string, bool>
  1414. */
  1415. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1416. {
  1417. $set = [];
  1418. $list = [];
  1419. foreach ($ccydhs as $c) {
  1420. $c = trim((string)$c);
  1421. if ($c !== '') {
  1422. $list[$c] = true;
  1423. }
  1424. }
  1425. if ($list === []) {
  1426. return $set;
  1427. }
  1428. try {
  1429. $rows = Db::table('purchase_order_bid_open')
  1430. ->where('ccydh', 'in', array_keys($list))
  1431. ->field('ccydh')
  1432. ->select();
  1433. if (!is_array($rows)) {
  1434. return $set;
  1435. }
  1436. foreach ($rows as $row) {
  1437. if (!is_array($row)) {
  1438. continue;
  1439. }
  1440. $c = trim((string)($row['ccydh'] ?? ''));
  1441. if ($c !== '') {
  1442. $set[$c] = true;
  1443. }
  1444. }
  1445. } catch (\Throwable $e) {
  1446. return [];
  1447. }
  1448. return $set;
  1449. }
  1450. /**
  1451. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1452. */
  1453. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1454. {
  1455. $ccydh = trim($ccydh);
  1456. if ($ccydh === '') {
  1457. return false;
  1458. }
  1459. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1460. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1461. }
  1462. try {
  1463. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1464. return is_array($row);
  1465. } catch (\Throwable $e) {
  1466. return false;
  1467. }
  1468. }
  1469. /**
  1470. * @param array<string, mixed>|null $po
  1471. * @param array<string, mixed>|null $row
  1472. */
  1473. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1474. {
  1475. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1476. }
  1477. /**
  1478. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1479. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1480. *
  1481. * @param array<string, mixed>|null $po
  1482. */
  1483. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1484. {
  1485. $raw = $this->mprocResolveSysRqFromPo($po);
  1486. if ($raw === '') {
  1487. return false;
  1488. }
  1489. $ts = strtotime(str_replace('T', ' ', $raw));
  1490. if ($ts === false || $ts <= 0) {
  1491. return false;
  1492. }
  1493. return time() >= $ts;
  1494. }
  1495. /**
  1496. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1497. *
  1498. * @param array<string, mixed>|null $po
  1499. */
  1500. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1501. {
  1502. // 以库中最新主表为准,避免内存中旧快照
  1503. $freshPo = null;
  1504. if (is_array($po)) {
  1505. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1506. if ($this->mprocIsValidScydgyRowId($sid)) {
  1507. try {
  1508. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1509. } catch (\Throwable $e) {
  1510. $freshPo = null;
  1511. }
  1512. }
  1513. }
  1514. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1515. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1516. throw new \InvalidArgumentException(
  1517. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1518. );
  1519. }
  1520. }
  1521. /**
  1522. * 保存前:截止时间 + 已开标均不可再改
  1523. *
  1524. * @param array<string, mixed>|null $po
  1525. * @param array<string, mixed>|null $row
  1526. */
  1527. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1528. {
  1529. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1530. $freshPo = is_array($po) ? $po : null;
  1531. if (is_array($po)) {
  1532. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1533. if ($this->mprocIsValidScydgyRowId($sid)) {
  1534. try {
  1535. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1536. if (is_array($got)) {
  1537. $freshPo = $got;
  1538. }
  1539. } catch (\Throwable $e) {
  1540. }
  1541. }
  1542. }
  1543. // 保存场景不走列表缓存,直接查库
  1544. $prev = $this->mprocBidOpenVerifiedSet;
  1545. $this->mprocBidOpenVerifiedSet = null;
  1546. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1547. $this->mprocBidOpenVerifiedSet = $prev;
  1548. if ($opened) {
  1549. throw new \InvalidArgumentException(
  1550. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1551. );
  1552. }
  1553. }
  1554. /**
  1555. * 主单已完结后:中标 / 未中标
  1556. *
  1557. * @param array<string, mixed> $row
  1558. * @param array<string, mixed>|null $po
  1559. */
  1560. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1561. {
  1562. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1563. return '';
  1564. }
  1565. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1566. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1567. }
  1568. /**
  1569. * 手机端左侧 Tab:draft|submitted|done
  1570. *
  1571. * @param array<string, mixed> $row
  1572. * @param array<string, mixed>|null $po
  1573. */
  1574. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1575. {
  1576. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1577. return 'done';
  1578. }
  1579. // 已开标或已过招标截止 →「已完成」(含已报价),角标「已截止」或中标结果
  1580. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  1581. return 'done';
  1582. }
  1583. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1584. return 'done';
  1585. }
  1586. if ($effectiveSn === '已提交') {
  1587. return 'submitted';
  1588. }
  1589. return 'draft';
  1590. }
  1591. /**
  1592. * 同一订单号 + 供应商合并为一张卡片
  1593. *
  1594. * @param array<int, array<string, mixed>> $rows
  1595. * @return array<int, array<string, mixed>>
  1596. */
  1597. protected function mprocGroupRowsByOrder(array $rows): array
  1598. {
  1599. $groups = [];
  1600. $order = [];
  1601. foreach ($rows as $row) {
  1602. if (!is_array($row)) {
  1603. continue;
  1604. }
  1605. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1606. $cname = trim((string)($row['company_name'] ?? ''));
  1607. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1608. if (!isset($groups[$key])) {
  1609. $groups[$key] = [
  1610. 'group_key' => $key,
  1611. 'CCYDH' => $ccydh,
  1612. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1613. 'company_name' => $cname,
  1614. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  1615. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  1616. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  1617. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  1618. 'lines' => [],
  1619. ];
  1620. $order[] = $key;
  1621. } else {
  1622. if ($groups[$key]['mproc_delivery_deadline'] === ''
  1623. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  1624. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  1625. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  1626. }
  1627. if ($groups[$key]['mproc_bid_deadline'] === ''
  1628. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  1629. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  1630. }
  1631. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  1632. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  1633. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  1634. }
  1635. }
  1636. $groups[$key]['lines'][] = $row;
  1637. }
  1638. $out = [];
  1639. foreach ($order as $key) {
  1640. $g = $groups[$key];
  1641. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1642. usort($lines, function ($a, $b) {
  1643. $sa = (int)($a['scydgy_id'] ?? 0);
  1644. $sb = (int)($b['scydgy_id'] ?? 0);
  1645. if ($sa !== $sb) {
  1646. return $sa <=> $sb;
  1647. }
  1648. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1649. });
  1650. $g['lines'] = $lines;
  1651. $g['line_count'] = count($lines);
  1652. $canEdit = false;
  1653. $bidOpen = false;
  1654. foreach ($lines as $ln) {
  1655. if (!is_array($ln)) {
  1656. continue;
  1657. }
  1658. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1659. $canEdit = true;
  1660. }
  1661. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  1662. $bidOpen = true;
  1663. }
  1664. }
  1665. $g['can_edit'] = $canEdit ? 1 : 0;
  1666. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  1667. $remark = '';
  1668. $doneLabel = '';
  1669. $pickResult = '';
  1670. $hasWin = false;
  1671. $hasLose = false;
  1672. $hasExpired = false;
  1673. foreach ($lines as $ln) {
  1674. if (!is_array($ln)) {
  1675. continue;
  1676. }
  1677. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1678. if ($rm !== '' && $remark === '') {
  1679. $remark = $rm;
  1680. }
  1681. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1682. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1683. if ($pr === '中标' || $dl === '中标') {
  1684. $hasWin = true;
  1685. } elseif ($pr === '未中标' || $dl === '未中标') {
  1686. $hasLose = true;
  1687. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  1688. $hasExpired = true;
  1689. }
  1690. }
  1691. if ($hasWin) {
  1692. $doneLabel = '中标';
  1693. $pickResult = '中标';
  1694. } elseif ($hasLose) {
  1695. $doneLabel = '未中标';
  1696. $pickResult = '未中标';
  1697. } elseif ($hasExpired) {
  1698. $doneLabel = '已截止';
  1699. $pickResult = '';
  1700. }
  1701. $g['remark'] = $remark;
  1702. $g['mproc_done_label'] = $doneLabel;
  1703. $g['mproc_pick_result'] = $pickResult;
  1704. $out[] = $g;
  1705. }
  1706. return $out;
  1707. }
  1708. /**
  1709. * 查询 purchase_order_detail 列表(订单页)
  1710. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  1711. * 有搜索词时:在当前 Tab 内做关键字匹配
  1712. *
  1713. * @param string $tab draft|submitted|done
  1714. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  1715. * @return array{rows: array, done_no_status: int}
  1716. */
  1717. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  1718. {
  1719. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  1720. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  1721. $userWhere = $this->mprocListWhereForLoginUser($user);
  1722. if ($userWhere !== []) {
  1723. $query->where($userWhere);
  1724. }
  1725. if (trim((string)$q) === '' && $tab === 'done' && $statusNameCol !== null) {
  1726. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  1727. }
  1728. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  1729. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  1730. try {
  1731. $rows = $query->limit(500)->select();
  1732. } catch (\Throwable $e) {
  1733. $rows = [];
  1734. }
  1735. if (!is_array($rows)) {
  1736. $rows = [];
  1737. }
  1738. $poBySid = [];
  1739. $sidList = [];
  1740. foreach ($rows as $r0) {
  1741. if (!is_array($r0)) {
  1742. continue;
  1743. }
  1744. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  1745. if ($this->mprocIsValidScydgyRowId($sid0)) {
  1746. $sidList[$sid0] = true;
  1747. }
  1748. }
  1749. if ($sidList !== []) {
  1750. try {
  1751. $poRows = Db::table('purchase_order')
  1752. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  1753. ->select();
  1754. if (is_array($poRows)) {
  1755. foreach ($poRows as $pr) {
  1756. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  1757. if ($this->mprocIsValidScydgyRowId($sidk)) {
  1758. $poBySid[$sidk] = $pr;
  1759. }
  1760. }
  1761. }
  1762. } catch (\Throwable $e) {
  1763. }
  1764. }
  1765. $ccydhForBid = [];
  1766. foreach ($poBySid as $pr) {
  1767. if (!is_array($pr)) {
  1768. continue;
  1769. }
  1770. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  1771. if ($c !== '') {
  1772. $ccydhForBid[$c] = true;
  1773. }
  1774. }
  1775. foreach ($rows as $r0) {
  1776. if (!is_array($r0)) {
  1777. continue;
  1778. }
  1779. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  1780. if ($c !== '') {
  1781. $ccydhForBid[$c] = true;
  1782. }
  1783. }
  1784. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  1785. foreach ($rows as &$row) {
  1786. if (!is_array($row)) {
  1787. continue;
  1788. }
  1789. // 废弃明细不在手机端展示
  1790. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
  1791. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
  1792. $row = null;
  1793. continue;
  1794. }
  1795. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  1796. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1797. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  1798. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  1799. }
  1800. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  1801. $oldSn = trim((string)($row['status_name'] ?? ''));
  1802. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  1803. $row['status_name'] = $effectiveSn;
  1804. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  1805. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  1806. }
  1807. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  1808. $row['mproc_list_tab'] = $listTab;
  1809. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  1810. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  1811. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  1812. if ($row['mproc_pick_result'] !== '') {
  1813. $row['mproc_done_label'] = $row['mproc_pick_result'];
  1814. } elseif ($listTab === 'done' && (
  1815. (int)$row['mproc_deadline_reached'] === 1
  1816. || (int)$row['mproc_bid_open_verified'] === 1
  1817. )) {
  1818. $row['mproc_done_label'] = '已截止';
  1819. } else {
  1820. $row['mproc_done_label'] = '';
  1821. }
  1822. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  1823. if (!isset($row['status_name']) || $row['status_name'] === null) {
  1824. $row['status_name'] = '';
  1825. } else {
  1826. $row['status_name'] = trim((string)$row['status_name']);
  1827. }
  1828. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  1829. $am = $row['amount'] ?? null;
  1830. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  1831. $row['amount_display'] = '';
  1832. } else {
  1833. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  1834. }
  1835. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  1836. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  1837. $row['delivery_display'] = $m[1];
  1838. } elseif ($dv !== '') {
  1839. $row['delivery_display'] = $dv;
  1840. } else {
  1841. $row['delivery_display'] = '';
  1842. }
  1843. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  1844. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  1845. $this->mprocEnrichLeadDaysDisplay($row);
  1846. $this->mprocEnrichOrderDeadlineDisplay($row);
  1847. $row['mproc_fill_hint'] = '';
  1848. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  1849. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  1850. }
  1851. unset($row);
  1852. $rows = array_values(array_filter($rows, function ($r) {
  1853. return is_array($r);
  1854. }));
  1855. // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
  1856. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  1857. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  1858. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  1859. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  1860. }));
  1861. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  1862. if ($tab === 'done') {
  1863. $rows = array_values(array_filter($rows, function ($r) {
  1864. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  1865. }));
  1866. }
  1867. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  1868. $rows = $this->mprocSortRowsByBidDeadline($rows, $tab === 'done' ? 'desc' : 'asc');
  1869. $groups = $this->mprocGroupRowsByOrder($rows);
  1870. return [
  1871. 'rows' => $rows ?: [],
  1872. 'groups' => $groups ?: [],
  1873. 'done_no_status' => (int)($statusNameCol === null),
  1874. ];
  1875. }
  1876. /**
  1877. * 按招标截止时间排序(无截止时间的排最后)
  1878. *
  1879. * @param array<int, array<string, mixed>> $rows
  1880. * @param string $dir asc|desc
  1881. * @return array<int, array<string, mixed>>
  1882. */
  1883. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  1884. {
  1885. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  1886. usort($rows, function ($a, $b) use ($dir) {
  1887. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  1888. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  1889. $ha = $ta > 0;
  1890. $hb = $tb > 0;
  1891. if ($ha !== $hb) {
  1892. return $ha ? -1 : 1;
  1893. }
  1894. if ($ha && $ta !== $tb) {
  1895. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  1896. }
  1897. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  1898. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  1899. return $idb <=> $ida;
  1900. });
  1901. return array_values($rows);
  1902. }
  1903. /**
  1904. * @param array<string, mixed> $row
  1905. */
  1906. protected function mprocBidDeadlineSortTs(array $row): int
  1907. {
  1908. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  1909. if ($raw === '') {
  1910. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  1911. }
  1912. if ($raw === '') {
  1913. return 0;
  1914. }
  1915. $ts = strtotime(str_replace('T', ' ', $raw));
  1916. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  1917. }
  1918. /**
  1919. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  1920. *
  1921. * @param array<string, mixed> $row
  1922. */
  1923. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  1924. {
  1925. $months = max(1, $months);
  1926. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  1927. if ($since === false) {
  1928. return true;
  1929. }
  1930. $candidates = [
  1931. $row['mproc_bid_deadline'] ?? '',
  1932. $row['sys_rq'] ?? '',
  1933. $row['SYS_RQ'] ?? '',
  1934. $row['mproc_bid_deadline_display'] ?? '',
  1935. $row['mproc_delivery_deadline'] ?? '',
  1936. $row['delivery_deadline'] ?? '',
  1937. $row['mproc_delivery_deadline_display'] ?? '',
  1938. $row['createtime'] ?? '',
  1939. $row['updatetime'] ?? '',
  1940. ];
  1941. foreach ($candidates as $raw) {
  1942. $raw = trim((string)$raw);
  1943. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  1944. continue;
  1945. }
  1946. $ts = strtotime(str_replace('T', ' ', $raw));
  1947. if ($ts === false || $ts <= 0) {
  1948. continue;
  1949. }
  1950. return $ts >= $since;
  1951. }
  1952. return false;
  1953. }
  1954. /**
  1955. * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
  1956. *
  1957. * @param array<int, array<string, mixed>> $rows
  1958. * @return array<int, array<string, mixed>>
  1959. */
  1960. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  1961. {
  1962. $best = [];
  1963. $orderKeys = [];
  1964. foreach ($rows as $row) {
  1965. if (!is_array($row)) {
  1966. continue;
  1967. }
  1968. $cn = trim((string)($row['company_name'] ?? ''));
  1969. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1970. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  1971. if ($this->mprocIsValidScydgyRowId($sid)) {
  1972. $key = $cn . '|sid:' . $sid;
  1973. } else {
  1974. $key = $cn . '|eid:' . $eid;
  1975. }
  1976. if (!isset($best[$key])) {
  1977. $best[$key] = $row;
  1978. $orderKeys[] = $key;
  1979. continue;
  1980. }
  1981. $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
  1982. if ($eid > $prevEid) {
  1983. $best[$key] = $row;
  1984. }
  1985. }
  1986. $out = [];
  1987. foreach ($orderKeys as $key) {
  1988. if (isset($best[$key])) {
  1989. $out[] = $best[$key];
  1990. }
  1991. }
  1992. return $out;
  1993. }
  1994. /**
  1995. * status_name → 手机端左侧 Tab
  1996. */
  1997. protected function mprocStatusNameToListTab(string $statusName): string
  1998. {
  1999. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2000. $sn = trim($statusName);
  2001. return isset($map[$sn]) ? $map[$sn] : '';
  2002. }
  2003. /**
  2004. * 短信/邮件 focus_eid 应落在的列表 Tab
  2005. */
  2006. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2007. {
  2008. if ($focusEid <= 0) {
  2009. return '';
  2010. }
  2011. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2012. if ($idCol === null) {
  2013. return '';
  2014. }
  2015. try {
  2016. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2017. $qw = $this->mprocListWhereForLoginUser($user);
  2018. if ($qw !== []) {
  2019. $qrow->where($qw);
  2020. }
  2021. $dr = $qrow->find();
  2022. } catch (\Throwable $e) {
  2023. $dr = null;
  2024. }
  2025. if (!is_array($dr) || $dr === []) {
  2026. return '';
  2027. }
  2028. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2029. $po = null;
  2030. if ($this->mprocIsValidScydgyRowId($sid)) {
  2031. try {
  2032. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2033. } catch (\Throwable $e) {
  2034. $po = null;
  2035. }
  2036. }
  2037. return $this->mprocResolveListTabForRow(
  2038. $dr,
  2039. is_array($po) ? $po : null,
  2040. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2041. );
  2042. }
  2043. /**
  2044. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2045. *
  2046. * @param array<string, mixed> $bundle
  2047. * @param array<string, mixed> $user
  2048. * @return array<string, mixed>
  2049. */
  2050. protected function mprocEnsureFocusRowInList(
  2051. array $bundle,
  2052. int $focusEid,
  2053. array $user,
  2054. $statusNameCol,
  2055. string $tab = 'draft',
  2056. string $q = ''
  2057. ): array {
  2058. if ($focusEid <= 0) {
  2059. return $bundle;
  2060. }
  2061. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2062. $foundIdx = -1;
  2063. foreach ($rows as $idx => $r) {
  2064. if (!is_array($r)) {
  2065. continue;
  2066. }
  2067. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2068. $foundIdx = (int)$idx;
  2069. break;
  2070. }
  2071. }
  2072. if ($foundIdx > 0) {
  2073. $hit = $rows[$foundIdx];
  2074. array_splice($rows, $foundIdx, 1);
  2075. array_unshift($rows, $hit);
  2076. $bundle['rows'] = $rows;
  2077. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2078. return $bundle;
  2079. }
  2080. if ($foundIdx === 0) {
  2081. return $bundle;
  2082. }
  2083. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2084. if ($idCol === null) {
  2085. return $bundle;
  2086. }
  2087. try {
  2088. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2089. $qw = $this->mprocListWhereForLoginUser($user);
  2090. if ($qw !== []) {
  2091. $qrow->where($qw);
  2092. }
  2093. $dr = $qrow->find();
  2094. } catch (\Throwable $e) {
  2095. $dr = null;
  2096. }
  2097. if (!is_array($dr) || $dr === []) {
  2098. return $bundle;
  2099. }
  2100. $row = $dr;
  2101. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2102. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2103. $poRow = null;
  2104. if ($this->mprocIsValidScydgyRowId($sid)) {
  2105. try {
  2106. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2107. } catch (\Throwable $e) {
  2108. $poRow = null;
  2109. }
  2110. if (is_array($poRow)) {
  2111. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2112. }
  2113. }
  2114. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2115. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2116. if ($rowTab !== '' && $rowTab !== $tab) {
  2117. return $bundle;
  2118. }
  2119. $row['status_name'] = $effectiveSn;
  2120. $listTab = $rowTab;
  2121. $row['mproc_list_tab'] = $listTab;
  2122. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2123. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2124. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2125. if ($row['mproc_pick_result'] !== '') {
  2126. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2127. } elseif ($listTab === 'done' && (
  2128. (int)$row['mproc_deadline_reached'] === 1
  2129. || (int)$row['mproc_bid_open_verified'] === 1
  2130. )) {
  2131. $row['mproc_done_label'] = '已截止';
  2132. } else {
  2133. $row['mproc_done_label'] = '';
  2134. }
  2135. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2136. $am = $row['amount'] ?? null;
  2137. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2138. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2139. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2140. $row['delivery_display'] = $m[1];
  2141. } elseif ($dv !== '') {
  2142. $row['delivery_display'] = $dv;
  2143. } else {
  2144. $row['delivery_display'] = '';
  2145. }
  2146. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2147. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2148. $this->mprocEnrichLeadDaysDisplay($row);
  2149. $this->mprocEnrichOrderDeadlineDisplay($row);
  2150. $row['mproc_fill_hint'] = '';
  2151. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2152. array_unshift($rows, $row);
  2153. $bundle['rows'] = $rows;
  2154. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2155. return $bundle;
  2156. }
  2157. /**
  2158. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2159. *
  2160. * @param array<string, mixed> $row
  2161. */
  2162. protected function mprocResolveDisplayThisQuantity(array $row): string
  2163. {
  2164. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2165. if ($qty !== '') {
  2166. return $qty;
  2167. }
  2168. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2169. if ($gzl === null || $gzl === '') {
  2170. return '';
  2171. }
  2172. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2173. }
  2174. /**
  2175. * 明细是否已填写单价或交货日期
  2176. *
  2177. * @param array<string, mixed> $row
  2178. */
  2179. protected function mprocDetailQuoteSubmitted(array $row): bool
  2180. {
  2181. $am = $row['amount'] ?? null;
  2182. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2183. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2184. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2185. return $amountFilled || $deliveryFilled;
  2186. }
  2187. /**
  2188. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2189. *
  2190. * @param array<string, mixed> $row
  2191. * @param array<string, mixed>|null $po
  2192. */
  2193. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2194. {
  2195. $sn = trim((string)($row['status_name'] ?? ''));
  2196. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2197. return $sn;
  2198. }
  2199. if (!is_array($po)) {
  2200. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2201. return '已提交';
  2202. }
  2203. if ($sn !== '') {
  2204. return $sn;
  2205. }
  2206. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2207. }
  2208. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2209. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2210. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2211. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2212. return '已提交';
  2213. }
  2214. if ($sn !== '') {
  2215. return $sn;
  2216. }
  2217. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2218. }
  2219. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2220. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2221. return '已完成';
  2222. }
  2223. if ($sn === '已提交') {
  2224. return '未通过';
  2225. }
  2226. return $sn !== '' ? $sn : '未提交';
  2227. }
  2228. /**
  2229. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2230. */
  2231. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2232. {
  2233. if ($detailId <= 0 || $statusNameCol === '') {
  2234. return;
  2235. }
  2236. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2237. if ($idCol === null || $idCol === '') {
  2238. return;
  2239. }
  2240. try {
  2241. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2242. } catch (\Throwable $e) {
  2243. }
  2244. }
  2245. /**
  2246. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2247. *
  2248. * @param array<string, mixed> $user
  2249. */
  2250. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2251. {
  2252. $userWhere = $this->mprocListWhereForLoginUser($user);
  2253. try {
  2254. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2255. if ($userWhere !== []) {
  2256. $query->where($userWhere);
  2257. }
  2258. $candidates = $query->limit(200)->select();
  2259. } catch (\Throwable $e) {
  2260. return;
  2261. }
  2262. if (!is_array($candidates) || $candidates === []) {
  2263. return;
  2264. }
  2265. $sidList = [];
  2266. foreach ($candidates as $cr) {
  2267. if (!is_array($cr)) {
  2268. continue;
  2269. }
  2270. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2271. if ($this->mprocIsValidScydgyRowId($sid)) {
  2272. $sidList[$sid] = true;
  2273. }
  2274. }
  2275. if ($sidList === []) {
  2276. return;
  2277. }
  2278. $poBySid = [];
  2279. try {
  2280. $poRows = Db::table('purchase_order')
  2281. ->where('scydgy_id', 'in', array_keys($sidList))
  2282. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2283. ->select();
  2284. if (is_array($poRows)) {
  2285. foreach ($poRows as $pr) {
  2286. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2287. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2288. $poBySid[$sidk] = $pr;
  2289. }
  2290. }
  2291. }
  2292. } catch (\Throwable $e) {
  2293. return;
  2294. }
  2295. if ($poBySid === []) {
  2296. return;
  2297. }
  2298. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2299. if ($idCol === null || $idCol === '') {
  2300. return;
  2301. }
  2302. foreach ($candidates as $cr) {
  2303. if (!is_array($cr)) {
  2304. continue;
  2305. }
  2306. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2307. if (!isset($poBySid[$sid])) {
  2308. continue;
  2309. }
  2310. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2311. if ($detailId <= 0) {
  2312. continue;
  2313. }
  2314. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2315. if ($targetSn === '已提交') {
  2316. continue;
  2317. }
  2318. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2319. }
  2320. }
  2321. /**
  2322. * 协助明细首页(需登录)
  2323. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2324. */
  2325. public function index()
  2326. {
  2327. $user = $this->mprocGetUser();
  2328. if (!$user) {
  2329. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2330. if ($pendingFocus > 0) {
  2331. $this->mprocRememberFocusEid($pendingFocus);
  2332. }
  2333. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2334. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2335. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2336. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2337. }
  2338. if ($safe !== '') {
  2339. Session::set('mproc_intended_url', $safe);
  2340. }
  2341. $this->redirect($this->mprocBuildLoginUrl($safe));
  2342. return;
  2343. }
  2344. $user = $this->mprocSyncSessionCustomerUser($user);
  2345. $tabParamRaw = $this->request->get('tab', null);
  2346. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2347. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2348. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2349. // 旧地址 ?tab=me 表示「我的」
  2350. if ($tabParam === 'me') {
  2351. $mainTab = 'me';
  2352. }
  2353. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2354. $mainTab = 'orders';
  2355. }
  2356. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  2357. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  2358. $tab = 'draft';
  2359. }
  2360. $q = trim((string)$this->request->get('q', ''));
  2361. $mprocFocusEid = 0;
  2362. $focusEid = $this->mprocReadFocusEidFromRequest();
  2363. if ($focusEid > 0 && $mainTab === 'orders') {
  2364. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2365. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2366. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2367. Session::delete('mproc_focus_eid');
  2368. $focusEid = 0;
  2369. } else {
  2370. $mprocFocusEid = $focusEid;
  2371. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2372. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2373. if (!$focusFromUrl) {
  2374. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2375. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2376. }
  2377. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2378. if ($resolvedTab !== '') {
  2379. $tab = $resolvedTab;
  2380. }
  2381. }
  2382. }
  2383. }
  2384. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2385. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2386. $profile = $this->mprocProfileForUser($user);
  2387. $this->view->assign('mprocMainTab', $mainTab);
  2388. $this->view->assign('mprocTab', $tab);
  2389. $this->view->assign('mprocSearchQ', $q);
  2390. $this->view->assign('mprocProfile', $profile);
  2391. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2392. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2393. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2394. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2395. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2396. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2397. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2398. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2399. if ($mainTab === 'me') {
  2400. $this->view->assign('rows', []);
  2401. return $this->view->fetch();
  2402. }
  2403. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2404. if ($mprocFocusEid > 0) {
  2405. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2406. }
  2407. $this->view->assign('rows', $bundle['rows']);
  2408. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2409. return $this->view->fetch();
  2410. }
  2411. /**
  2412. * 协助明细列表 JSON(需登录)
  2413. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2414. */
  2415. public function mprocList()
  2416. {
  2417. $user = $this->mprocGetUser();
  2418. if (!$user) {
  2419. $this->error('请先登录', url('index/index/login'));
  2420. }
  2421. $user = $this->mprocSyncSessionCustomerUser($user);
  2422. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  2423. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  2424. if ($tabParam === 'me') {
  2425. $mainTab = 'me';
  2426. }
  2427. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2428. $mainTab = 'orders';
  2429. }
  2430. $tab = $tabParam === 'me' ? 'draft' : $tabParam;
  2431. if (!in_array($tab, ['draft', 'submitted', 'done'], true)) {
  2432. $tab = 'draft';
  2433. }
  2434. $q = trim((string)$this->request->request('q', ''));
  2435. if ($mainTab === 'me') {
  2436. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  2437. $this->success('ok', '', [
  2438. 'main_tab' => 'me',
  2439. 'tab' => $tab,
  2440. 'rows' => [],
  2441. 'profile' => $this->mprocProfileForUser($user),
  2442. 'done_no_status' => 0,
  2443. ]);
  2444. }
  2445. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2446. if ((int)$this->request->request('clear_focus', 0) === 1) {
  2447. Session::delete('mproc_focus_eid');
  2448. $focusEid = 0;
  2449. $focusTab = '';
  2450. } else {
  2451. $focusEid = $this->mprocReadFocusEidFromRequest();
  2452. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  2453. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  2454. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  2455. Session::delete('mproc_focus_eid');
  2456. $focusEid = 0;
  2457. $focusTab = '';
  2458. }
  2459. }
  2460. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2461. if ($focusEid > 0) {
  2462. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  2463. }
  2464. $this->success('ok', '', array_merge([
  2465. 'main_tab' => 'orders',
  2466. 'tab' => $tab,
  2467. 'focus_tab' => $focusTab,
  2468. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  2469. 'focus_eid' => $focusEid,
  2470. ], $bundle));
  2471. }
  2472. /**
  2473. * 登录页(手机号验证码 / 账号密码)
  2474. */
  2475. public function login()
  2476. {
  2477. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  2478. if ($this->mprocGetUser()) {
  2479. $this->redirect($this->mprocBuildAfterLoginIndexUrl($redirect));
  2480. }
  2481. if ($redirect !== '') {
  2482. Session::set('mproc_intended_url', $redirect);
  2483. }
  2484. $this->view->assign('mprocLoginRedirect', $redirect);
  2485. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  2486. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  2487. return $this->view->fetch();
  2488. }
  2489. /**
  2490. * 图形验证码(手机号登录用)
  2491. */
  2492. public function captcha($id = '')
  2493. {
  2494. $captcha = new Captcha((array)Config::get('captcha'));
  2495. return $captcha->entry($id);
  2496. }
  2497. /**
  2498. * 发送登录验证码(POST:phone、captcha)
  2499. */
  2500. public function sendSms()
  2501. {
  2502. if (!$this->request->isPost()) {
  2503. $this->error('请使用 POST');
  2504. }
  2505. $phone = trim((string)$this->request->post('phone', ''));
  2506. $captcha = trim((string)$this->request->post('captcha', ''));
  2507. if (!preg_match('/^1\d{10}$/', $phone)) {
  2508. $this->error('请输入正确的11位手机号');
  2509. }
  2510. if ($captcha === '') {
  2511. $this->error('请输入图形验证码');
  2512. }
  2513. if (!$this->mprocFindCustomerUserByMobile($phone)) {
  2514. $this->error('该手机号未开通或已禁用,请联系管理员');
  2515. }
  2516. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  2517. if (Cache::get('mproc_sms_wait_' . $phone)) {
  2518. $this->error('发送过于频繁,请稍后再试');
  2519. }
  2520. if (!Validate::is($captcha, 'captcha')) {
  2521. $this->error('图形验证码不正确');
  2522. }
  2523. $code = (string)random_int(100000, 999999);
  2524. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  2525. $ttl = max(60, min(600, $ttl));
  2526. Cache::set('mproc_code_' . $phone, $code, $ttl);
  2527. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  2528. try {
  2529. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  2530. if ($tpl === '') {
  2531. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  2532. }
  2533. $content = str_replace('{code}', $code, $tpl);
  2534. $this->mprocSmsSend($phone, $content);
  2535. } catch (\Exception $e) {
  2536. Cache::rm('mproc_code_' . $phone);
  2537. Cache::rm('mproc_sms_wait_' . $phone);
  2538. $this->error($e->getMessage());
  2539. }
  2540. $this->success('验证码已发送');
  2541. }
  2542. /**
  2543. * 验证码登录(POST:phone、code)
  2544. */
  2545. public function doLogin()
  2546. {
  2547. if (!$this->request->isPost()) {
  2548. $this->error('请使用 POST');
  2549. }
  2550. $phone = trim((string)$this->request->post('phone', ''));
  2551. $code = trim((string)$this->request->post('code', ''));
  2552. if (!preg_match('/^1\d{10}$/', $phone)) {
  2553. $this->error('手机号格式不正确');
  2554. }
  2555. if (!preg_match('/^\d{6}$/', $code)) {
  2556. $this->error('请输入6位验证码');
  2557. }
  2558. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2559. $mock = Config::get('mproc.mock_sms_code');
  2560. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2561. Cache::rm('mproc_code_' . $phone);
  2562. } else {
  2563. $cached = Cache::get('mproc_code_' . $phone);
  2564. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2565. $this->error('验证码错误或已过期');
  2566. }
  2567. Cache::rm('mproc_code_' . $phone);
  2568. }
  2569. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2570. if (!$cu) {
  2571. $this->error('该手机号未开通或已禁用,请联系管理员');
  2572. }
  2573. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2574. }
  2575. /**
  2576. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2577. */
  2578. public function mprocRestore()
  2579. {
  2580. if (!$this->request->isPost()) {
  2581. $this->error('请使用 POST');
  2582. }
  2583. $token = $this->mprocReadTokenFromRequest();
  2584. $user = null;
  2585. if ($token !== '') {
  2586. $user = $this->mprocLoadUserByToken($token);
  2587. }
  2588. if (!$user) {
  2589. $user = $this->mprocUserFromRememberCookie();
  2590. if ($user) {
  2591. $token = $this->mprocPackSignedAuthToken($user);
  2592. }
  2593. }
  2594. if (!$user) {
  2595. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2596. }
  2597. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2598. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2599. $jump = $this->mprocBuildAfterLoginIndexUrl($redirect);
  2600. $this->success('ok', $jump, [
  2601. 'mproc_token' => $token,
  2602. 'keep_hours' => $this->mprocKeepHours(),
  2603. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2604. ]);
  2605. }
  2606. /**
  2607. * 账号密码登录(POST:username、password)
  2608. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2609. */
  2610. public function doLoginPwd()
  2611. {
  2612. if (!$this->request->isPost()) {
  2613. $this->error('请使用 POST');
  2614. }
  2615. $username = trim((string)$this->request->post('username', ''));
  2616. $password = (string)$this->request->post('password', '');
  2617. if ($username === '' || $password === '') {
  2618. $this->error('请输入账号和密码');
  2619. }
  2620. $cu = $this->mprocFindCustomerUserByUsername($username);
  2621. if ($cu) {
  2622. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2623. $this->error('账号或密码错误');
  2624. }
  2625. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2626. }
  2627. // 管理员:表 admin
  2628. $row = null;
  2629. try {
  2630. $row = Db::name('admin')
  2631. ->field('id,username,password,salt,status,loginfailure,updatetime')
  2632. ->where('username', $username)
  2633. ->find();
  2634. } catch (\Throwable $e) {
  2635. $row = null;
  2636. }
  2637. if (!$row || !is_array($row)) {
  2638. $this->error('账号或密码错误');
  2639. }
  2640. $id = (int)($row['id'] ?? 0);
  2641. if (($row['status'] ?? '') == 'hidden') {
  2642. $this->error('该账号已禁用');
  2643. }
  2644. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  2645. $this->error('登录失败次数过多,请24小时后再试');
  2646. }
  2647. $salt = (string)($row['salt'] ?? '');
  2648. $hashStored = (string)($row['password'] ?? '');
  2649. $hashInput = md5(md5($password) . $salt);
  2650. if ($hashStored === '' || $hashInput !== $hashStored) {
  2651. if ($id > 0) {
  2652. try {
  2653. Db::name('admin')->where('id', $id)->update([
  2654. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  2655. 'updatetime' => time(),
  2656. ]);
  2657. } catch (\Throwable $e) {
  2658. }
  2659. }
  2660. $this->error('账号或密码错误');
  2661. }
  2662. if ($id > 0) {
  2663. try {
  2664. Db::name('admin')->where('id', $id)->update([
  2665. 'loginfailure' => 0,
  2666. 'updatetime' => time(),
  2667. ]);
  2668. } catch (\Throwable $e) {
  2669. }
  2670. }
  2671. $this->mprocFinishLogin([
  2672. 'phone' => trim((string)($row['mobile'] ?? '')),
  2673. 'company_name' => '',
  2674. 'username' => $username,
  2675. 'customer_user_id' => 0,
  2676. 'login_type' => 'pwd',
  2677. 'is_admin' => 1,
  2678. ]);
  2679. }
  2680. /**
  2681. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  2682. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  2683. */
  2684. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  2685. {
  2686. if (!empty($user['is_admin'])) {
  2687. return false;
  2688. }
  2689. $sn = trim((string)($row['status_name'] ?? ''));
  2690. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2691. return false;
  2692. }
  2693. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  2694. return false;
  2695. }
  2696. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  2697. return false;
  2698. }
  2699. $uCo = trim((string)($user['company_name'] ?? ''));
  2700. if ($uCo === '') {
  2701. $uPhone = trim((string)($user['phone'] ?? ''));
  2702. if ($uPhone !== '') {
  2703. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  2704. }
  2705. }
  2706. $rCo = trim((string)($row['company_name'] ?? ''));
  2707. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  2708. return true;
  2709. }
  2710. $uPhone = trim((string)($user['phone'] ?? ''));
  2711. $rPhone = trim((string)($row['phone'] ?? ''));
  2712. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  2713. }
  2714. /**
  2715. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  2716. *
  2717. * @param array<string, mixed> $detailRow
  2718. */
  2719. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  2720. {
  2721. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  2722. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  2723. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  2724. try {
  2725. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2726. } catch (\Throwable $e) {
  2727. $po = null;
  2728. }
  2729. if (is_array($po)) {
  2730. $pl = array_change_key_case($po, CASE_LOWER);
  2731. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  2732. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  2733. $raw = trim((string)$pl[$ck]);
  2734. break;
  2735. }
  2736. }
  2737. if ($raw === '') {
  2738. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  2739. }
  2740. }
  2741. }
  2742. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  2743. return null;
  2744. }
  2745. return (float)$raw;
  2746. }
  2747. protected function mprocFormatCeilingPriceDisplay(float $n): string
  2748. {
  2749. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  2750. return $s === '' ? '0' : $s;
  2751. }
  2752. /**
  2753. * 确保 purchase_order_detail.lead_days 字段存在
  2754. */
  2755. protected function mprocEnsureLeadDaysColumn(): void
  2756. {
  2757. static $done = false;
  2758. if ($done) {
  2759. return;
  2760. }
  2761. $done = true;
  2762. try {
  2763. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  2764. if (empty($cols)) {
  2765. Db::execute(
  2766. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  2767. );
  2768. }
  2769. } catch (\Throwable $e) {
  2770. // 忽略:保存时再按列是否存在处理
  2771. }
  2772. }
  2773. /**
  2774. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  2775. */
  2776. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  2777. {
  2778. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  2779. return null;
  2780. }
  2781. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2782. $t2 = strtotime($m[1] . ' 00:00:00');
  2783. if ($t1 === false || $t2 === false) {
  2784. return null;
  2785. }
  2786. return (int)round(($t2 - $t1) / 86400);
  2787. }
  2788. protected function mprocAddDaysToToday(int $days): string
  2789. {
  2790. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  2791. if ($base === false) {
  2792. $base = time();
  2793. }
  2794. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  2795. }
  2796. /**
  2797. * @param array<string, mixed> $row
  2798. */
  2799. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  2800. {
  2801. $days = null;
  2802. $raw = $row['lead_days'] ?? null;
  2803. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  2804. $days = max(0, (int)$raw);
  2805. } else {
  2806. $dd = trim((string)($row['delivery_display'] ?? ''));
  2807. if ($dd === '') {
  2808. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2809. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2810. $dd = $m[1];
  2811. }
  2812. }
  2813. if ($dd !== '') {
  2814. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  2815. if ($calc !== null) {
  2816. $days = max(0, $calc);
  2817. }
  2818. }
  2819. }
  2820. if ($days !== null) {
  2821. $row['lead_days'] = $days;
  2822. $row['lead_days_display'] = (string)$days;
  2823. $row['lead_days_missing'] = 0;
  2824. } else {
  2825. $row['lead_days'] = '';
  2826. $row['lead_days_display'] = '';
  2827. $row['lead_days_missing'] = 1;
  2828. }
  2829. }
  2830. /**
  2831. * 保存单条协助明细的金额、交期、工期(内部)
  2832. *
  2833. * @param array<string, mixed> $user
  2834. * @param int $id
  2835. * @param string $amountRaw
  2836. * @param string $deliveryRaw
  2837. * @param string|int|null $leadDaysRaw
  2838. * @return string 工序名(用于批量错误提示)
  2839. */
  2840. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  2841. {
  2842. if ($id <= 0) {
  2843. throw new \InvalidArgumentException('参数错误');
  2844. }
  2845. $row = null;
  2846. try {
  2847. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  2848. if (!$row) {
  2849. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  2850. }
  2851. } catch (\Throwable $e) {
  2852. $row = null;
  2853. }
  2854. if (!$row || !is_array($row)) {
  2855. throw new \InvalidArgumentException('记录不存在');
  2856. }
  2857. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  2858. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2859. $po = null;
  2860. if ($this->mprocIsValidScydgyRowId($sid)) {
  2861. try {
  2862. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2863. } catch (\Throwable $e) {
  2864. $po = null;
  2865. }
  2866. if (is_array($po)) {
  2867. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  2868. if ($gymc === '') {
  2869. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2870. }
  2871. }
  2872. }
  2873. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  2874. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  2875. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  2876. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  2877. }
  2878. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  2879. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  2880. if (!empty($user['is_admin'])) {
  2881. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  2882. }
  2883. // 截止后 / 已开标 canEdit=false,统一给明确文案
  2884. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  2885. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  2886. }
  2887. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  2888. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  2889. }
  2890. throw new \InvalidArgumentException($label . '无权修改');
  2891. }
  2892. $this->mprocEnsureLeadDaysColumn();
  2893. $amountRaw = trim($amountRaw);
  2894. $deliveryRaw = trim($deliveryRaw);
  2895. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  2896. $hasAmt = $amountRaw !== '';
  2897. $hasLead = $leadRaw !== '';
  2898. $hasDel = $deliveryRaw !== '';
  2899. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  2900. if ($filledCount === 0) {
  2901. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  2902. }
  2903. if ($filledCount < 3) {
  2904. if (!$hasAmt) {
  2905. throw new \InvalidArgumentException($label . '请填写单价');
  2906. }
  2907. if (!$hasLead) {
  2908. throw new \InvalidArgumentException($label . '请填写工期');
  2909. }
  2910. throw new \InvalidArgumentException($label . '请填写交期');
  2911. }
  2912. $leadDays = null;
  2913. if ($leadRaw !== '') {
  2914. if (!preg_match('/^\d+$/', $leadRaw)) {
  2915. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  2916. }
  2917. $leadDays = (int)$leadRaw;
  2918. }
  2919. $data = [];
  2920. if ($amountRaw === '') {
  2921. $data['amount'] = null;
  2922. } else {
  2923. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  2924. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  2925. }
  2926. if ((float)$amountRaw <= 0) {
  2927. throw new \InvalidArgumentException($label . '单价必须大于0');
  2928. }
  2929. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  2930. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  2931. throw new \InvalidArgumentException(
  2932. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  2933. );
  2934. }
  2935. $data['amount'] = $amountRaw;
  2936. }
  2937. if ($deliveryRaw === '') {
  2938. $data['delivery'] = null;
  2939. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  2940. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2941. $timePart = date('H:i:s');
  2942. if ($existingDel !== '') {
  2943. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  2944. if ($tsEx !== false) {
  2945. $hms = date('H:i:s', $tsEx);
  2946. if ($hms !== '00:00:00') {
  2947. $timePart = $hms;
  2948. }
  2949. }
  2950. }
  2951. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  2952. } else {
  2953. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  2954. $ts = strtotime($deliveryRaw);
  2955. if ($ts === false) {
  2956. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  2957. }
  2958. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  2959. }
  2960. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  2961. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  2962. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  2963. }
  2964. if ($leadDays === null && !empty($data['delivery'])) {
  2965. $ymd = substr((string)$data['delivery'], 0, 10);
  2966. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  2967. if ($calc !== null) {
  2968. $leadDays = max(0, $calc);
  2969. }
  2970. }
  2971. $data['lead_days'] = $leadDays;
  2972. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  2973. if ($dcCol !== null && array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  2974. $data[$dcCol] = date('Y-m-d H:i:s');
  2975. }
  2976. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  2977. if ($upCol !== null) {
  2978. $data[$upCol] = date('Y-m-d H:i:s');
  2979. }
  2980. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2981. if ($statusNameCol !== null) {
  2982. $curSn = '';
  2983. foreach ($row as $k => $v) {
  2984. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  2985. $curSn = trim((string)$v);
  2986. break;
  2987. }
  2988. }
  2989. if ($curSn !== '已完成') {
  2990. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  2991. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  2992. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  2993. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  2994. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2995. }
  2996. }
  2997. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  2998. $pkVal = (int)($row[$pkField] ?? $id);
  2999. try {
  3000. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3001. } catch (\Throwable $e) {
  3002. $msg = $e->getMessage();
  3003. if (stripos($msg, 'Unknown column') !== false) {
  3004. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3005. }
  3006. throw new \RuntimeException('保存失败:' . $msg);
  3007. }
  3008. if ($aff === false) {
  3009. throw new \RuntimeException($label . '保存失败');
  3010. }
  3011. return $gymc;
  3012. }
  3013. /**
  3014. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3015. *
  3016. * @param array<string, mixed> $user
  3017. * @param int[] $detailIds 本次保存涉及的明细 ID
  3018. * @param string $remarkRaw
  3019. */
  3020. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3021. {
  3022. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3023. if ($remarkCol === null) {
  3024. return;
  3025. }
  3026. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3027. if ($detailIds === []) {
  3028. return;
  3029. }
  3030. $anchorId = $detailIds[0];
  3031. $row = null;
  3032. try {
  3033. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3034. if (!$row) {
  3035. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3036. }
  3037. } catch (\Throwable $e) {
  3038. $row = null;
  3039. }
  3040. if (!$row || !is_array($row)) {
  3041. throw new \InvalidArgumentException('记录不存在');
  3042. }
  3043. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3044. $po = null;
  3045. if ($this->mprocIsValidScydgyRowId($sid)) {
  3046. try {
  3047. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3048. } catch (\Throwable $e) {
  3049. $po = null;
  3050. }
  3051. if (is_array($po)) {
  3052. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3053. }
  3054. }
  3055. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3056. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3057. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3058. }
  3059. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3060. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3061. if (!empty($user['is_admin'])) {
  3062. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3063. }
  3064. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3065. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3066. }
  3067. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3068. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3069. }
  3070. throw new \InvalidArgumentException('无权修改备注');
  3071. }
  3072. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3073. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3074. if ($ccydhCol === null || $companyCol === null) {
  3075. return;
  3076. }
  3077. $ccydh = '';
  3078. $company = '';
  3079. foreach ($row as $k => $v) {
  3080. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3081. $ccydh = trim((string)$v);
  3082. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3083. $company = trim((string)$v);
  3084. }
  3085. }
  3086. if ($ccydh === '' || $company === '') {
  3087. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3088. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3089. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3090. if ($upCol !== null) {
  3091. $data[$upCol] = date('Y-m-d H:i:s');
  3092. }
  3093. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3094. return;
  3095. }
  3096. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3097. $data = [$remarkCol => $remarkVal];
  3098. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3099. if ($upCol !== null) {
  3100. $data[$upCol] = date('Y-m-d H:i:s');
  3101. }
  3102. $query = Db::table('purchase_order_detail')
  3103. ->where($ccydhCol, $ccydh)
  3104. ->where($companyCol, $company);
  3105. $userWhere = $this->mprocListWhereForLoginUser($user);
  3106. if ($userWhere !== []) {
  3107. $query->where($userWhere);
  3108. }
  3109. try {
  3110. $query->update($data);
  3111. } catch (\Throwable $e) {
  3112. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3113. }
  3114. }
  3115. /**
  3116. * 保存协助明细金额、交期、工期
  3117. * 单条:POST id、amount、delivery、lead_days
  3118. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3119. */
  3120. public function mprocSave()
  3121. {
  3122. if (!$this->request->isPost()) {
  3123. $this->error('请使用 POST');
  3124. }
  3125. $user = $this->mprocGetUser();
  3126. if (!$user) {
  3127. $this->error('请先登录', url('index/index/login'));
  3128. }
  3129. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3130. $itemsRaw = $this->request->post('items', '', null);
  3131. if ($itemsRaw === '' || $itemsRaw === null) {
  3132. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3133. }
  3134. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3135. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3136. }
  3137. $items = [];
  3138. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3139. $decoded = json_decode($itemsRaw, true);
  3140. if (!is_array($decoded)) {
  3141. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3142. }
  3143. if (is_array($decoded)) {
  3144. $items = $decoded;
  3145. }
  3146. } elseif (is_array($itemsRaw)) {
  3147. $items = $itemsRaw;
  3148. }
  3149. if ($items === []) {
  3150. $id = (int)$this->request->post('id', 0, null);
  3151. if ($id <= 0) {
  3152. $this->error('保存失败,请关闭弹窗后重试');
  3153. }
  3154. $items = [[
  3155. 'id' => $id,
  3156. 'amount' => (string)$this->request->post('amount', '', null),
  3157. 'delivery' => (string)$this->request->post('delivery', '', null),
  3158. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3159. ]];
  3160. }
  3161. $saved = 0;
  3162. $savedIds = [];
  3163. $remarkRaw = $this->request->post('remark', '', null);
  3164. if ($remarkRaw === '' || $remarkRaw === null) {
  3165. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3166. }
  3167. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3168. Db::startTrans();
  3169. try {
  3170. foreach ($items as $it) {
  3171. if (!is_array($it)) {
  3172. continue;
  3173. }
  3174. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3175. if ($id <= 0) {
  3176. continue;
  3177. }
  3178. $delivery = (string)($it['delivery'] ?? '');
  3179. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3180. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3181. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3182. }
  3183. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3184. $amount = trim((string)($it['amount'] ?? ''));
  3185. $leadDays = trim($leadDays);
  3186. $delivery = trim($delivery);
  3187. // 全空工序跳过:多工序时允许只保存已填全的
  3188. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3189. continue;
  3190. }
  3191. $this->mprocSaveDetailQuote(
  3192. $user,
  3193. $id,
  3194. $amount,
  3195. $delivery,
  3196. $leadDays
  3197. );
  3198. $saved++;
  3199. $savedIds[] = $id;
  3200. }
  3201. if ($saved < 1) {
  3202. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3203. }
  3204. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3205. Db::commit();
  3206. } catch (\InvalidArgumentException $e) {
  3207. Db::rollback();
  3208. $this->error($e->getMessage());
  3209. } catch (\Throwable $e) {
  3210. Db::rollback();
  3211. $this->error($e->getMessage());
  3212. }
  3213. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3214. }
  3215. /**
  3216. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  3217. */
  3218. public function mprocChangePwd()
  3219. {
  3220. if (!$this->request->isPost()) {
  3221. $this->error('请使用 POST');
  3222. }
  3223. $user = $this->mprocGetUser();
  3224. if (!$user) {
  3225. $this->error('请先登录', url('index/index/login'));
  3226. }
  3227. $user = $this->mprocSyncSessionCustomerUser($user);
  3228. if (!empty($user['is_admin'])) {
  3229. $this->error('当前账号不支持修改密码');
  3230. }
  3231. $cu = $this->mprocResolveCustomerUserForSession($user);
  3232. if (!$cu) {
  3233. $this->error('账号不存在或已禁用');
  3234. }
  3235. $oldPwd = (string)$this->request->post('old_password', '');
  3236. $newPwd = (string)$this->request->post('new_password', '');
  3237. $renewPwd = (string)$this->request->post('renew_password', '');
  3238. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3239. $this->error('请填写完整');
  3240. }
  3241. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3242. if ($pwdErr !== '') {
  3243. $this->error($pwdErr);
  3244. }
  3245. if ($newPwd !== $renewPwd) {
  3246. $this->error('两次输入的新密码不一致');
  3247. }
  3248. if ($oldPwd === $newPwd) {
  3249. $this->error('新密码不能与旧密码相同');
  3250. }
  3251. $cuId = (int)($cu['id'] ?? 0);
  3252. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3253. $this->error('原密码不正确');
  3254. }
  3255. $data = [
  3256. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3257. 'updatetime' => date('Y-m-d H:i:s'),
  3258. ];
  3259. try {
  3260. Db::table('customer')->where('id', $cuId)->update($data);
  3261. } catch (\Throwable $e) {
  3262. $this->error('修改失败:' . $e->getMessage());
  3263. }
  3264. // 改密后强制重新登录
  3265. $token = Session::get('mproc_token');
  3266. if ($token === null || $token === '') {
  3267. $token = Cookie::get('mproc_token');
  3268. }
  3269. $this->mprocClearLogin(preg_replace('/[^a-f0-9]/i', '', (string)$token));
  3270. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3271. }
  3272. /**
  3273. * 退出登录
  3274. */
  3275. public function logout()
  3276. {
  3277. $token = Session::get('mproc_token');
  3278. if ($token === null || $token === '') {
  3279. $token = Cookie::get('mproc_token');
  3280. }
  3281. if ($token) {
  3282. $this->mprocClearLogin(preg_replace('/[^a-f0-9]/i', '', (string)$token));
  3283. }
  3284. $this->redirect(url('index/index/login'));
  3285. }
  3286. /**
  3287. * 短信宝(与后台协助审核一致,便于复用账号)
  3288. *
  3289. * @throws \Exception
  3290. */
  3291. protected function mprocSmsSend($phone, $content)
  3292. {
  3293. $statusStr = [
  3294. '0' => '短信发送成功',
  3295. '-1' => '参数不全',
  3296. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3297. '30' => '密码错误',
  3298. '40' => '账号不存在',
  3299. '41' => '余额不足',
  3300. '42' => '帐户已过期',
  3301. '43' => 'IP地址限制',
  3302. '50' => '内容含有敏感词',
  3303. ];
  3304. $smsapi = 'http://api.smsbao.com/';
  3305. $user = trim((string)Config::get('mproc.smsbao_user'));
  3306. if ($user === '') {
  3307. $user = 'zhuwei123';
  3308. }
  3309. $passPlain = Config::get('mproc.smsbao_pass');
  3310. $pass = ($passPlain !== null && $passPlain !== '')
  3311. ? md5((string)$passPlain)
  3312. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3313. $phone = trim((string)$phone);
  3314. $content = trim((string)$content);
  3315. if ($phone === '' || $content === '') {
  3316. throw new \Exception('短信发送失败:参数不全');
  3317. }
  3318. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3319. $result = @file_get_contents($sendurl);
  3320. if ($result === false) {
  3321. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3322. throw new \Exception('短信发送失败:网络异常');
  3323. }
  3324. $result = trim((string)$result);
  3325. if ($result !== '0') {
  3326. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3327. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3328. throw new \Exception('短信发送失败:' . $msg);
  3329. }
  3330. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3331. }
  3332. }