| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371 |
- <?php
- namespace app\index\controller;
- use app\common\controller\Frontend;
- use app\common\library\ProcuremenStatus;
- use think\Cache;
- use think\captcha\Captcha;
- use think\Config;
- use think\Cookie;
- use think\Db;
- use think\Log;
- use think\Session;
- use think\Validate;
- /**
- * 手机端:协助明细(purchase_order_detail)验证码 / 账号密码登录 + 列表
- * 普通用户(customer):登录后进报价列表,可填单价/交期
- * 管理员(admin):登录后进「质量评分」,对订单评合格/不合格、客户投诉、订单中断
- */
- class Index extends Frontend
- {
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- protected $layout = '';
- /** @var int 登录态有效天数 */
- protected $mprocTtlSeconds = 0;
- /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
- protected static $mprocProcuremenColumns = null;
- public function _initialize()
- {
- parent::_initialize();
- if (is_file(APP_PATH . 'extra/mproc.php')) {
- Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
- }
- $hours = (int)Config::get('mproc.session_hours');
- if ($hours > 0) {
- $this->mprocTtlSeconds = max(1, min(720, $hours)) * 3600;
- } else {
- $days = (int)(Config::get('mproc.session_days') ?: 3);
- $days = max(1, min(30, $days));
- $this->mprocTtlSeconds = $days * 86400;
- }
- if (PHP_VERSION_ID >= 70300) {
- ini_set('session.cookie_lifetime', (string)$this->mprocTtlSeconds);
- ini_set('session.gc_maxlifetime', (string)$this->mprocTtlSeconds);
- }
- }
- /** 登录有效小时数(用于前端 localStorage 过期时间) */
- protected function mprocKeepHours(): int
- {
- return max(1, (int)round($this->mprocTtlSeconds / 3600));
- }
- /**
- * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
- */
- protected function mprocGetUser()
- {
- $token = $this->mprocReadTokenFromRequest();
- if ($token !== '') {
- $user = $this->mprocLoadUserByToken($token);
- if ($user) {
- $token = $this->mprocTouchLoginState($user, $token);
- $user['token'] = $token;
- return $user;
- }
- }
- $user = $this->mprocUserFromRememberCookie();
- if (!$user) {
- return null;
- }
- $token = $this->mprocPackSignedAuthToken($user);
- $token = $this->mprocTouchLoginState($user, $token);
- $user['token'] = $token;
- return $user;
- }
- protected function mprocReadTokenFromRequest(): string
- {
- $token = Session::get('mproc_token');
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_token');
- }
- if ($token === null || $token === '') {
- $token = $this->request->header('X-Mproc-Token');
- }
- if ($token === null || $token === '') {
- $token = $this->request->request('mproc_token', '');
- }
- $token = trim((string)$token);
- if ($token === '') {
- return '';
- }
- if ($this->mprocIsSignedAuthToken($token)) {
- return $token;
- }
- $token = preg_replace('/[^a-f0-9]/i', '', $token);
- return strlen($token) >= 16 ? $token : '';
- }
- protected function mprocIsSignedAuthToken(string $token): bool
- {
- return strpos($token, '.') !== false
- && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
- }
- protected function mprocAuthCacheKey(string $token): string
- {
- return 'mproc_u_' . md5($token);
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocLoadUserByToken(string $token): ?array
- {
- if ($this->mprocIsSignedAuthToken($token)) {
- if ($this->mprocIsAuthTokenRevoked($token)) {
- return null;
- }
- $user = $this->mprocUserFromSignedToken($token);
- if (!$user) {
- return null;
- }
- if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
- $this->mprocClearLogin($token);
- return null;
- }
- $user['token'] = $token;
- return $user;
- }
- $user = Cache::get('mproc_u_' . $token);
- if (!is_array($user)) {
- $user = $this->mprocUserFromRememberCookie();
- if (!$user) {
- return null;
- }
- }
- if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
- return null;
- }
- if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
- $this->mprocClearLogin($token);
- return null;
- }
- $user['token'] = $token;
- return $user;
- }
- /**
- * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
- *
- * @param array<string, mixed> $user
- */
- protected function mprocTouchLoginState(array $user, string $token): string
- {
- $user['login_time'] = time();
- if ($this->mprocIsSignedAuthToken($token)) {
- $token = $this->mprocPackSignedAuthToken($user);
- }
- Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
- if (!$this->mprocIsSignedAuthToken($token)) {
- Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
- }
- Session::set('mproc_token', $token);
- $this->mprocSetTokenCookie($token);
- $this->mprocSetRememberCookie($user, $token);
- return $token;
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocCookieOptions(): array
- {
- $opts = [
- 'expire' => $this->mprocTtlSeconds,
- 'path' => '/',
- 'httponly' => true,
- ];
- if ($this->request->isSsl()) {
- $opts['secure'] = true;
- }
- if (PHP_VERSION_ID >= 70300) {
- $opts['samesite'] = 'Lax';
- }
- return $opts;
- }
- protected function mprocSetTokenCookie(string $token): void
- {
- Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
- }
- /**
- * @param array<string, mixed> $user
- */
- protected function mprocSetRememberCookie(array $user, ?string $token = null): void
- {
- $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
- Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
- }
- protected function mprocAuthSignSecret(): string
- {
- $key = trim((string)Config::get('mproc.auth_sign_key'));
- if ($key === '') {
- $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
- }
- return hash('sha256', $key);
- }
- /**
- * @param array<string, mixed> $user
- */
- protected function mprocPackSignedAuthToken(array $user): string
- {
- $payload = [
- 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
- 'phone' => trim((string)($user['phone'] ?? '')),
- 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
- 'admin' => !empty($user['is_admin']) ? 1 : 0,
- 'lt' => time(),
- ];
- $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
- $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
- return $b64 . '.' . $sig;
- }
- /** @deprecated 使用 mprocPackSignedAuthToken */
- protected function mprocPackRememberCookie(array $user): string
- {
- return $this->mprocPackSignedAuthToken($user);
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocUserFromSignedToken(string $raw): ?array
- {
- $parts = explode('.', trim($raw), 2);
- if (count($parts) !== 2) {
- return null;
- }
- $b64 = $parts[0];
- $sig = $parts[1];
- if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
- return null;
- }
- $pad = strlen($b64) % 4;
- if ($pad > 0) {
- $b64 .= str_repeat('=', 4 - $pad);
- }
- $json = base64_decode(strtr($b64, '-_', '+/'), true);
- if ($json === false || $json === '') {
- return null;
- }
- $payload = json_decode($json, true);
- if (!is_array($payload)) {
- return null;
- }
- $lt = (int)($payload['lt'] ?? 0);
- if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
- return null;
- }
- return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocUserFromRememberCookie(): ?array
- {
- $raw = Cookie::get('mproc_remember');
- if ($raw === null || $raw === '') {
- $raw = Cookie::get('mproc_token');
- }
- if ($raw === null || $raw === '') {
- return null;
- }
- $raw = (string)$raw;
- if ($this->mprocIsAuthTokenRevoked($raw)) {
- return null;
- }
- return $this->mprocUserFromSignedToken($raw);
- }
- /**
- * @param array<string, mixed> $payload
- * @return array<string, mixed>|null
- */
- protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
- {
- if (!empty($payload['admin'])) {
- $uname = trim((string)($payload['uname'] ?? ''));
- if ($uname === '') {
- return null;
- }
- try {
- $row = Db::name('admin')->where('username', $uname)->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
- return null;
- }
- return [
- 'phone' => trim((string)($row['mobile'] ?? '')),
- 'company_name' => '',
- 'username' => $uname,
- 'customer_user_id' => 0,
- 'admin_id' => (int)($row['id'] ?? 0),
- 'login_type' => 'remember',
- 'is_admin' => 1,
- 'login_time' => $loginTime,
- ];
- }
- $cid = (int)($payload['uid'] ?? 0);
- if ($cid > 0) {
- try {
- $cu = Db::table('customer')->where('id', $cid)->find();
- } catch (\Throwable $e) {
- $cu = null;
- }
- if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
- $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
- $user['login_time'] = $loginTime;
- return $user;
- }
- }
- $phone = trim((string)($payload['phone'] ?? ''));
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- $cu = $this->mprocFindCustomerUserByMobile($phone);
- if ($cu) {
- $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
- $user['login_time'] = $loginTime;
- return $user;
- }
- }
- return null;
- }
- protected function mprocAuthRevokeCacheKey(string $token): string
- {
- return 'mproc_revoked_' . md5($token);
- }
- protected function mprocRevokeAuthToken(string $token): void
- {
- $token = trim($token);
- if ($token === '') {
- return;
- }
- try {
- Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
- } catch (\Throwable $e) {
- }
- }
- protected function mprocIsAuthTokenRevoked(string $token): bool
- {
- $token = trim($token);
- if ($token === '') {
- return false;
- }
- try {
- return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
- } catch (\Throwable $e) {
- return false;
- }
- }
- /**
- * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
- */
- protected function mprocExpireAuthCookies(): void
- {
- $opts = $this->mprocCookieOptions();
- $opts['expire'] = -3600;
- try {
- Cookie::set('mproc_token', '', $opts);
- Cookie::set('mproc_remember', '', $opts);
- } catch (\Throwable $e) {
- }
- try {
- Cookie::delete('mproc_token');
- Cookie::delete('mproc_remember');
- } catch (\Throwable $e) {
- }
- unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
- $prefix = (string)Config::get('cookie.prefix');
- if ($prefix !== '') {
- unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
- }
- }
- protected function mprocClearLogin($token)
- {
- $token = trim((string)($token ?? ''));
- if ($token !== '') {
- $this->mprocRevokeAuthToken($token);
- try {
- Cache::rm($this->mprocAuthCacheKey($token));
- } catch (\Throwable $e) {
- }
- if (!$this->mprocIsSignedAuthToken($token)) {
- try {
- Cache::rm('mproc_u_' . $token);
- } catch (\Throwable $e) {
- }
- }
- }
- // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
- foreach (['mproc_token', 'mproc_remember'] as $ck) {
- $raw = Cookie::get($ck);
- if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
- $this->mprocRevokeAuthToken((string)$raw);
- }
- }
- Session::delete('mproc_token');
- $this->mprocExpireAuthCookies();
- }
- /**
- * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
- *
- * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
- */
- protected function mprocSanitizeRedirectUrl($raw)
- {
- $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
- if ($s === '') {
- return '';
- }
- if (preg_match('#^https?://#i', $s)) {
- $h = parse_url($s, PHP_URL_HOST);
- if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
- return '';
- }
- $path = parse_url($s, PHP_URL_PATH);
- $query = parse_url($s, PHP_URL_QUERY);
- $s = (is_string($path) && $path !== '' ? $path : '/');
- if (is_string($query) && $query !== '') {
- $s .= '?' . $query;
- }
- }
- if (strpos($s, '://') !== false) {
- return '';
- }
- if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
- return '';
- }
- if ($s[0] !== '/') {
- $s = '/' . ltrim($s, '/');
- }
- if (strpos($s, '//') === 0) {
- return '';
- }
- $okHome = stripos($s, 'index/index/index') !== false;
- $okInbound = stripos($s, 'index/index/inboundscore') !== false;
- if (!$okHome && !$okInbound) {
- return '';
- }
- if (stripos($s, 'index/index/login') !== false) {
- return '';
- }
- return $s;
- }
- protected function mprocRememberFocusEid(int $focusEid): void
- {
- if ($focusEid > 0) {
- Session::set('mproc_focus_eid', $focusEid);
- }
- }
- protected function mprocPullSessionFocusEid(): int
- {
- $fe = (int)Session::get('mproc_focus_eid', 0);
- if ($fe > 0) {
- Session::delete('mproc_focus_eid');
- }
- return $fe;
- }
- /**
- * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &focus_eid 拼进上一参数值的情况)
- */
- protected function mprocParseFocusEidFromUriString(string $uri): int
- {
- if ($uri === '' || stripos($uri, 'focus_eid') === false) {
- return 0;
- }
- if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
- return (int)$m[1];
- }
- $query = parse_url($uri, PHP_URL_QUERY);
- if (!is_string($query) || $query === '') {
- return 0;
- }
- $q = [];
- parse_str($query, $q);
- if (!is_array($q)) {
- return 0;
- }
- if (isset($q['focus_eid'])) {
- $fe = (int)$q['focus_eid'];
- if ($fe > 0) {
- return $fe;
- }
- }
- foreach ($q as $k => $v) {
- $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
- if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
- return (int)$m2[1];
- }
- }
- return 0;
- }
- /**
- * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
- */
- protected function mprocReadFocusEidFromRequest(): int
- {
- $fe = (int)$this->request->param('focus_eid', 0);
- if ($fe > 0) {
- $this->mprocRememberFocusEid($fe);
- return $fe;
- }
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $fe = $this->mprocParseFocusEidFromUriString($uri);
- if ($fe > 0) {
- $this->mprocRememberFocusEid($fe);
- return $fe;
- }
- $fe = (int)Session::get('mproc_focus_eid', 0);
- if ($fe > 0) {
- return $fe;
- }
- return 0;
- }
- /**
- * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
- *
- * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
- */
- protected function mprocBuildLoginUrl($redirectPath = '')
- {
- $root = rtrim($this->request->root(), '/');
- $path = '/index/index/login';
- $rp = trim((string)$redirectPath);
- if ($rp === '') {
- return $root . $path;
- }
- return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
- }
- /**
- * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
- *
- * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
- */
- protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
- {
- $raw = trim((string)$redirectPathOrUrl);
- if ($raw === '') {
- return url('index/index/index', '', '', true);
- }
- $queryStr = '';
- if (preg_match('#^https?://#i', $raw)) {
- $pq = parse_url($raw);
- $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
- } elseif (isset($raw[0]) && $raw[0] === '/') {
- $pq = parse_url('http://127.0.0.1' . $raw);
- $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
- } else {
- $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
- $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
- }
- $q = [];
- if ($queryStr !== '') {
- parse_str($queryStr, $q);
- if (!is_array($q)) {
- $q = [];
- }
- }
- $allowed = [];
- $fe = 0;
- if (isset($q['focus_eid'])) {
- $fe = (int)$q['focus_eid'];
- }
- if ($fe <= 0) {
- $fe = $this->mprocParseFocusEidFromUriString($raw);
- }
- if ($fe <= 0) {
- $fe = (int)Session::get('mproc_focus_eid', 0);
- }
- if ($fe > 0) {
- $allowed['focus_eid'] = $fe;
- $this->mprocRememberFocusEid($fe);
- }
- $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
- if ($mt === 'me' || $mt === 'orders') {
- $allowed['main_tab'] = $mt;
- }
- $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
- if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
- $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
- }
- if (isset($q['q']) && trim((string)$q['q']) !== '') {
- $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
- }
- if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
- $allowed['main_tab'] = 'orders';
- }
- $base = rtrim($this->request->root(true), '/');
- $path = '/index/index/index';
- if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
- $fe = (int)$allowed['focus_eid'];
- if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
- return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
- }
- $ordered = ['focus_eid' => $fe];
- if (isset($allowed['tab'])) {
- $ordered['tab'] = $allowed['tab'];
- }
- if (isset($allowed['main_tab'])) {
- $ordered['main_tab'] = $allowed['main_tab'];
- }
- return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
- }
- $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
- return $base . $path . $qs;
- }
- /**
- * 按登录身份决定首页:供应商→报价列表;管理员→质量评分
- *
- * @param array<string, mixed> $user
- * @param string $redirectPathOrUrl
- */
- protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
- {
- if (!empty($user['is_admin'])) {
- $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
- if ($raw !== '' && stripos($raw, 'inboundscore') !== false) {
- $base = rtrim($this->request->root(true), '/');
- $path = parse_url($raw, PHP_URL_PATH);
- $query = parse_url($raw, PHP_URL_QUERY);
- if (!is_string($path) || $path === '') {
- return url('index/index/inboundscore', '', '', true);
- }
- if (stripos($path, 'inboundscore') === false) {
- return url('index/index/inboundscore', '', '', true);
- }
- return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
- }
- return url('index/index/inboundscore', '', '', true);
- }
- return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
- }
- /**
- * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
- *
- * @param string[] $candidatesLower 如 ['status','istatus']
- * @return string|null
- */
- protected function mprocResolveProcuremenColumn(array $candidatesLower)
- {
- if (self::$mprocProcuremenColumns === null) {
- self::$mprocProcuremenColumns = [];
- try {
- $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
- if (is_array($rows)) {
- foreach ($rows as $c) {
- $name = isset($c['Field']) ? (string)$c['Field'] : '';
- if ($name !== '') {
- self::$mprocProcuremenColumns[strtolower($name)] = $name;
- }
- }
- }
- } catch (\Throwable $e) {
- self::$mprocProcuremenColumns = [];
- }
- }
- foreach ($candidatesLower as $low) {
- $k = strtolower((string)$low);
- if (isset(self::$mprocProcuremenColumns[$k])) {
- return self::$mprocProcuremenColumns[$k];
- }
- }
- return null;
- }
- /**
- * 供应商整单备注(purchase_order_detail.remark)
- *
- * @param array<string, mixed> $row
- */
- protected function mprocResolveDetailRemark(array $row): string
- {
- $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
- if ($col === null) {
- return '';
- }
- foreach ($row as $k => $v) {
- if (strcasecmp((string)$k, $col) === 0) {
- return trim((string)$v);
- }
- }
- return '';
- }
- /**
- * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
- *
- * @return array|callable 可直接 $query->where(...);空数组表示不加条件
- */
- protected function mprocListWhereForLoginUser(array $user)
- {
- if (!empty($user['is_admin'])) {
- return [];
- }
- $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
- $pCol = $this->mprocResolveProcuremenColumn(['phone']);
- if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
- return ['id' => 0];
- }
- $cn = trim((string)($user['company_name'] ?? ''));
- $phone = trim((string)($user['phone'] ?? ''));
- if ($cn === '' && $phone !== '') {
- $cn = $this->mprocResolveCompanyForLoginPhone($phone);
- }
- if ($cn === '' && $phone === '') {
- return ['id' => 0];
- }
- return function ($q) use ($cCol, $pCol, $cn, $phone) {
- $first = true;
- if ($cCol !== null && $cCol !== '' && $cn !== '') {
- $q->where($cCol, $cn);
- $first = false;
- }
- if ($pCol !== null && $pCol !== '' && $phone !== '') {
- if ($first) {
- $q->where($pCol, $phone);
- } else {
- $q->whereOr($pCol, $phone);
- }
- }
- if ($first) {
- $q->where('id', 0);
- }
- };
- }
- /**
- * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
- */
- protected function mprocCustomerUserActive(array $row): bool
- {
- $st = $row['status'] ?? '';
- if ($st === '' || $st === null) {
- return true;
- }
- return $st === 1 || $st === '1';
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerUserByMobile(string $phone): ?array
- {
- return $this->mprocFindCustomerRowByPhone($phone);
- }
- /**
- * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
- *
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerUserByUsername(string $username): ?array
- {
- $username = trim($username);
- if ($username === '') {
- return null;
- }
- try {
- $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
- $row = $this->mprocFindCustomerRowByPhone($username);
- }
- if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
- return null;
- }
- return $row;
- }
- /**
- * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
- */
- protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
- {
- $stored = (string)($row['password'] ?? '');
- if ($stored === '' || $password === '') {
- return false;
- }
- if (preg_match('/^\$2[ayb]\$/', $stored)) {
- return password_verify($password, $stored);
- }
- return hash_equals($stored, md5(md5($password)));
- }
- /**
- * 生成 customer 登录密码密文
- */
- protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
- {
- unset($existingSalt);
- return md5(md5($password));
- }
- /**
- * 手机端强密码校验:通过返回空字符串,否则返回错误提示
- */
- protected function mprocValidateStrongPassword(string $password): string
- {
- $len = strlen($password);
- if ($len < 8 || $len > 20) {
- return '密码长度须为8~20位';
- }
- if (preg_match('/\s/', $password)) {
- return '密码不能包含空格';
- }
- if (preg_match('/^\d+$/', $password)) {
- return '密码不能为纯数字,请同时包含字母';
- }
- if (preg_match('/^[a-zA-Z]+$/', $password)) {
- return '密码不能为纯字母,请同时包含数字';
- }
- if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
- return '密码须同时包含字母和数字';
- }
- if (preg_match('/(.)\1{3,}/', $password)) {
- return '密码不能包含过多重复字符(如1111、aaaa)';
- }
- if ($this->mprocPasswordHasSequentialRun($password, 4)) {
- return '密码不能包含连续字符(如1234、abcd)';
- }
- $weak = [
- '12345678', '123456789', '1234567890', '87654321', '01234567',
- 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
- 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
- '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
- ];
- if (in_array(strtolower($password), $weak, true)) {
- return '密码过于简单,请重新设置';
- }
- return '';
- }
- /**
- * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
- */
- protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
- {
- $runLen = max(3, $runLen);
- $lower = strtolower($password);
- $n = strlen($lower);
- if ($n < $runLen) {
- return false;
- }
- for ($i = 0; $i <= $n - $runLen; $i++) {
- $asc = true;
- $desc = true;
- for ($j = 1; $j < $runLen; $j++) {
- $prev = ord($lower[$i + $j - 1]);
- $cur = ord($lower[$i + $j]);
- if ($cur !== $prev + 1) {
- $asc = false;
- }
- if ($cur !== $prev - 1) {
- $desc = false;
- }
- if (!$asc && !$desc) {
- break;
- }
- }
- if ($asc || $desc) {
- return true;
- }
- }
- return false;
- }
- /**
- * @param array<string, mixed> $cu
- * @return array<string, mixed>
- */
- protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
- {
- $phone = trim((string)($cu['phone'] ?? ''));
- $account = trim((string)($cu['account'] ?? ''));
- if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
- $phone = $account;
- }
- if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
- $account = $phone;
- }
- $companyName = trim((string)($cu['company_name'] ?? ''));
- if ($companyName === '' && $phone !== '') {
- $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
- }
- $id = (int)($cu['id'] ?? 0);
- return [
- 'phone' => $phone,
- 'account' => $account,
- 'company_name' => $companyName,
- 'username' => trim((string)($cu['username'] ?? '')),
- 'customer_id' => $id,
- 'customer_user_id' => $id,
- 'login_type' => $loginType,
- 'is_admin' => 0,
- ];
- }
- /**
- * 写入手机端登录态并返回跳转 URL
- *
- * @param array<string, mixed> $userData
- */
- protected function mprocFinishLogin(array $userData): void
- {
- $old = Session::get('mproc_token');
- if ($old) {
- $this->mprocClearLogin((string)$old);
- }
- $userData['login_time'] = time();
- $token = $this->mprocPackSignedAuthToken($userData);
- $token = $this->mprocTouchLoginState($userData, $token);
- $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
- $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
- Session::delete('mproc_intended_url');
- $raw = $postR !== '' ? $postR : $sessR;
- $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
- $this->success('登录成功', $jump, [
- 'mproc_token' => $token,
- 'keep_hours' => $this->mprocKeepHours(),
- 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
- ]);
- }
- /**
- * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
- */
- protected function mprocResolveCompanyForLoginPhone(string $phone): string
- {
- $phone = trim($phone);
- if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
- return '';
- }
- $cust = $this->mprocFindCustomerRowByPhone($phone);
- if (is_array($cust) && $cust !== []) {
- $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
- if ($co !== '') {
- return $co;
- }
- }
- try {
- $one = Db::table('purchase_order_detail')
- ->where('phone', $phone)
- ->order('id', 'desc')
- ->find();
- if (is_array($one)) {
- $n = trim((string)($one['company_name'] ?? ''));
- if ($n !== '') {
- return $n;
- }
- }
- } catch (\Throwable $e) {
- }
- return '';
- }
- /**
- * 按手机号匹配 customer(phone 或 account 单值相等)
- *
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerRowByPhone(string $phone): ?array
- {
- $phone = trim($phone);
- if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
- return null;
- }
- try {
- $row = Db::table('customer')
- ->where(function ($q) use ($phone) {
- $q->where('phone', $phone)->whereOr('account', $phone);
- })
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
- return null;
- }
- return $row;
- }
- /**
- * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
- *
- * @return array<string, mixed>|null
- */
- protected function mprocAdminRowByMobile(string $phone): ?array
- {
- $phone = trim($phone);
- if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
- return null;
- }
- try {
- $row = Db::name('admin')
- ->where('mobile', $phone)
- ->where('status', '<>', 'hidden')
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- return is_array($row) && $row !== [] ? $row : null;
- }
- /**
- * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
- *
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerRowForUser(array $user): ?array
- {
- $phone = trim((string)($user['phone'] ?? ''));
- if ($phone === '') {
- $phone = trim((string)($user['account'] ?? ''));
- }
- $cn = trim((string)($user['company_name'] ?? ''));
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- $byPhone = $this->mprocFindCustomerRowByPhone($phone);
- if ($byPhone !== null) {
- return $byPhone;
- }
- }
- if ($cn !== '') {
- try {
- // customer 表无 name 列,勿用 whereOr('name')
- $hit = Db::table('customer')
- ->where('company_name', $cn)
- ->order('id', 'desc')
- ->find();
- } catch (\Throwable $e) {
- $hit = null;
- }
- if (is_array($hit) && $hit !== []) {
- return $hit;
- }
- }
- return null;
- }
- /**
- * 从 customer 行取字段(兼容列名大小写)
- *
- * @param string[] $candidates
- */
- protected function mprocCustomerPickField(array $row, array $candidates): string
- {
- foreach ($candidates as $want) {
- $lw = strtolower($want);
- foreach ($row as $k => $v) {
- if (!is_string($k)) {
- continue;
- }
- if (strtolower($k) !== $lw) {
- continue;
- }
- $s = trim((string)$v);
- if ($s !== '') {
- return $s;
- }
- }
- }
- return '';
- }
- /**
- * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
- * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
- *
- * @param \think\db\Query $query
- */
- protected function mprocApplySearchKeywordToDetailQuery($query, $search)
- {
- $kw = trim((string)$search);
- if ($kw === '') {
- return;
- }
- $map = self::$mprocProcuremenColumns;
- if (!is_array($map) || $map === []) {
- return;
- }
- $like = '%' . addcslashes($kw, '%_\\') . '%';
- $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
- $detailCols = [];
- foreach ($wantLower as $low) {
- if (isset($map[$low])) {
- $detailCols[] = $map[$low];
- }
- }
- $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
- $idCol = isset($map['id']) ? $map['id'] : 'id';
- $poSidList = [];
- $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
- try {
- $col = Db::table('purchase_order')
- ->where(function ($sub) use ($like, $poWant) {
- $firstPo = true;
- foreach ($poWant as $pf) {
- if ($firstPo) {
- $sub->where($pf, 'like', $like);
- $firstPo = false;
- } else {
- $sub->whereOr($pf, 'like', $like);
- }
- }
- })
- ->column('scydgy_id');
- if (is_array($col)) {
- foreach ($col as $v) {
- $id = (int)$v;
- if ($this->mprocIsValidScydgyRowId($id)) {
- $poSidList[$id] = true;
- }
- }
- }
- $poSidList = array_keys($poSidList);
- } catch (\Throwable $e) {
- $poSidList = [];
- }
- $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
- $first = true;
- foreach ($detailCols as $col) {
- if ($first) {
- $q2->where($col, 'like', $like);
- $first = false;
- } else {
- $q2->whereOr($col, 'like', $like);
- }
- }
- if ($poSidList !== []) {
- if ($first) {
- $q2->where($scydgyCol, 'in', $poSidList);
- $first = false;
- } else {
- $q2->whereOr($scydgyCol, 'in', $poSidList);
- }
- }
- if ($first) {
- $q2->where($idCol, '=', 0);
- }
- });
- }
- /**
- * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
- * - draft:status_name = 未提交
- * - submitted:status_name = 已提交
- * - done:status_name = 已完成
- * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
- *
- * @param mixed $query
- * @param string $tab draft|submitted|done
- * @param string|null $statusNameCol 真实列名,如 status_name
- */
- protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
- {
- if ($statusNameCol === null) {
- return;
- }
- $map = [
- 'draft' => '未提交',
- 'submitted' => '已提交',
- 'done' => '已完成',
- ];
- $label = $map[$tab] ?? '未提交';
- $query->where($statusNameCol, '=', $label);
- }
- /**
- * 按登录态解析 customer 行
- *
- * @return array<string, mixed>|null
- */
- protected function mprocResolveCustomerUserForSession(array $user): ?array
- {
- if (!empty($user['is_admin'])) {
- return null;
- }
- $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
- if ($cuId > 0) {
- try {
- $row = Db::table('customer')->where('id', $cuId)->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
- return $row;
- }
- }
- $account = trim((string)($user['account'] ?? ''));
- if ($account !== '') {
- $byAcc = $this->mprocFindCustomerUserByUsername($account);
- if ($byAcc !== null) {
- return $byAcc;
- }
- }
- $phone = trim((string)($user['phone'] ?? ''));
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- return $this->mprocFindCustomerUserByMobile($phone);
- }
- $uname = trim((string)($user['username'] ?? ''));
- if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
- return $this->mprocFindCustomerUserByMobile($uname);
- }
- return null;
- }
- /**
- * customer 表字段 →「我的」展示结构
- *
- * @param array<string, mixed> $cu
- * @return array{company_name:string,contact_name:string,phone:string,email:string}
- */
- protected function mprocProfileFromCustomerUserRow(array $cu): array
- {
- $nm = trim((string)($cu['username'] ?? ''));
- $phone = trim((string)($cu['phone'] ?? ''));
- if ($phone === '') {
- $phone = trim((string)($cu['account'] ?? ''));
- }
- return [
- 'company_name' => trim((string)($cu['company_name'] ?? '')),
- 'contact_name' => $nm,
- 'phone' => $phone,
- 'email' => trim((string)($cu['email'] ?? '')),
- ];
- }
- /**
- * 管理员「我的」:admin 表
- *
- * @return array{company_name:string,contact_name:string,phone:string,email:string}
- */
- protected function mprocProfileForAdmin(array $user): array
- {
- $uname = trim((string)($user['username'] ?? ''));
- $out = [
- 'company_name' => '管理员',
- 'contact_name' => $uname !== '' ? $uname : '管理员',
- 'phone' => trim((string)($user['phone'] ?? '')),
- 'email' => '',
- ];
- if ($uname === '') {
- return $out;
- }
- try {
- $row = Db::name('admin')->where('username', $uname)->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!is_array($row) || $row === []) {
- return $out;
- }
- $nick = trim((string)($row['nickname'] ?? ''));
- if ($nick !== '') {
- $out['contact_name'] = $nick;
- }
- $mob = trim((string)($row['mobile'] ?? ''));
- if ($mob !== '') {
- $out['phone'] = $mob;
- }
- $em = trim((string)($row['email'] ?? ''));
- if ($em !== '') {
- $out['email'] = $em;
- }
- return $out;
- }
- /**
- * 旧会话补全 customer_id 等字段
- */
- protected function mprocSyncSessionCustomerUser(array $user): array
- {
- if (!empty($user['is_admin'])) {
- return $user;
- }
- $cu = $this->mprocResolveCustomerUserForSession($user);
- if (!$cu) {
- return $user;
- }
- $id = (int)($cu['id'] ?? 0);
- $user['customer_id'] = $id;
- $user['customer_user_id'] = $id;
- $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
- $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
- $user['account'] = trim((string)($cu['account'] ?? ''));
- $mob = trim((string)($cu['phone'] ?? ''));
- if ($mob === '') {
- $mob = trim((string)($cu['account'] ?? ''));
- }
- if ($mob !== '') {
- $user['phone'] = $mob;
- }
- $token = Session::get('mproc_token');
- if ($token) {
- $user['login_time'] = (int)($user['login_time'] ?? time());
- $tok = trim((string)$token);
- Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
- if (!$this->mprocIsSignedAuthToken($tok)) {
- Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
- }
- }
- return $user;
- }
- /**
- * 「我的」:普通用户 customer;管理员 admin
- */
- protected function mprocProfileForUser(array $user)
- {
- if (!empty($user['is_admin'])) {
- return $this->mprocProfileForAdmin($user);
- }
- $cu = $this->mprocResolveCustomerUserForSession($user);
- if (is_array($cu) && $cu !== []) {
- return $this->mprocProfileFromCustomerUserRow($cu);
- }
- $phone = trim((string)($user['phone'] ?? ''));
- if ($phone === '') {
- $phone = trim((string)($user['account'] ?? ''));
- }
- return [
- 'company_name' => trim((string)($user['company_name'] ?? '')),
- 'contact_name' => trim((string)($user['username'] ?? '')),
- 'phone' => $phone,
- 'email' => '',
- ];
- }
- protected function mprocIsValidScydgyRowId($id): bool
- {
- return (int)$id !== 0;
- }
- /**
- * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
- * 金额、交期、外厂 company、明细 status 等仍保留明细表。
- *
- * @param array $row 引用:明细行
- * @param array $poRow purchase_order 一行
- */
- protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
- {
- $pl = array_change_key_case($poRow, CASE_LOWER);
- $hdr = [
- 'ccydh' => 'CCYDH',
- 'cyjmc' => 'CYJMC',
- 'cdf' => 'CDF',
- 'cgzzxmc' => 'cGzzxMc',
- 'cgymc' => 'CGYMC',
- 'cdxmc' => 'CDXMC',
- 'ngzl' => 'NGZL',
- 'cdw' => 'CDW',
- 'cgybh' => 'CGYBH',
- ];
- foreach ($hdr as $lk => $out) {
- if (!array_key_exists($lk, $pl)) {
- continue;
- }
- $v = $pl[$lk];
- if ($v !== null && $v !== '') {
- $row[$out] = $v;
- }
- }
- // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
- $qtyRaw = '';
- foreach (['this_quantity', 'This_quantity'] as $qk) {
- if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
- $qtyRaw = trim((string)$pl[$qk]);
- break;
- }
- }
- if ($qtyRaw === '') {
- foreach (['This_quantity', 'this_quantity'] as $qk) {
- if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
- $qtyRaw = trim((string)$poRow[$qk]);
- break;
- }
- }
- }
- if ($qtyRaw !== '') {
- $row['This_quantity'] = $qtyRaw;
- }
- $ceilRaw = '';
- foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
- if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
- $ceilRaw = trim((string)$pl[$ck]);
- break;
- }
- }
- if ($ceilRaw === '') {
- foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
- if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
- $ceilRaw = trim((string)$poRow[$ck]);
- break;
- }
- }
- }
- if ($ceilRaw !== '') {
- $row['ceilingPrice'] = $ceilRaw;
- }
- $sysRq = '';
- foreach (['sys_rq', 'SYS_RQ'] as $sk) {
- if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
- $sysRq = trim((string)$pl[$sk]);
- break;
- }
- if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
- $sysRq = trim((string)$poRow[$sk]);
- break;
- }
- }
- if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
- $row['sys_rq'] = $sysRq;
- }
- $deliveryDeadline = '';
- foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
- if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
- $deliveryDeadline = trim((string)$pl[$dk]);
- break;
- }
- if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
- $deliveryDeadline = trim((string)$poRow[$dk]);
- break;
- }
- }
- if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
- $row['delivery_deadline'] = $deliveryDeadline;
- }
- }
- /**
- * 统一取年月日(无效则空串)
- */
- protected function mprocFormatYmdValue($raw): string
- {
- $s = trim((string)$raw);
- if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
- return '';
- }
- $s = str_replace(['/', '.'], '-', $s);
- if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
- return $m[1];
- }
- $ts = strtotime(str_replace('T', ' ', $s));
- if ($ts === false || $ts <= 0) {
- return '';
- }
- return date('Y-m-d', $ts);
- }
- /**
- * 列表展示:招标截止 / 交货截止
- *
- * @param array<string, mixed> $row
- */
- protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
- {
- $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
- $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
- $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
- $row['mproc_bid_deadline_display'] = $bid;
- // 完整截止时间供前端保存前校验(含时分秒)
- $row['mproc_bid_deadline'] = $sysRqRaw;
- $row['mproc_delivery_deadline_display'] = $del;
- $row['mproc_delivery_deadline'] = $del;
- }
- /**
- * 明细对应主表的交货截止日期 Y-m-d
- *
- * @param array<string, mixed> $row
- */
- protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
- {
- $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
- if ($fromRow !== '') {
- return $fromRow;
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- if (!$this->mprocIsValidScydgyRowId($sid)) {
- return '';
- }
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (!is_array($po)) {
- return '';
- }
- return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
- }
- /**
- * 主表报价截止时间(未设置则视为未截止)
- *
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolveSysRqFromPo(?array $po): string
- {
- if (!is_array($po)) {
- return '';
- }
- $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
- if ($sr === '') {
- $pl = array_change_key_case($po, CASE_LOWER);
- $sr = trim((string)($pl['sys_rq'] ?? ''));
- }
- return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
- }
- /**
- * 从主表/明细解析订单号
- *
- * @param array<string, mixed>|null $po
- * @param array<string, mixed>|null $row
- */
- protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
- {
- foreach ([$po, $row] as $src) {
- if (!is_array($src)) {
- continue;
- }
- $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
- if ($c !== '') {
- return $c;
- }
- }
- return '';
- }
- /**
- * 批量:已开标验证的订单号集合(本请求内可复用)
- *
- * @var array<string, bool>|null
- */
- protected $mprocBidOpenVerifiedSet = null;
- /**
- * @param array<int, string> $ccydhs
- * @return array<string, bool>
- */
- protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
- {
- $set = [];
- $list = [];
- foreach ($ccydhs as $c) {
- $c = trim((string)$c);
- if ($c !== '') {
- $list[$c] = true;
- }
- }
- if ($list === []) {
- return $set;
- }
- try {
- $rows = Db::table('purchase_order_bid_open')
- ->where('ccydh', 'in', array_keys($list))
- ->field('ccydh')
- ->select();
- if (!is_array($rows)) {
- return $set;
- }
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $c = trim((string)($row['ccydh'] ?? ''));
- if ($c !== '') {
- $set[$c] = true;
- }
- }
- } catch (\Throwable $e) {
- return [];
- }
- return $set;
- }
- /**
- * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
- */
- protected function mprocIsBidOpenVerified(string $ccydh): bool
- {
- $ccydh = trim($ccydh);
- if ($ccydh === '') {
- return false;
- }
- if (is_array($this->mprocBidOpenVerifiedSet)) {
- return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
- }
- try {
- $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
- return is_array($row);
- } catch (\Throwable $e) {
- return false;
- }
- }
- /**
- * @param array<string, mixed>|null $po
- * @param array<string, mixed>|null $row
- */
- protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
- {
- return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
- }
- /**
- * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
- * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
- *
- * @param array<string, mixed>|null $po
- */
- protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
- {
- $raw = $this->mprocResolveSysRqFromPo($po);
- if ($raw === '') {
- return false;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- if ($ts === false || $ts <= 0) {
- return false;
- }
- return time() >= $ts;
- }
- /**
- * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
- *
- * @param array<string, mixed>|null $po
- */
- protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
- {
- // 以库中最新主表为准,避免内存中旧快照
- $freshPo = null;
- if (is_array($po)) {
- $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $freshPo = null;
- }
- }
- }
- $checkPo = is_array($freshPo) ? $freshPo : $po;
- if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
- throw new \InvalidArgumentException(
- ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
- );
- }
- }
- /**
- * 保存前:截止时间 + 已开标均不可再改
- *
- * @param array<string, mixed>|null $po
- * @param array<string, mixed>|null $row
- */
- protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
- {
- $sid = 0;
- if (is_array($row)) {
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- }
- if ($sid === 0 && is_array($po)) {
- $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
- }
- // 手工询价无招标截止、不开标
- if ($sid < 0) {
- return;
- }
- $this->mprocAssertQuoteNotDeadlineReached($po, $label);
- $freshPo = is_array($po) ? $po : null;
- if (is_array($po)) {
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($got)) {
- $freshPo = $got;
- }
- } catch (\Throwable $e) {
- }
- }
- }
- // 保存场景不走列表缓存,直接查库
- $prev = $this->mprocBidOpenVerifiedSet;
- $this->mprocBidOpenVerifiedSet = null;
- $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
- $this->mprocBidOpenVerifiedSet = $prev;
- if ($opened) {
- throw new \InvalidArgumentException(
- ($label !== '' ? $label : '') . '已开标验证,不可再提交'
- );
- }
- }
- /**
- * 主单已完结后:中标 / 未中标
- *
- * @param array<string, mixed> $row
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolvePickResultText(array $row, ?array $po): string
- {
- if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
- return '';
- }
- $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
- return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
- }
- /**
- * 手机端左侧 Tab:
- * 询价:rfq / rfq_submitted(手工单 scydgy_id<0,仅未提交/已提交)
- * 报价:draft / submitted / done(协助下发)
- *
- * @param array<string, mixed> $row
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
- {
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
- if ($sid < 0) {
- if ($effectiveSn === '已提交'
- || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- return 'rfq_submitted';
- }
- return 'rfq';
- }
- if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- return 'done';
- }
- if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
- || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
- // 已开标或已过招标截止 →「已完成」
- return 'done';
- }
- if ($effectiveSn === '已提交') {
- return 'submitted';
- }
- return 'draft';
- }
- /**
- * @return string[]
- */
- protected function mprocListTabWhitelist(): array
- {
- return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
- }
- /**
- * 兼容旧地址 tab=rfq_done → 询价已提交
- */
- protected function mprocNormalizeListTab(string $tab): string
- {
- if ($tab === 'rfq_done') {
- return 'rfq_submitted';
- }
- if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
- return 'draft';
- }
- return $tab;
- }
- protected function mprocIsDoneListTab(string $tab): bool
- {
- return $tab === 'done';
- }
- protected function mprocIsRfqListTab(string $tab): bool
- {
- return $tab === 'rfq' || $tab === 'rfq_submitted';
- }
- /**
- * 复合 Tab → 状态维度:draft|submitted|done
- */
- protected function mprocStatusFromListTab(string $tab): string
- {
- if ($tab === 'rfq' || $tab === 'draft') {
- return 'draft';
- }
- if ($tab === 'rfq_submitted' || $tab === 'submitted') {
- return 'submitted';
- }
- if ($this->mprocIsDoneListTab($tab)) {
- return 'done';
- }
- return 'draft';
- }
- /**
- * 同一订单号 + 供应商合并为一张卡片
- *
- * @param array<int, array<string, mixed>> $rows
- * @return array<int, array<string, mixed>>
- */
- protected function mprocGroupRowsByOrder(array $rows): array
- {
- $groups = [];
- $order = [];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ccydh = trim((string)($row['CCYDH'] ?? ''));
- $cname = trim((string)($row['company_name'] ?? ''));
- $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
- if (!isset($groups[$key])) {
- $groups[$key] = [
- 'group_key' => $key,
- 'CCYDH' => $ccydh,
- 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
- 'company_name' => $cname,
- 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
- 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
- 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
- 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
- 'lines' => [],
- ];
- $order[] = $key;
- } else {
- if ($groups[$key]['mproc_delivery_deadline'] === ''
- && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
- $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
- $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
- }
- if ($groups[$key]['mproc_bid_deadline'] === ''
- && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
- $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
- }
- if ($groups[$key]['mproc_bid_deadline_display'] === ''
- && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
- $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
- }
- }
- $groups[$key]['lines'][] = $row;
- }
- $out = [];
- foreach ($order as $key) {
- $g = $groups[$key];
- $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
- usort($lines, function ($a, $b) {
- $sa = (int)($a['scydgy_id'] ?? 0);
- $sb = (int)($b['scydgy_id'] ?? 0);
- if ($sa !== $sb) {
- return $sa <=> $sb;
- }
- return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
- });
- $g['lines'] = $lines;
- $g['line_count'] = count($lines);
- $canEdit = false;
- $bidOpen = false;
- foreach ($lines as $ln) {
- if (!is_array($ln)) {
- continue;
- }
- if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
- $canEdit = true;
- }
- if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
- $bidOpen = true;
- }
- }
- $g['can_edit'] = $canEdit ? 1 : 0;
- $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
- $remark = '';
- $doneLabel = '';
- $pickResult = '';
- $hasWin = false;
- $hasLose = false;
- $hasExpired = false;
- foreach ($lines as $ln) {
- if (!is_array($ln)) {
- continue;
- }
- $rm = trim((string)($ln['mproc_remark'] ?? ''));
- if ($rm !== '' && $remark === '') {
- $remark = $rm;
- }
- $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
- $dl = trim((string)($ln['mproc_done_label'] ?? ''));
- if ($pr === '中标' || $dl === '中标') {
- $hasWin = true;
- } elseif ($pr === '未中标' || $dl === '未中标') {
- $hasLose = true;
- } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
- $hasExpired = true;
- }
- }
- if ($hasWin) {
- $doneLabel = '中标';
- $pickResult = '中标';
- } elseif ($hasLose) {
- $doneLabel = '未中标';
- $pickResult = '未中标';
- } elseif ($hasExpired) {
- $doneLabel = '已截止';
- $pickResult = '';
- }
- $g['remark'] = $remark;
- $g['mproc_done_label'] = $doneLabel;
- $g['mproc_pick_result'] = $pickResult;
- $out[] = $g;
- }
- return $out;
- }
- /**
- * 查询 purchase_order_detail 列表(订单页)
- * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
- * 有搜索词时:在当前 Tab 内做关键字匹配
- *
- * @param string $tab draft|submitted|done
- * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
- * @return array{rows: array, done_no_status: int}
- */
- protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
- {
- $query = Db::table('purchase_order_detail')->order('id', 'desc');
- // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
- $userWhere = $this->mprocListWhereForLoginUser($user);
- if ($userWhere !== []) {
- $query->where($userWhere);
- }
- if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
- $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
- }
- $this->mprocApplySearchKeywordToDetailQuery($query, $q);
- // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
- try {
- $rows = $query->limit(500)->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- $rows = [];
- }
- $poBySid = [];
- $sidList = [];
- foreach ($rows as $r0) {
- if (!is_array($r0)) {
- continue;
- }
- $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid0)) {
- $sidList[$sid0] = true;
- }
- }
- if ($sidList !== []) {
- try {
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
- ->select();
- if (is_array($poRows)) {
- foreach ($poRows as $pr) {
- $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sidk)) {
- $poBySid[$sidk] = $pr;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- }
- $ccydhForBid = [];
- foreach ($poBySid as $pr) {
- if (!is_array($pr)) {
- continue;
- }
- $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
- if ($c !== '') {
- $ccydhForBid[$c] = true;
- }
- }
- foreach ($rows as $r0) {
- if (!is_array($r0)) {
- continue;
- }
- $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
- if ($c !== '') {
- $ccydhForBid[$c] = true;
- }
- }
- $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
- foreach ($rows as &$row) {
- if (!is_array($row)) {
- continue;
- }
- // 废弃明细不在手机端展示
- if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
- || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
- $row = null;
- continue;
- }
- $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
- }
- $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
- $oldSn = trim((string)($row['status_name'] ?? ''));
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
- $row['status_name'] = $effectiveSn;
- if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
- $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
- }
- $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
- $row['mproc_list_tab'] = $listTab;
- $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
- if ((int)$row['mproc_is_rfq'] === 1) {
- // 手工询价不展示招标/交货截止,也不走开标截止逻辑
- $row['mproc_bid_deadline'] = '';
- $row['mproc_bid_deadline_display'] = '';
- $row['mproc_delivery_deadline'] = '';
- $row['mproc_delivery_deadline_display'] = '';
- $row['mproc_deadline_reached'] = 0;
- $row['mproc_bid_open_verified'] = 0;
- $row['mproc_pick_result'] = '';
- } else {
- $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
- $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
- $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
- }
- if ($row['mproc_pick_result'] !== '') {
- $row['mproc_done_label'] = $row['mproc_pick_result'];
- } elseif ($this->mprocIsDoneListTab($listTab) && (
- (int)$row['mproc_deadline_reached'] === 1
- || (int)$row['mproc_bid_open_verified'] === 1
- )) {
- $row['mproc_done_label'] = '已截止';
- } else {
- $row['mproc_done_label'] = '';
- }
- // status_name 由库表/后端维护,不在此根据 amount 覆盖
- if (!isset($row['status_name']) || $row['status_name'] === null) {
- $row['status_name'] = '';
- } else {
- $row['status_name'] = trim((string)$row['status_name']);
- }
- $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
- $am = $row['amount'] ?? null;
- if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
- $row['amount_display'] = '';
- } else {
- $row['amount_display'] = is_scalar($am) ? (string)$am : '';
- }
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
- $row['delivery_display'] = $m[1];
- } elseif ($dv !== '') {
- $row['delivery_display'] = $dv;
- } else {
- $row['delivery_display'] = '';
- }
- $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
- $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
- $this->mprocEnrichLeadDaysDisplay($row);
- if ((int)$row['mproc_is_rfq'] === 1) {
- $row['mproc_bid_deadline'] = '';
- $row['mproc_bid_deadline_display'] = '';
- $row['mproc_delivery_deadline'] = '';
- $row['mproc_delivery_deadline_display'] = '';
- } else {
- $this->mprocEnrichOrderDeadlineDisplay($row);
- }
- $row['mproc_fill_hint'] = '';
- $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
- $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
- }
- unset($row);
- $rows = array_values(array_filter($rows, function ($r) {
- return is_array($r);
- }));
- // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
- $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
- // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
- $rows = array_values(array_filter($rows, function ($r) use ($tab) {
- return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
- }));
- // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
- if ($this->mprocIsDoneListTab((string)$tab)) {
- $rows = array_values(array_filter($rows, function ($r) {
- return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
- }));
- }
- // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
- $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
- $groups = $this->mprocGroupRowsByOrder($rows);
- return [
- 'rows' => $rows ?: [],
- 'groups' => $groups ?: [],
- 'done_no_status' => (int)($statusNameCol === null),
- ];
- }
- /**
- * 按招标截止时间排序(无截止时间的排最后)
- *
- * @param array<int, array<string, mixed>> $rows
- * @param string $dir asc|desc
- * @return array<int, array<string, mixed>>
- */
- protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
- {
- $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
- usort($rows, function ($a, $b) use ($dir) {
- $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
- $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
- $ha = $ta > 0;
- $hb = $tb > 0;
- if ($ha !== $hb) {
- return $ha ? -1 : 1;
- }
- if ($ha && $ta !== $tb) {
- return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
- }
- $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
- $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
- return $idb <=> $ida;
- });
- return array_values($rows);
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocBidDeadlineSortTs(array $row): int
- {
- $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
- if ($raw === '') {
- $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
- }
- if ($raw === '') {
- return 0;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- return ($ts !== false && $ts > 0) ? (int)$ts : 0;
- }
- /**
- * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
- *
- * @param array<string, mixed> $row
- */
- protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
- {
- $months = max(1, $months);
- $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
- if ($since === false) {
- return true;
- }
- $candidates = [
- $row['mproc_bid_deadline'] ?? '',
- $row['sys_rq'] ?? '',
- $row['SYS_RQ'] ?? '',
- $row['mproc_bid_deadline_display'] ?? '',
- $row['mproc_delivery_deadline'] ?? '',
- $row['delivery_deadline'] ?? '',
- $row['mproc_delivery_deadline_display'] ?? '',
- $row['createtime'] ?? '',
- $row['updatetime'] ?? '',
- ];
- foreach ($candidates as $raw) {
- $raw = trim((string)$raw);
- if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
- continue;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- if ($ts === false || $ts <= 0) {
- continue;
- }
- return $ts >= $since;
- }
- return false;
- }
- /**
- * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
- *
- * @param array<int, array<string, mixed>> $rows
- * @return array<int, array<string, mixed>>
- */
- protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
- {
- $best = [];
- $orderKeys = [];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $cn = trim((string)($row['company_name'] ?? ''));
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid)) {
- $key = $cn . '|sid:' . $sid;
- } else {
- $key = $cn . '|eid:' . $eid;
- }
- if (!isset($best[$key])) {
- $best[$key] = $row;
- $orderKeys[] = $key;
- continue;
- }
- $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
- if ($eid > $prevEid) {
- $best[$key] = $row;
- }
- }
- $out = [];
- foreach ($orderKeys as $key) {
- if (isset($best[$key])) {
- $out[] = $best[$key];
- }
- }
- return $out;
- }
- /**
- * status_name → 手机端左侧 Tab
- */
- protected function mprocStatusNameToListTab(string $statusName): string
- {
- $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
- $sn = trim($statusName);
- return isset($map[$sn]) ? $map[$sn] : '';
- }
- /**
- * 短信/邮件 focus_eid 应落在的列表 Tab
- */
- protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
- {
- if ($focusEid <= 0) {
- return '';
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null) {
- return '';
- }
- try {
- $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
- $qw = $this->mprocListWhereForLoginUser($user);
- if ($qw !== []) {
- $qrow->where($qw);
- }
- $dr = $qrow->find();
- } catch (\Throwable $e) {
- $dr = null;
- }
- if (!is_array($dr) || $dr === []) {
- return '';
- }
- $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
- $po = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- }
- return $this->mprocResolveListTabForRow(
- $dr,
- is_array($po) ? $po : null,
- $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
- );
- }
- /**
- * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
- *
- * @param array<string, mixed> $bundle
- * @param array<string, mixed> $user
- * @return array<string, mixed>
- */
- protected function mprocEnsureFocusRowInList(
- array $bundle,
- int $focusEid,
- array $user,
- $statusNameCol,
- string $tab = 'draft',
- string $q = ''
- ): array {
- if ($focusEid <= 0) {
- return $bundle;
- }
- $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
- $foundIdx = -1;
- foreach ($rows as $idx => $r) {
- if (!is_array($r)) {
- continue;
- }
- if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
- $foundIdx = (int)$idx;
- break;
- }
- }
- if ($foundIdx > 0) {
- $hit = $rows[$foundIdx];
- array_splice($rows, $foundIdx, 1);
- array_unshift($rows, $hit);
- $bundle['rows'] = $rows;
- $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
- return $bundle;
- }
- if ($foundIdx === 0) {
- return $bundle;
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null) {
- return $bundle;
- }
- try {
- $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
- $qw = $this->mprocListWhereForLoginUser($user);
- if ($qw !== []) {
- $qrow->where($qw);
- }
- $dr = $qrow->find();
- } catch (\Throwable $e) {
- $dr = null;
- }
- if (!is_array($dr) || $dr === []) {
- return $bundle;
- }
- $row = $dr;
- $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $poRow = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $poRow = null;
- }
- if (is_array($poRow)) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
- }
- }
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
- $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
- if ($rowTab !== '' && $rowTab !== $tab) {
- return $bundle;
- }
- $row['status_name'] = $effectiveSn;
- $listTab = $rowTab;
- $row['mproc_list_tab'] = $listTab;
- $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
- $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
- $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
- if ($row['mproc_pick_result'] !== '') {
- $row['mproc_done_label'] = $row['mproc_pick_result'];
- } elseif ($this->mprocIsDoneListTab($listTab) && (
- (int)$row['mproc_deadline_reached'] === 1
- || (int)$row['mproc_bid_open_verified'] === 1
- )) {
- $row['mproc_done_label'] = '已截止';
- } else {
- $row['mproc_done_label'] = '';
- }
- $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
- $am = $row['amount'] ?? null;
- $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
- $row['delivery_display'] = $m[1];
- } elseif ($dv !== '') {
- $row['delivery_display'] = $dv;
- } else {
- $row['delivery_display'] = '';
- }
- $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
- $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
- $this->mprocEnrichLeadDaysDisplay($row);
- $this->mprocEnrichOrderDeadlineDisplay($row);
- $row['mproc_fill_hint'] = '';
- $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
- array_unshift($rows, $row);
- $bundle['rows'] = $rows;
- $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
- return $bundle;
- }
- /**
- * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
- *
- * @param array<string, mixed> $row
- */
- protected function mprocResolveDisplayThisQuantity(array $row): string
- {
- $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
- if ($qty !== '') {
- return $qty;
- }
- $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
- if ($gzl === null || $gzl === '') {
- return '';
- }
- return is_scalar($gzl) ? trim((string)$gzl) : '';
- }
- /**
- * 明细是否已填写单价或交货日期
- *
- * @param array<string, mixed> $row
- */
- protected function mprocDetailQuoteSubmitted(array $row): bool
- {
- $am = $row['amount'] ?? null;
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
- $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
- return $amountFilled || $deliveryFilled;
- }
- /**
- * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
- *
- * @param array<string, mixed> $row
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
- {
- $sn = trim((string)($row['status_name'] ?? ''));
- if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
- return $sn;
- }
- if (!is_array($po)) {
- if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
- return '已提交';
- }
- if ($sn !== '') {
- return $sn;
- }
- return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
- }
- $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
- if (!ProcuremenStatus::isPoCompleted($poStatus)) {
- // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
- if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
- return '已提交';
- }
- if ($sn !== '') {
- return $sn;
- }
- return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
- }
- $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
- if (ProcuremenStatus::isPodPicked($detailStatus)) {
- return '已完成';
- }
- if ($sn === '已提交') {
- return '未通过';
- }
- return $sn !== '' ? $sn : '未提交';
- }
- /**
- * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
- */
- protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
- {
- if ($detailId <= 0 || $statusNameCol === '') {
- return;
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null || $idCol === '') {
- return;
- }
- try {
- Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
- } catch (\Throwable $e) {
- }
- }
- /**
- * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
- *
- * @param array<string, mixed> $user
- */
- protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
- {
- $userWhere = $this->mprocListWhereForLoginUser($user);
- try {
- $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
- if ($userWhere !== []) {
- $query->where($userWhere);
- }
- $candidates = $query->limit(200)->select();
- } catch (\Throwable $e) {
- return;
- }
- if (!is_array($candidates) || $candidates === []) {
- return;
- }
- $sidList = [];
- foreach ($candidates as $cr) {
- if (!is_array($cr)) {
- continue;
- }
- $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid)) {
- $sidList[$sid] = true;
- }
- }
- if ($sidList === []) {
- return;
- }
- $poBySid = [];
- try {
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($sidList))
- ->whereIn('status', ProcuremenStatus::poCompletedValues())
- ->select();
- if (is_array($poRows)) {
- foreach ($poRows as $pr) {
- $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sidk)) {
- $poBySid[$sidk] = $pr;
- }
- }
- }
- } catch (\Throwable $e) {
- return;
- }
- if ($poBySid === []) {
- return;
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null || $idCol === '') {
- return;
- }
- foreach ($candidates as $cr) {
- if (!is_array($cr)) {
- continue;
- }
- $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
- if (!isset($poBySid[$sid])) {
- continue;
- }
- $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
- if ($detailId <= 0) {
- continue;
- }
- $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
- if ($targetSn === '已提交') {
- continue;
- }
- $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
- }
- }
- /**
- * 协助明细首页(需登录)
- * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
- */
- public function index()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $pendingFocus = $this->mprocReadFocusEidFromRequest();
- if ($pendingFocus > 0) {
- $this->mprocRememberFocusEid($pendingFocus);
- }
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
- $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
- }
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- // 管理员进质量评分,不进供应商报价列表
- if (!empty($user['is_admin'])) {
- $this->redirect(url('index/index/inboundscore', '', '', true));
- return;
- }
- $user = $this->mprocSyncSessionCustomerUser($user);
- $tabParamRaw = $this->request->get('tab', null);
- $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
- $tabParam = trim((string)($tabParamRaw ?? 'draft'));
- $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
- // 旧地址 ?tab=me 表示「我的」
- if ($tabParam === 'me') {
- $mainTab = 'me';
- }
- if (!in_array($mainTab, ['orders', 'me'], true)) {
- $mainTab = 'orders';
- }
- $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
- $q = trim((string)$this->request->get('q', ''));
- $mprocFocusEid = 0;
- $focusEid = $this->mprocReadFocusEidFromRequest();
- if ($focusEid > 0 && $mainTab === 'orders') {
- $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
- // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
- if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
- Session::delete('mproc_focus_eid');
- $focusEid = 0;
- } else {
- $mprocFocusEid = $focusEid;
- // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
- $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
- if (!$focusFromUrl) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
- }
- if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
- if ($resolvedTab !== '') {
- $tab = $resolvedTab;
- }
- }
- }
- }
- // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
- $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
- $profile = $this->mprocProfileForUser($user);
- $this->view->assign('mprocMainTab', $mainTab);
- $this->view->assign('mprocTab', $tab);
- $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
- $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
- $this->view->assign('mprocSearchQ', $q);
- $this->view->assign('mprocProfile', $profile);
- $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
- $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
- $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
- $this->view->assign('mprocFocusEid', $mprocFocusEid);
- $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
- $this->view->assign('mprocFocusTab', $mprocFocusTab);
- $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
- $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
- if ($mainTab === 'me') {
- $this->view->assign('rows', []);
- return $this->view->fetch();
- }
- $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
- if ($mprocFocusEid > 0) {
- $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
- }
- $this->view->assign('rows', $bundle['rows']);
- $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
- return $this->view->fetch();
- }
- /**
- * 协助明细列表 JSON(需登录)
- * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
- */
- public function mprocList()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- $user = $this->mprocSyncSessionCustomerUser($user);
- $tabParam = trim((string)$this->request->request('tab', 'draft'));
- $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
- if ($tabParam === 'me') {
- $mainTab = 'me';
- }
- if (!in_array($mainTab, ['orders', 'me'], true)) {
- $mainTab = 'orders';
- }
- $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
- $q = trim((string)$this->request->request('q', ''));
- if ($mainTab === 'me') {
- // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
- $this->success('ok', '', [
- 'main_tab' => 'me',
- 'tab' => $tab,
- 'rows' => [],
- 'profile' => $this->mprocProfileForUser($user),
- 'done_no_status' => 0,
- ]);
- }
- $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
- if ((int)$this->request->request('clear_focus', 0) === 1) {
- Session::delete('mproc_focus_eid');
- $focusEid = 0;
- $focusTab = '';
- } else {
- $focusEid = $this->mprocReadFocusEidFromRequest();
- $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
- // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
- if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
- Session::delete('mproc_focus_eid');
- $focusEid = 0;
- $focusTab = '';
- }
- }
- $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
- if ($focusEid > 0) {
- $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
- }
- $this->success('ok', '', array_merge([
- 'main_tab' => 'orders',
- 'tab' => $tab,
- 'focus_tab' => $focusTab,
- 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
- 'focus_eid' => $focusEid,
- ], $bundle));
- }
- /**
- * 登录页(手机号验证码 / 账号密码)
- */
- public function login()
- {
- $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
- $user = $this->mprocGetUser();
- if ($user) {
- $this->redirect($this->mprocBuildAfterLoginHomeUrl($user, $redirect));
- }
- if ($redirect !== '') {
- Session::set('mproc_intended_url', $redirect);
- }
- $this->view->assign('mprocLoginRedirect', $redirect);
- $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
- $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
- return $this->view->fetch();
- }
- /**
- * 图形验证码(手机号登录用)
- */
- public function captcha($id = '')
- {
- $captcha = new Captcha((array)Config::get('captcha'));
- return $captcha->entry($id);
- }
- /**
- * 发送登录验证码(POST:phone、captcha)
- */
- public function sendSms()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $phone = trim((string)$this->request->post('phone', ''));
- $captcha = trim((string)$this->request->post('captcha', ''));
- if (!preg_match('/^1\d{10}$/', $phone)) {
- $this->error('请输入正确的11位手机号');
- }
- if ($captcha === '') {
- $this->error('请输入图形验证码');
- }
- if (!$this->mprocFindCustomerUserByMobile($phone)) {
- $this->error('该手机号未开通或已禁用,请联系管理员');
- }
- $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
- if (Cache::get('mproc_sms_wait_' . $phone)) {
- $this->error('发送过于频繁,请稍后再试');
- }
- if (!Validate::is($captcha, 'captcha')) {
- $this->error('图形验证码不正确');
- }
- $code = (string)random_int(100000, 999999);
- $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
- $ttl = max(60, min(600, $ttl));
- Cache::set('mproc_code_' . $phone, $code, $ttl);
- Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
- try {
- $tpl = trim((string)Config::get('mproc.sms_login_template'));
- if ($tpl === '') {
- $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
- }
- $content = str_replace('{code}', $code, $tpl);
- $this->mprocSmsSend($phone, $content);
- } catch (\Exception $e) {
- Cache::rm('mproc_code_' . $phone);
- Cache::rm('mproc_sms_wait_' . $phone);
- $this->error($e->getMessage());
- }
- $this->success('验证码已发送');
- }
- /**
- * 验证码登录(POST:phone、code)
- */
- public function doLogin()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $phone = trim((string)$this->request->post('phone', ''));
- $code = trim((string)$this->request->post('code', ''));
- if (!preg_match('/^1\d{10}$/', $phone)) {
- $this->error('手机号格式不正确');
- }
- if (!preg_match('/^\d{6}$/', $code)) {
- $this->error('请输入6位验证码');
- }
- // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
- $mock = Config::get('mproc.mock_sms_code');
- if ($mock !== null && $mock !== '' && (string)$mock === $code) {
- Cache::rm('mproc_code_' . $phone);
- } else {
- $cached = Cache::get('mproc_code_' . $phone);
- if ($cached === false || $cached === null || (string)$cached !== $code) {
- $this->error('验证码错误或已过期');
- }
- Cache::rm('mproc_code_' . $phone);
- }
- $cu = $this->mprocFindCustomerUserByMobile($phone);
- if (!$cu) {
- $this->error('该手机号未开通或已禁用,请联系管理员');
- }
- $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
- }
- /**
- * 用本地保存的 token 恢复登录态(POST:mproc_token)
- */
- public function mprocRestore()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $token = $this->mprocReadTokenFromRequest();
- $user = null;
- if ($token !== '') {
- $user = $this->mprocLoadUserByToken($token);
- }
- if (!$user) {
- $user = $this->mprocUserFromRememberCookie();
- if ($user) {
- $token = $this->mprocPackSignedAuthToken($user);
- }
- }
- if (!$user) {
- $this->error('登录已过期,请重新登录', url('index/index/login'));
- }
- $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
- $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
- $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
- $this->success('ok', $jump, [
- 'mproc_token' => $token,
- 'keep_hours' => $this->mprocKeepHours(),
- 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
- ]);
- }
- /**
- * 账号密码登录(POST:username、password)
- * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
- */
- public function doLoginPwd()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $username = trim((string)$this->request->post('username', ''));
- $password = (string)$this->request->post('password', '');
- if ($username === '' || $password === '') {
- $this->error('请输入账号和密码');
- }
- $cu = $this->mprocFindCustomerUserByUsername($username);
- if ($cu) {
- if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
- $this->error('账号或密码错误');
- }
- $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
- }
- // 管理员:表 admin
- $row = null;
- try {
- $row = Db::name('admin')
- ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
- ->where('username', $username)
- ->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row)) {
- $this->error('账号或密码错误');
- }
- $id = (int)($row['id'] ?? 0);
- if (($row['status'] ?? '') == 'hidden') {
- $this->error('该账号已禁用');
- }
- if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
- $this->error('登录失败次数过多,请24小时后再试');
- }
- $salt = (string)($row['salt'] ?? '');
- $hashStored = (string)($row['password'] ?? '');
- $hashInput = md5(md5($password) . $salt);
- if ($hashStored === '' || $hashInput !== $hashStored) {
- if ($id > 0) {
- try {
- Db::name('admin')->where('id', $id)->update([
- 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
- 'updatetime' => time(),
- ]);
- } catch (\Throwable $e) {
- }
- }
- $this->error('账号或密码错误');
- }
- if ($id > 0) {
- try {
- Db::name('admin')->where('id', $id)->update([
- 'loginfailure' => 0,
- 'updatetime' => time(),
- ]);
- } catch (\Throwable $e) {
- }
- }
- $this->mprocFinishLogin([
- 'phone' => trim((string)($row['mobile'] ?? '')),
- 'company_name' => '',
- 'username' => $username,
- 'customer_user_id' => 0,
- 'admin_id' => $id,
- 'login_type' => 'pwd',
- 'is_admin' => 1,
- ]);
- }
- /**
- * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
- * 仅普通用户(customer)可改;管理员(admin)仅可查看
- */
- protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
- {
- if (!empty($user['is_admin'])) {
- return false;
- }
- $sn = trim((string)($row['status_name'] ?? ''));
- if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
- return false;
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- // 手工询价无招标截止/开标限制
- if ($sid >= 0) {
- if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
- return false;
- }
- if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
- return false;
- }
- }
- $uCo = trim((string)($user['company_name'] ?? ''));
- if ($uCo === '') {
- $uPhone = trim((string)($user['phone'] ?? ''));
- if ($uPhone !== '') {
- $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
- }
- }
- $rCo = trim((string)($row['company_name'] ?? ''));
- if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
- return true;
- }
- $uPhone = trim((string)($user['phone'] ?? ''));
- $rPhone = trim((string)($row['phone'] ?? ''));
- return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
- }
- /**
- * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
- *
- * @param array<string, mixed> $detailRow
- */
- protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
- {
- $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
- $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
- if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (is_array($po)) {
- $pl = array_change_key_case($po, CASE_LOWER);
- foreach (['ceilingprice', 'ceiling_price'] as $ck) {
- if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
- $raw = trim((string)$pl[$ck]);
- break;
- }
- }
- if ($raw === '') {
- $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
- }
- }
- }
- if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
- return null;
- }
- return (float)$raw;
- }
- protected function mprocFormatCeilingPriceDisplay(float $n): string
- {
- $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
- return $s === '' ? '0' : $s;
- }
- /**
- * 确保 purchase_order_detail.lead_days 字段存在
- */
- protected function mprocEnsureLeadDaysColumn(): void
- {
- static $done = false;
- if ($done) {
- return;
- }
- $done = true;
- try {
- $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
- if (empty($cols)) {
- Db::execute(
- "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
- );
- }
- } catch (\Throwable $e) {
- // 忽略:保存时再按列是否存在处理
- }
- }
- /**
- * 交货日期相对今天的天数(可负数,调用方自行 clamp)
- */
- protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
- {
- if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
- return null;
- }
- $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
- $t2 = strtotime($m[1] . ' 00:00:00');
- if ($t1 === false || $t2 === false) {
- return null;
- }
- return (int)round(($t2 - $t1) / 86400);
- }
- protected function mprocAddDaysToToday(int $days): string
- {
- $base = strtotime(date('Y-m-d') . ' 00:00:00');
- if ($base === false) {
- $base = time();
- }
- return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocEnrichLeadDaysDisplay(array &$row): void
- {
- $days = null;
- $raw = $row['lead_days'] ?? null;
- if ($raw !== null && $raw !== '' && is_numeric($raw)) {
- $days = max(0, (int)$raw);
- } else {
- $dd = trim((string)($row['delivery_display'] ?? ''));
- if ($dd === '') {
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
- $dd = $m[1];
- }
- }
- if ($dd !== '') {
- $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
- if ($calc !== null) {
- $days = max(0, $calc);
- }
- }
- }
- if ($days !== null) {
- $row['lead_days'] = $days;
- $row['lead_days_display'] = (string)$days;
- $row['lead_days_missing'] = 0;
- } else {
- $row['lead_days'] = '';
- $row['lead_days_display'] = '';
- $row['lead_days_missing'] = 1;
- }
- }
- /**
- * 保存单条协助明细的金额、交期、工期(内部)
- *
- * @param array<string, mixed> $user
- * @param int $id
- * @param string $amountRaw
- * @param string $deliveryRaw
- * @param string|int|null $leadDaysRaw
- * @return string 工序名(用于批量错误提示)
- */
- protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
- {
- if ($id <= 0) {
- throw new \InvalidArgumentException('参数错误');
- }
- $row = null;
- try {
- $row = Db::table('purchase_order_detail')->where('id', $id)->find();
- if (!$row) {
- $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
- }
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row)) {
- throw new \InvalidArgumentException('记录不存在');
- }
- $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $po = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (is_array($po)) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $po);
- if ($gymc === '') {
- $gymc = trim((string)($row['CGYMC'] ?? ''));
- }
- }
- }
- $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
- if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- throw new \InvalidArgumentException($label . '已结束,不能再修改');
- }
- $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
- if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
- if (!empty($user['is_admin'])) {
- throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
- }
- // 截止后 / 已开标 canEdit=false,统一给明确文案
- if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
- throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
- }
- if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
- throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
- }
- throw new \InvalidArgumentException($label . '无权修改');
- }
- $this->mprocEnsureLeadDaysColumn();
- $amountRaw = trim($amountRaw);
- $deliveryRaw = trim($deliveryRaw);
- $leadRaw = trim((string)($leadDaysRaw ?? ''));
- $hasAmt = $amountRaw !== '';
- $hasLead = $leadRaw !== '';
- $hasDel = $deliveryRaw !== '';
- $isManualRfq = ($sid < 0);
- if ($isManualRfq) {
- // 手工询价:只需填写单价
- if (!$hasAmt) {
- throw new \InvalidArgumentException($label . '请填写单价');
- }
- } else {
- $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
- if ($filledCount === 0) {
- throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
- }
- if ($filledCount < 3) {
- if (!$hasAmt) {
- throw new \InvalidArgumentException($label . '请填写单价');
- }
- if (!$hasLead) {
- throw new \InvalidArgumentException($label . '请填写工期');
- }
- throw new \InvalidArgumentException($label . '请填写交期');
- }
- }
- $leadDays = null;
- if ($leadRaw !== '') {
- if (!preg_match('/^\d+$/', $leadRaw)) {
- throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
- }
- $leadDays = (int)$leadRaw;
- }
- $data = [];
- if ($amountRaw === '') {
- $data['amount'] = null;
- } else {
- if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
- throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
- }
- if ((float)$amountRaw <= 0) {
- throw new \InvalidArgumentException($label . '单价必须大于0');
- }
- $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
- if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
- throw new \InvalidArgumentException(
- $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
- );
- }
- $data['amount'] = $amountRaw;
- }
- if ($deliveryRaw === '') {
- $data['delivery'] = null;
- } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
- $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- $timePart = date('H:i:s');
- if ($existingDel !== '') {
- $tsEx = strtotime(str_replace('T', ' ', $existingDel));
- if ($tsEx !== false) {
- $hms = date('H:i:s', $tsEx);
- if ($hms !== '00:00:00') {
- $timePart = $hms;
- }
- }
- }
- $data['delivery'] = $deliveryRaw . ' ' . $timePart;
- } else {
- $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
- $ts = strtotime($deliveryRaw);
- if ($ts === false) {
- throw new \InvalidArgumentException($label . '交期时间格式不正确');
- }
- $data['delivery'] = date('Y-m-d H:i:s', $ts);
- }
- // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
- if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
- $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
- }
- if ($leadDays === null && !empty($data['delivery'])) {
- $ymd = substr((string)$data['delivery'], 0, 10);
- $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
- if ($calc !== null) {
- $leadDays = max(0, $calc);
- }
- }
- $data['lead_days'] = $leadDays;
- $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
- if ($dcCol !== null) {
- $shouldStampQuoteTime = false;
- if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
- $shouldStampQuoteTime = true;
- }
- // 手工询价只填单价:有单价也记报价时间
- if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
- $shouldStampQuoteTime = true;
- }
- if ($shouldStampQuoteTime) {
- $data[$dcCol] = date('Y-m-d H:i:s');
- }
- }
- $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
- if ($upCol !== null) {
- $data[$upCol] = date('Y-m-d H:i:s');
- }
- $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
- if ($statusNameCol !== null) {
- $curSn = '';
- foreach ($row as $k => $v) {
- if (strcasecmp((string)$k, $statusNameCol) === 0) {
- $curSn = trim((string)$v);
- break;
- }
- }
- if ($curSn !== '已完成') {
- $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
- $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
- $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
- $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
- $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
- }
- }
- $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
- $pkVal = (int)($row[$pkField] ?? $id);
- try {
- $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
- } catch (\Throwable $e) {
- $msg = $e->getMessage();
- if (stripos($msg, 'Unknown column') !== false) {
- $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
- }
- throw new \RuntimeException('保存失败:' . $msg);
- }
- if ($aff === false) {
- throw new \RuntimeException($label . '保存失败');
- }
- return $gymc;
- }
- /**
- * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
- *
- * @param array<string, mixed> $user
- * @param int[] $detailIds 本次保存涉及的明细 ID
- * @param string $remarkRaw
- */
- protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
- {
- $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
- if ($remarkCol === null) {
- return;
- }
- $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
- if ($detailIds === []) {
- return;
- }
- $anchorId = $detailIds[0];
- $row = null;
- try {
- $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
- if (!$row) {
- $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
- }
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row)) {
- throw new \InvalidArgumentException('记录不存在');
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $po = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (is_array($po)) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $po);
- }
- }
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
- if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- throw new \InvalidArgumentException('订单已结束,不能再修改备注');
- }
- $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
- if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
- if (!empty($user['is_admin'])) {
- throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
- }
- if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
- throw new \InvalidArgumentException('已开标验证,不可再提交');
- }
- if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
- throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
- }
- throw new \InvalidArgumentException('无权修改备注');
- }
- $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
- $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
- if ($ccydhCol === null || $companyCol === null) {
- return;
- }
- $ccydh = '';
- $company = '';
- foreach ($row as $k => $v) {
- if (strcasecmp((string)$k, $ccydhCol) === 0) {
- $ccydh = trim((string)$v);
- } elseif (strcasecmp((string)$k, $companyCol) === 0) {
- $company = trim((string)$v);
- }
- }
- if ($ccydh === '' || $company === '') {
- $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
- $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
- $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
- if ($upCol !== null) {
- $data[$upCol] = date('Y-m-d H:i:s');
- }
- Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
- return;
- }
- $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
- $data = [$remarkCol => $remarkVal];
- $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
- if ($upCol !== null) {
- $data[$upCol] = date('Y-m-d H:i:s');
- }
- $query = Db::table('purchase_order_detail')
- ->where($ccydhCol, $ccydh)
- ->where($companyCol, $company);
- $userWhere = $this->mprocListWhereForLoginUser($user);
- if ($userWhere !== []) {
- $query->where($userWhere);
- }
- try {
- $query->update($data);
- } catch (\Throwable $e) {
- throw new \RuntimeException('备注保存失败:' . $e->getMessage());
- }
- }
- /**
- * 保存协助明细金额、交期、工期
- * 单条:POST id、amount、delivery、lead_days
- * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
- */
- public function mprocSave()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 " 导致解析失败
- $itemsRaw = $this->request->post('items', '', null);
- if ($itemsRaw === '' || $itemsRaw === null) {
- $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
- }
- if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '"') !== false) {
- $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
- }
- $items = [];
- if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
- $decoded = json_decode($itemsRaw, true);
- if (!is_array($decoded)) {
- $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
- }
- if (is_array($decoded)) {
- $items = $decoded;
- }
- } elseif (is_array($itemsRaw)) {
- $items = $itemsRaw;
- }
- if ($items === []) {
- $id = (int)$this->request->post('id', 0, null);
- if ($id <= 0) {
- $this->error('保存失败,请关闭弹窗后重试');
- }
- $items = [[
- 'id' => $id,
- 'amount' => (string)$this->request->post('amount', '', null),
- 'delivery' => (string)$this->request->post('delivery', '', null),
- 'lead_days' => (string)$this->request->post('lead_days', '', null),
- ]];
- }
- $saved = 0;
- $savedIds = [];
- $remarkRaw = $this->request->post('remark', '', null);
- if ($remarkRaw === '' || $remarkRaw === null) {
- $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
- }
- $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
- Db::startTrans();
- try {
- foreach ($items as $it) {
- if (!is_array($it)) {
- continue;
- }
- $id = (int)($it['id'] ?? $it['eid'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- $delivery = (string)($it['delivery'] ?? '');
- // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
- if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
- $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
- }
- $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
- $amount = trim((string)($it['amount'] ?? ''));
- $leadDays = trim($leadDays);
- $delivery = trim($delivery);
- // 全空工序跳过:多工序时允许只保存已填全的
- if ($amount === '' && $leadDays === '' && $delivery === '') {
- continue;
- }
- $this->mprocSaveDetailQuote(
- $user,
- $id,
- $amount,
- $delivery,
- $leadDays
- );
- $saved++;
- $savedIds[] = $id;
- }
- if ($saved < 1) {
- throw new \InvalidArgumentException('请填写单价、工期、交期');
- }
- $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
- Db::commit();
- } catch (\InvalidArgumentException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
- }
- /**
- * 普通用户修改密码(POST:old_password、new_password、renew_password)
- */
- public function mprocChangePwd()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- $user = $this->mprocSyncSessionCustomerUser($user);
- if (!empty($user['is_admin'])) {
- $this->error('当前账号不支持修改密码');
- }
- $cu = $this->mprocResolveCustomerUserForSession($user);
- if (!$cu) {
- $this->error('账号不存在或已禁用');
- }
- $oldPwd = (string)$this->request->post('old_password', '');
- $newPwd = (string)$this->request->post('new_password', '');
- $renewPwd = (string)$this->request->post('renew_password', '');
- if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
- $this->error('请填写完整');
- }
- $pwdErr = $this->mprocValidateStrongPassword($newPwd);
- if ($pwdErr !== '') {
- $this->error($pwdErr);
- }
- if ($newPwd !== $renewPwd) {
- $this->error('两次输入的新密码不一致');
- }
- if ($oldPwd === $newPwd) {
- $this->error('新密码不能与旧密码相同');
- }
- $cuId = (int)($cu['id'] ?? 0);
- if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
- $this->error('原密码不正确');
- }
- $data = [
- 'password' => $this->mprocHashCustomerUserPassword($newPwd),
- 'updatetime' => date('Y-m-d H:i:s'),
- ];
- try {
- Db::table('customer')->where('id', $cuId)->update($data);
- } catch (\Throwable $e) {
- $this->error('修改失败:' . $e->getMessage());
- }
- // 改密后强制重新登录
- $token = Session::get('mproc_token');
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_token');
- }
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_remember');
- }
- $this->mprocClearLogin((string)$token);
- $this->success('密码已修改,请重新登录', url('index/index/login'));
- }
- /**
- * 退出登录
- */
- public function logout()
- {
- $token = Session::get('mproc_token');
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_token');
- }
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_remember');
- }
- // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
- $this->mprocClearLogin((string)$token);
- $this->redirect(url('index/index/login'));
- }
- /**
- * 短信宝(与后台协助审核一致,便于复用账号)
- *
- * @throws \Exception
- */
- protected function mprocSmsSend($phone, $content)
- {
- $statusStr = [
- '0' => '短信发送成功',
- '-1' => '参数不全',
- '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
- '30' => '密码错误',
- '40' => '账号不存在',
- '41' => '余额不足',
- '42' => '帐户已过期',
- '43' => 'IP地址限制',
- '50' => '内容含有敏感词',
- ];
- $smsapi = 'http://api.smsbao.com/';
- $user = trim((string)Config::get('mproc.smsbao_user'));
- if ($user === '') {
- $user = 'zhuwei123';
- }
- $passPlain = Config::get('mproc.smsbao_pass');
- $pass = ($passPlain !== null && $passPlain !== '')
- ? md5((string)$passPlain)
- : md5('1d1e605c101e4c1f8a156c6d7b19f126');
- $phone = trim((string)$phone);
- $content = trim((string)$content);
- if ($phone === '' || $content === '') {
- throw new \Exception('短信发送失败:参数不全');
- }
- $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
- $result = @file_get_contents($sendurl);
- if ($result === false) {
- Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
- throw new \Exception('短信发送失败:网络异常');
- }
- $result = trim((string)$result);
- if ($result !== '0') {
- $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
- Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
- throw new \Exception('短信发送失败:' . $msg);
- }
- Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
- }
- /**
- * 质量评分页(仅管理员)
- */
- public function inboundscore()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- if (empty($user['is_admin'])) {
- $this->redirect(url('index/index/index', '', '', true));
- return;
- }
- $this->mprocEnsureInboundScoreTable();
- $q = trim((string)$this->request->get('q', ''));
- $profile = $this->mprocProfileForUser($user);
- $this->view->assign('mprocSearchQ', $q);
- $this->view->assign('mprocProfile', $profile);
- $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
- $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
- $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0)));
- return $this->view->fetch();
- }
- /**
- * 质量评分列表 JSON(仅管理员;tab=pending|scored)
- * scored 仅返回当前账号操作过的已评分记录
- */
- public function inboundscorelist()
- {
- $user = $this->mprocRequireAdminUser();
- $this->mprocEnsureInboundScoreTable();
- $q = trim((string)$this->request->request('q', ''));
- $tab = trim((string)$this->request->request('tab', 'pending'));
- if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
- $tab = 'pending';
- }
- // 兼容旧 tab:合格/不合格并入已评分
- if ($tab === 'pass' || $tab === 'fail') {
- $tab = 'scored';
- }
- $adminId = (int)($user['admin_id'] ?? 0);
- $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId);
- $this->success('ok', '', [
- 'tab' => $tab,
- 'q' => $q,
- 'rows' => $rows,
- 'count' => count($rows),
- ]);
- }
- /**
- * 保存质量评分(仅管理员)
- * POST:ccydh 或 scydgy_id、result=合格|不合格、delivery_status=准时|滞后、customer_complaint=0|1、order_interrupt=0|1、remark
- * 同一订单号下多道工序一并评分、一并完结(与历史存证一单一行一致)
- */
- public function inboundscoresave()
- {
- $user = $this->mprocRequireAdminUser();
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $this->mprocEnsureInboundScoreTable();
- $ccydh = trim((string)$this->request->post('ccydh', ''));
- $sid = (int)$this->request->post('scydgy_id', 0);
- $result = trim((string)$this->request->post('result', ''));
- if ($result !== '合格' && $result !== '不合格') {
- $this->error('请选择是否合格');
- }
- $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
- if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
- $this->error('请选择交货情况');
- }
- $customerComplaint = (int)$this->request->post('customer_complaint', -1);
- $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
- if ($customerComplaint !== 0 && $customerComplaint !== 1) {
- $this->error('请选择客户是否投诉');
- }
- if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
- $this->error('请选择订单是否中断');
- }
- $remark = trim((string)$this->request->post('remark', ''));
- if ($result === '不合格' && $remark === '') {
- $this->error('请填写不合格原因');
- }
- if (mb_strlen($remark) > 500) {
- $remark = mb_substr($remark, 0, 500);
- }
- $approvedVals = ProcuremenStatus::wflowApprovedValues();
- $approvedIn = implode(',', array_map(static function ($v) {
- return "'" . str_replace("'", "''", (string)$v) . "'";
- }, $approvedVals));
- try {
- $q = Db::table('purchase_order')
- ->where('scydgy_id', '>', 0)
- ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
- ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name,pick_time,wflow_status,status');
- if ($ccydh !== '') {
- $q->where('CCYDH', $ccydh);
- } elseif ($sid > 0) {
- $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
- $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
- if ($ccydh === '') {
- $this->error('缺少订单号');
- }
- $q->where('CCYDH', $ccydh);
- } else {
- $this->error('缺少订单号');
- }
- $poRows = $q->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $poRows = [];
- }
- if (!is_array($poRows) || $poRows === []) {
- $this->error('未找到可评分的已审核订单');
- }
- $now = date('Y-m-d H:i:s');
- $adminId = (int)($user['admin_id'] ?? 0);
- // 操作日志记昵称,不用登录账号
- $adminName = '';
- if ($adminId > 0) {
- try {
- $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
- if (is_array($adminRow)) {
- $adminName = trim((string)($adminRow['nickname'] ?? ''));
- if ($adminName === '') {
- $adminName = trim((string)($adminRow['username'] ?? ''));
- }
- }
- } catch (\Throwable $e) {
- }
- }
- if ($adminName === '') {
- $adminName = trim((string)($user['username'] ?? ''));
- }
- if ($adminName === '') {
- $adminName = '管理员';
- }
- $saved = 0;
- $firstSid = 0;
- $firstPoId = 0;
- try {
- Db::startTrans();
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $rowSid = (int)($po['scydgy_id'] ?? 0);
- if ($rowSid <= 0) {
- continue;
- }
- if ($firstSid <= 0) {
- $firstSid = $rowSid;
- $firstPoId = (int)($po['id'] ?? 0);
- }
- $g = trim((string)($po['CGYMC'] ?? ''));
- $data = [
- 'scydgy_id' => $rowSid,
- 'purchase_order_id' => (int)($po['id'] ?? 0),
- 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
- 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
- 'cgymc' => $g,
- 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
- 'result' => $result,
- 'delivery_status' => $deliveryStatus,
- 'customer_complaint' => $customerComplaint,
- 'order_interrupt' => $orderInterrupt,
- 'remark' => $remark,
- 'admin_id' => $adminId,
- 'admin_name' => $adminName,
- 'updatetime' => $now,
- ];
- $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
- if (is_array($exist) && $exist !== []) {
- Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
- } else {
- $data['createtime'] = $now;
- Db::table('purchase_order_inbound_score')->insert($data);
- }
- Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
- 'status' => ProcuremenStatus::PO_COMPLETED,
- ]);
- $saved++;
- }
- if ($saved < 1) {
- throw new \RuntimeException('没有可保存的工序');
- }
- Db::commit();
- } catch (\Throwable $e) {
- try {
- Db::rollback();
- } catch (\Throwable $e2) {
- }
- Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
- $this->error('保存失败,请稍后重试');
- }
- $logDetail = '质量评分:是否合格=' . $result
- . ';交货情况=' . $deliveryStatus
- . ';客户投诉:' . ($customerComplaint === 1 ? '是' : '否')
- . ';订单中断:' . ($orderInterrupt === 1 ? '是' : '否');
- if ($remark !== '') {
- $logDetail .= ';备注:' . $remark;
- }
- \app\common\library\ProcuremenOperLog::write(
- $firstSid,
- 'inbound_score',
- $logDetail,
- $firstPoId > 0 ? $firstPoId : null,
- [$adminId, $adminName]
- );
- // 按入库合格/不合格重算该供应商当月质量得分
- $companyName = '';
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $companyName = trim((string)($po['pick_company_name'] ?? ''));
- if ($companyName !== '') {
- break;
- }
- }
- $scoreYm = date('Y-m', strtotime($now) ?: time());
- if ($companyName !== '') {
- try {
- \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
- } catch (\Throwable $e) {
- Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
- }
- }
- $this->success('操作成功', '', [
- 'ccydh' => $ccydh,
- 'result' => $result,
- 'delivery_status' => $deliveryStatus,
- 'customer_complaint' => $customerComplaint,
- 'order_interrupt' => $orderInterrupt,
- 'remark' => $remark,
- 'count' => $saved,
- 'status' => '已完结',
- ]);
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocRequireAdminUser(): array
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- if (empty($user['is_admin'])) {
- $this->error('仅系统管理员可操作');
- }
- return $user;
- }
- protected function mprocEnsureInboundScoreTable(): void
- {
- static $ok = false;
- if ($ok) {
- return;
- }
- try {
- Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
- } catch (\Throwable $e) {
- try {
- Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
- `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
- `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
- `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
- `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
- `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
- `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
- `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
- `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
- `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
- `admin_id` int unsigned NOT NULL DEFAULT 0,
- `admin_name` varchar(64) NOT NULL DEFAULT '',
- `remark` varchar(500) NOT NULL DEFAULT '',
- `createtime` datetime DEFAULT NULL,
- `updatetime` datetime DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
- KEY `idx_ccydh` (`ccydh`),
- KEY `idx_result` (`result`),
- KEY `idx_updatetime` (`updatetime`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
- } catch (\Throwable $e2) {
- Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
- return;
- }
- }
- foreach ([
- 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
- 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `delivery_status`",
- 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `customer_complaint`",
- ] as $col => $ddl) {
- try {
- $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
- if (!is_array($cols) || $cols === []) {
- Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
- }
- } catch (\Throwable $e) {
- Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
- }
- }
- $ok = true;
- }
- /**
- * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
- * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0): array
- {
- $this->mprocEnsureInboundScoreTable();
- $keyword = trim($keyword);
- if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
- $tab = 'pending';
- }
- if ($tab === 'pass' || $tab === 'fail') {
- $tab = 'scored';
- }
- try {
- $approvedVals = ProcuremenStatus::wflowApprovedValues();
- $approvedIn = implode(',', array_map(static function ($v) {
- return "'" . str_replace("'", "''", (string)$v) . "'";
- }, $approvedVals));
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', '>', 0)
- ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
- ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,pick_company_name,pick_time,wflow_status,status')
- ->order('pick_time', 'desc')
- ->order('id', 'asc')
- ->limit(800)
- ->select();
- } catch (\Throwable $e) {
- Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
- return [];
- }
- if (!is_array($poRows) || $poRows === []) {
- return [];
- }
- $sids = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($sid > 0) {
- $sids[$sid] = true;
- }
- }
- $scoreMap = [];
- if ($sids !== []) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
- ->select();
- } catch (\Throwable $e) {
- $scores = [];
- }
- if (is_array($scores)) {
- foreach ($scores as $sc) {
- if (!is_array($sc)) {
- continue;
- }
- $sid = (int)($sc['scydgy_id'] ?? 0);
- if ($sid > 0) {
- $scoreMap[$sid] = $sc;
- }
- }
- }
- }
- /** @var array<string, array<string, mixed>> $groups */
- $groups = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- $ccydh = trim((string)($po['CCYDH'] ?? ''));
- if ($sid <= 0 || $ccydh === '') {
- continue;
- }
- if (!isset($groups[$ccydh])) {
- $pickRaw = trim((string)($po['pick_time'] ?? ''));
- $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
- $groups[$ccydh] = [
- 'CCYDH' => $ccydh,
- 'scydgy_id' => $sid,
- 'scydgy_ids' => [],
- 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
- 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
- 'CGYMC_list' => [],
- 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
- 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
- 'pick_time_raw' => $pickRaw,
- 'process_count' => 0,
- 'results' => [],
- 'score_admin_ids' => [],
- 'score_time_raw' => '',
- 'customer_complaint'=> 0,
- 'order_interrupt' => 0,
- 'delivery_status' => '',
- 'remark' => '',
- ];
- }
- $g = &$groups[$ccydh];
- $g['scydgy_ids'][] = $sid;
- $g['process_count']++;
- if ($g['scydgy_id'] <= 0) {
- $g['scydgy_id'] = $sid;
- }
- if ($g['CYJMC'] === '') {
- $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
- }
- if ($g['CCLBMMC'] === '') {
- $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
- }
- if ($g['pick_company_name'] === '') {
- $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
- }
- $pt = trim((string)($po['pick_time'] ?? ''));
- if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
- $g['pick_time_raw'] = $pt;
- $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
- $g['pick_time'] = $disp !== '' ? $disp : $pt;
- }
- $gymc = trim((string)($po['CGYMC'] ?? ''));
- if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
- $g['CGYMC_list'][] = $gymc;
- }
- $sc = $scoreMap[$sid] ?? null;
- $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
- $g['results'][] = $res;
- if (is_array($sc) && $res !== '') {
- $aid = (int)($sc['admin_id'] ?? 0);
- if ($aid > 0) {
- $g['score_admin_ids'][$aid] = true;
- }
- if ((int)($sc['customer_complaint'] ?? 0) === 1) {
- $g['customer_complaint'] = 1;
- }
- if ((int)($sc['order_interrupt'] ?? 0) === 1) {
- $g['order_interrupt'] = 1;
- }
- $ds = trim((string)($sc['delivery_status'] ?? ''));
- if ($ds !== '' && $g['delivery_status'] === '') {
- $g['delivery_status'] = $ds;
- }
- $rm = trim((string)($sc['remark'] ?? ''));
- if ($rm !== '' && $g['remark'] === '') {
- $g['remark'] = $rm;
- }
- $st = trim((string)($sc['updatetime'] ?? ''));
- if ($st === '') {
- $st = trim((string)($sc['createtime'] ?? ''));
- }
- if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
- $g['score_time_raw'] = $st;
- }
- }
- unset($g);
- }
- $out = [];
- foreach ($groups as $ccydh => $g) {
- $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
- $company = (string)($g['pick_company_name'] ?? '');
- $cyjmc = (string)($g['CYJMC'] ?? '');
- if ($keyword !== '') {
- $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
- if (mb_stripos($blob, $keyword) === false) {
- continue;
- }
- }
- $results = is_array($g['results'] ?? null) ? $g['results'] : [];
- $uniq = [];
- $allScored = true;
- foreach ($results as $r) {
- $r = trim((string)$r);
- if ($r === '') {
- $allScored = false;
- continue;
- }
- $uniq[$r] = true;
- }
- $orderResult = '';
- if ($allScored && count($uniq) === 1) {
- $keys = array_keys($uniq);
- $orderResult = (string)($keys[0] ?? '');
- } elseif ($allScored && count($uniq) > 1) {
- $orderResult = '';
- }
- if ($tab === 'pending' && $orderResult !== '') {
- continue;
- }
- if ($tab === 'scored') {
- if ($orderResult !== '合格' && $orderResult !== '不合格') {
- continue;
- }
- // 已评分:仅当前账号操作过的
- if ($adminId <= 0) {
- continue;
- }
- $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
- if (empty($adminIds[$adminId])) {
- continue;
- }
- }
- $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
- $scoreTime = $scoreTimeRaw !== ''
- ? \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw)
- : '';
- $out[] = [
- 'CCYDH' => $ccydh,
- 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
- 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
- 'CYJMC' => $cyjmc,
- 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
- 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
- 'pick_company_name' => $company,
- 'pick_time' => (string)($g['pick_time'] ?? ''),
- 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
- 'score_time_raw' => $scoreTimeRaw,
- 'process_count' => (int)($g['process_count'] ?? 0),
- 'result' => $orderResult,
- 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
- 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
- 'delivery_status' => (string)($g['delivery_status'] ?? ''),
- 'remark' => (string)($g['remark'] ?? ''),
- ];
- }
- usort($out, static function ($a, $b) use ($tab) {
- if ($tab === 'scored') {
- $ta = (string)($a['score_time_raw'] ?? '');
- $tb = (string)($b['score_time_raw'] ?? '');
- if ($ta !== $tb) {
- return strcmp($tb, $ta);
- }
- }
- $ta = (string)($a['pick_time'] ?? '');
- $tb = (string)($b['pick_time'] ?? '');
- if ($ta !== $tb) {
- return strcmp($tb, $ta);
- }
- return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
- });
- return $out;
- }
- }
|